Skip to main content

sql_splitter/profile/
profiler.rs

1//! Stream a SQL dump into a neutral [`DumpProfile`] in a single pass.
2//!
3//! [`DumpProfiler`] drives the production parser's [`Parser::visit_events`]
4//! visitor: DDL statements build schema evidence as they arrive, and each
5//! decoded data row is routed — value by value, by column identity — into the
6//! per-column bounded sketches from [`crate::profile::sketches`]. Nothing here
7//! buffers a whole INSERT/COPY block: the visitor delivers one tuple / one COPY
8//! line at a time, so resident memory is bounded by the [`ProfileBudget`], never
9//! by the row count.
10//!
11//! # Depths
12//! * [`ProfileDepth::Schema`] reads no non-null values — it counts rows and,
13//!   per column, total/null tallies when the schema is available, producing
14//!   the portable schema with no value-derived evidence.
15//! * [`ProfileDepth::Basic`] adds the cheap per-column metrics: distinct
16//!   estimate, min/max, quantiles, string shape, length, top-k, and a bounded
17//!   sample.
18//! * [`ProfileDepth::Full`] additionally computes pairwise evidence for the
19//!   *bounded* candidate set: declared foreign-key pairs (child→parent coverage)
20//!   and same-table temporal orderings. Planner-nominated pairs plug in through
21//!   the same [`RelationshipEvidence`] surface.
22//!
23//! Every depth returns the *same* portable schema and exact table row counts.
24//! Schema-late data that exceeds its bounded replay buffer retains partial
25//! column evidence; the table and column confidence values report that gap.
26//! The depths otherwise differ only in how much value-derived evidence they
27//! attach.
28
29use std::collections::HashSet;
30use std::io::Read;
31use std::path::Path;
32
33use ahash::AHashMap;
34
35use crate::diagnostic::{codes, Diagnostic};
36use crate::parser::mysql_insert::{
37    hash_pk_tuple, parse_insert_tuple, InsertRowContext, ParsedRow, PkTuple, PkValue, RowExtraction,
38};
39use crate::parser::postgres_copy::{parse_copy_columns, CopyParser, ParsedCopyRow};
40use crate::parser::{
41    detect_dialect_from_file, determine_buffer_size, Parser, ParserEvent, RowFlow, SqlDialect,
42    StatementType, SMALL_BUFFER_SIZE,
43};
44use crate::schema::{Column, ColumnType, Schema, SchemaBuilder, TableId, TableSchema};
45use crate::synthetic::schema::PortableSchema;
46
47use super::evidence::{ColumnEvidence, DumpProfile, RelationshipEvidence, TableEvidence};
48use super::{ColumnSketches, ProfileBudget, ProfileDepth, ProfileValue};
49
50/// Streams a SQL dump into a [`DumpProfile`]. Build one with
51/// [`DumpProfiler::builder`].
52#[derive(Debug, Clone)]
53pub struct DumpProfiler {
54    depth: ProfileDepth,
55    budget: ProfileBudget,
56    seed: u64,
57    dialect: Option<SqlDialect>,
58}
59
60impl Default for DumpProfiler {
61    fn default() -> Self {
62        Self {
63            depth: ProfileDepth::Full,
64            budget: ProfileBudget::default(),
65            seed: 0,
66            dialect: None,
67        }
68    }
69}
70
71impl DumpProfiler {
72    /// Start configuring a profiler.
73    pub fn builder() -> DumpProfilerBuilder {
74        DumpProfilerBuilder::default()
75    }
76
77    /// Profile a dump on disk. Opens the file through the shared input layer
78    /// (transparent decompression / zip), and auto-detects the dialect from the
79    /// header unless one was configured on the builder.
80    pub fn profile_path(&self, path: &Path) -> anyhow::Result<DumpProfile> {
81        let dialect = match self.dialect {
82            Some(d) => d,
83            None => detect_dialect_from_file(path)?.dialect,
84        };
85        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
86        let buffer_size = determine_buffer_size(file_size);
87        let reader = crate::splitter::open_input(path)?;
88        self.run(reader, dialect, buffer_size)
89    }
90
91    /// Profile a dump from an arbitrary reader. The dialect must be given
92    /// explicitly (there is no file header to sniff a compressed input from).
93    pub fn profile_reader<R: Read>(
94        &self,
95        reader: R,
96        dialect: SqlDialect,
97    ) -> anyhow::Result<DumpProfile> {
98        self.run(reader, dialect, SMALL_BUFFER_SIZE)
99    }
100
101    fn run<R: Read>(
102        &self,
103        reader: R,
104        dialect: SqlDialect,
105        buffer_size: usize,
106    ) -> anyhow::Result<DumpProfile> {
107        let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
108        let mut run = ProfileRun::new(self.depth, self.budget, self.seed, dialect);
109        parser.visit_events(|event| run.on_event(event))?;
110        Ok(run.finish())
111    }
112}
113
114/// Builder for [`DumpProfiler`].
115#[derive(Debug, Clone, Default)]
116pub struct DumpProfilerBuilder {
117    inner: DumpProfilerConfig,
118}
119
120// A small config carrier so the builder can start from `Default` without
121// exposing the profiler's private fields.
122#[derive(Debug, Clone)]
123struct DumpProfilerConfig {
124    depth: ProfileDepth,
125    budget: ProfileBudget,
126    seed: u64,
127    dialect: Option<SqlDialect>,
128}
129
130impl Default for DumpProfilerConfig {
131    fn default() -> Self {
132        let d = DumpProfiler::default();
133        Self {
134            depth: d.depth,
135            budget: d.budget,
136            seed: d.seed,
137            dialect: d.dialect,
138        }
139    }
140}
141
142impl DumpProfilerBuilder {
143    /// How deep to profile (default [`ProfileDepth::Full`]).
144    pub fn depth(mut self, depth: ProfileDepth) -> Self {
145        self.inner.depth = depth;
146        self
147    }
148
149    /// Per-column retention budget (default [`ProfileBudget::default`]).
150    pub fn budget(mut self, budget: ProfileBudget) -> Self {
151        self.inner.budget = budget;
152        self
153    }
154
155    /// Seed for the reservoir sampler, making retained samples reproducible.
156    pub fn seed(mut self, seed: u64) -> Self {
157        self.inner.seed = seed;
158        self
159    }
160
161    /// Force a SQL dialect instead of auto-detecting from the file header.
162    pub fn dialect(mut self, dialect: SqlDialect) -> Self {
163        self.inner.dialect = Some(dialect);
164        self
165    }
166
167    /// Finalize the profiler.
168    pub fn build(self) -> DumpProfiler {
169        DumpProfiler {
170            depth: self.inner.depth,
171            budget: self.inner.budget,
172            seed: self.inner.seed,
173            dialect: self.inner.dialect,
174        }
175    }
176}
177
178// ---------------------------------------------------------------------------
179// Streaming run state
180// ---------------------------------------------------------------------------
181
182/// Coarse column family, derived once from the schema so row observation never
183/// has to re-borrow the schema to decide how to interpret a value.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185enum ColumnKind {
186    Bool,
187    Int,
188    BigInt,
189    Decimal,
190    DateTime,
191    Json,
192    Text,
193}
194
195impl ColumnKind {
196    fn from_column(col: &Column) -> Self {
197        if col.source_type.to_ascii_lowercase().contains("json") {
198            return ColumnKind::Json;
199        }
200        match col.col_type {
201            ColumnType::Bool => ColumnKind::Bool,
202            ColumnType::Int => ColumnKind::Int,
203            ColumnType::BigInt => ColumnKind::BigInt,
204            ColumnType::Decimal => ColumnKind::Decimal,
205            ColumnType::DateTime => ColumnKind::DateTime,
206            ColumnType::Text | ColumnType::Uuid | ColumnType::Other(_) => ColumnKind::Text,
207        }
208    }
209}
210
211/// Per-column accumulator: observed total/null tallies at every depth, plus
212/// the value sketches at [`ProfileDepth::Basic`] and above.
213struct ColumnAccum {
214    name: String,
215    kind: ColumnKind,
216    total: u64,
217    nulls: u64,
218    sketches: Option<ColumnSketches>,
219}
220
221/// A same-table pair of timestamp columns, tracked for temporal ordering
222/// (`from <= to`) at [`ProfileDepth::Full`].
223struct TemporalPair {
224    from: usize,
225    to: usize,
226    both_present: u64,
227    ordered: u64,
228}
229
230/// A budget-capped set of 64-bit value hashes. Once full it stops inserting and
231/// records that it overflowed, so retention never scales with the row count.
232struct BoundedHashSet {
233    set: HashSet<u64>,
234    cap: usize,
235    overflowed: bool,
236}
237
238impl BoundedHashSet {
239    fn new(cap: usize) -> Self {
240        Self {
241            set: HashSet::new(),
242            cap: cap.max(1),
243            overflowed: false,
244        }
245    }
246
247    fn insert(&mut self, hash: u64) {
248        if self.set.len() < self.cap {
249            self.set.insert(hash);
250        } else if !self.set.contains(&hash) {
251            self.overflowed = true;
252        }
253    }
254
255    fn contains(&self, hash: u64) -> bool {
256        self.set.contains(&hash)
257    }
258
259    fn is_empty(&self) -> bool {
260        self.set.is_empty()
261    }
262}
263
264/// A declared foreign key reduced to the local column ordinals that carry its
265/// child values, so coverage can be tracked without re-borrowing the schema per
266/// row. `referenced_table_id` is resolved only at `build()`, so we key by
267/// `fk_index` and resolve the parent at finish.
268struct FkCandidate {
269    fk_index: u16,
270    ordinals: Vec<usize>,
271}
272
273/// Per-table profiling state.
274struct TableProfile {
275    name: String,
276    table_id: TableId,
277    row_count: u64,
278    /// Rows that contributed column evidence. This can be below `row_count`
279    /// when schema-late input overflowed the bounded replay buffer or when a
280    /// delivered row could not be decoded.
281    profiled_row_count: u64,
282    columns: Vec<ColumnAccum>,
283    // Full-depth relationship tracking (empty otherwise).
284    pk_hashes: BoundedHashSet,
285    fk_candidates: Vec<FkCandidate>,
286    fk_child: AHashMap<u16, BoundedHashSet>,
287    temporal: Vec<TemporalPair>,
288    /// Whether a `GEN-PROFILE-DECODE-SKIPPED` warning has already been raised for
289    /// this table, so a run of undecodable rows warns once, not per row.
290    decode_warned: bool,
291}
292
293/// Buffered rows for a table whose data arrived before its DDL, retained up to
294/// the sample budget for a bounded replay once the schema appears.
295struct PendingTable {
296    row_count: u64,
297    retained: Vec<PendingRow>,
298    overflowed: bool,
299    header: Option<Vec<u8>>,
300    copy_columns: Option<Vec<String>>,
301}
302
303enum PendingRow {
304    Insert(Vec<u8>),
305    Copy(Vec<u8>),
306}
307
308/// Column context for the INSERT statement currently being streamed.
309struct InsertCtx {
310    table_idx: usize,
311    context: InsertRowContext,
312}
313
314/// Column context for the COPY block currently being streamed.
315struct CopyCtx {
316    table_idx: usize,
317    columns: Vec<String>,
318}
319
320struct ProfileRun {
321    depth: ProfileDepth,
322    budget: ProfileBudget,
323    seed: u64,
324    dialect: SqlDialect,
325    builder: SchemaBuilder,
326    tables: Vec<TableProfile>,
327    table_index: AHashMap<String, usize>,
328    insert_ctx: Option<InsertCtx>,
329    copy_ctx: Option<CopyCtx>,
330    /// The schema-late COPY table whose block is currently open. `CopyRow`
331    /// events carry no table name, so this is the *only* reliable way to route
332    /// pending COPY rows — a predicate scan over `pending` would misroute when
333    /// two tables both have COPY data before either's DDL.
334    pending_copy_key: Option<String>,
335    pending: AHashMap<String, PendingTable>,
336    warnings: Vec<Diagnostic>,
337    next_seed: u64,
338}
339
340impl ProfileRun {
341    fn new(depth: ProfileDepth, budget: ProfileBudget, seed: u64, dialect: SqlDialect) -> Self {
342        Self {
343            depth,
344            budget,
345            seed,
346            dialect,
347            builder: SchemaBuilder::new(),
348            tables: Vec::new(),
349            table_index: AHashMap::new(),
350            insert_ctx: None,
351            copy_ctx: None,
352            pending_copy_key: None,
353            pending: AHashMap::new(),
354            warnings: Vec::new(),
355            next_seed: 0,
356        }
357    }
358
359    fn key(name: &str) -> String {
360        name.to_ascii_lowercase()
361    }
362
363    fn on_event(&mut self, event: ParserEvent<'_>) -> anyhow::Result<RowFlow> {
364        match event {
365            ParserEvent::Statement(bytes) => self.on_statement(bytes),
366            ParserEvent::InsertRow {
367                header,
368                row,
369                first_in_statement,
370            } => self.on_insert_row(header, row, first_in_statement),
371            ParserEvent::CopyStart(header) => self.on_copy_start(header),
372            ParserEvent::CopyRow(line) => self.on_copy_row(line),
373            ParserEvent::CopyEnd => {
374                self.copy_ctx = None;
375                self.pending_copy_key = None;
376                Ok(RowFlow::Continue)
377            }
378        }
379    }
380
381    fn on_statement(&mut self, bytes: &[u8]) -> anyhow::Result<RowFlow> {
382        let (stmt_type, name) = Parser::<&[u8]>::parse_statement_with_dialect(bytes, self.dialect);
383        self.builder.ingest_statement(bytes, self.dialect);
384        if stmt_type == StatementType::CreateTable && !name.is_empty() {
385            self.register_table(&name);
386        }
387        Ok(RowFlow::Continue)
388    }
389
390    /// Ensure a [`TableProfile`] exists for a freshly created table, then replay
391    /// any rows that were buffered before the DDL arrived.
392    fn register_table(&mut self, name: &str) {
393        let key = Self::key(name);
394        if self.table_index.contains_key(&key) {
395            return;
396        }
397        let Some(table_id) = self.builder.schema().get_table_id(name) else {
398            return;
399        };
400        let profile = self.build_table_profile(name, table_id);
401        let idx = self.tables.len();
402        self.tables.push(profile);
403        self.table_index.insert(key.clone(), idx);
404
405        if let Some(pending) = self.pending.remove(&key) {
406            self.replay_pending(idx, pending);
407        }
408    }
409
410    fn build_table_profile(&mut self, name: &str, table_id: TableId) -> TableProfile {
411        let schema = self.builder.schema();
412        let table = schema
413            .table(table_id)
414            .expect("table id just resolved from builder");
415        let full = self.depth == ProfileDepth::Full;
416
417        let columns: Vec<ColumnAccum> = table
418            .columns
419            .iter()
420            .map(|col| {
421                let kind = ColumnKind::from_column(col);
422                // A credential-named, string-shaped column never enters the
423                // sketches: its raw values (hashes, tokens, keys) must not be
424                // retained in evidence. The observed total/null counts tracked
425                // separately below are still kept, so the observed null rate
426                // survives.
427                let credential = matches!(kind, ColumnKind::Text | ColumnKind::Json)
428                    && crate::profile::heuristics::is_credential_name(&col.name);
429                let sketches = if self.depth == ProfileDepth::Schema || credential {
430                    None
431                } else {
432                    let s = ColumnSketches::new(&self.budget, self.seed ^ self.next_seed);
433                    self.next_seed = self.next_seed.wrapping_add(1);
434                    Some(s)
435                };
436                ColumnAccum {
437                    name: col.name.clone(),
438                    kind,
439                    total: 0,
440                    nulls: 0,
441                    sketches,
442                }
443            })
444            .collect();
445
446        // Same-table temporal candidate pairs (Full only): ordered pairs of
447        // timestamp columns, bounded by the schema's column count.
448        let temporal = if full {
449            let ts_cols: Vec<usize> = table
450                .columns
451                .iter()
452                .enumerate()
453                .filter(|(_, c)| ColumnKind::from_column(c) == ColumnKind::DateTime)
454                .map(|(i, _)| i)
455                .collect();
456            let mut pairs = Vec::new();
457            for (a_pos, &a) in ts_cols.iter().enumerate() {
458                for &b in &ts_cols[a_pos + 1..] {
459                    pairs.push(TemporalPair {
460                        from: a,
461                        to: b,
462                        both_present: 0,
463                        ordered: 0,
464                    });
465                }
466            }
467            pairs
468        } else {
469            Vec::new()
470        };
471
472        // Declared FKs reduced to local column ordinals (resolved at CREATE
473        // TABLE time; only the *referenced* table id is deferred to `build()`).
474        let fk_candidates: Vec<FkCandidate> = if full {
475            table
476                .foreign_keys
477                .iter()
478                .enumerate()
479                .filter(|(_, fk)| !fk.columns.is_empty())
480                .map(|(fk_index, fk)| FkCandidate {
481                    fk_index: fk_index as u16,
482                    ordinals: fk.columns.iter().map(|c| c.0 as usize).collect(),
483                })
484                .collect()
485        } else {
486            Vec::new()
487        };
488
489        TableProfile {
490            name: name.to_string(),
491            table_id,
492            row_count: 0,
493            profiled_row_count: 0,
494            columns,
495            pk_hashes: BoundedHashSet::new(self.budget.sample_rows),
496            fk_candidates,
497            fk_child: AHashMap::new(),
498            temporal,
499            decode_warned: false,
500        }
501    }
502
503    // --- INSERT path -------------------------------------------------------
504
505    fn on_insert_row(
506        &mut self,
507        header: &[u8],
508        row: &[u8],
509        first_in_statement: bool,
510    ) -> anyhow::Result<RowFlow> {
511        if first_in_statement {
512            self.prepare_insert(header);
513        }
514
515        // Every delivered `InsertRow` is a real `(...)` tuple, so it counts
516        // toward the exact row total for a known table regardless of whether the
517        // secondary value decode succeeds. Decode success only governs per-column
518        // value/null evidence.
519        if let Some(table_idx) = self.insert_ctx.as_ref().map(|c| c.table_idx) {
520            match self.decode_insert_row(row) {
521                Some((idx, parsed)) => self.observe_insert(idx, &parsed),
522                None => {
523                    self.tables[table_idx].row_count += 1;
524                    self.warn_decode_skipped(table_idx);
525                }
526            }
527        } else {
528            // Schema-late: buffer the raw tuple for replay once the DDL arrives.
529            let cap = self.budget.sample_rows;
530            if let Some(table) = self.pending_insert_target(header) {
531                table.push_insert(row, cap);
532            }
533        }
534
535        Ok(RowFlow::Continue)
536    }
537
538    fn decode_insert_row(&self, row: &[u8]) -> Option<(usize, ParsedRow)> {
539        let ctx = self.insert_ctx.as_ref()?;
540        let table_idx = ctx.table_idx;
541        let table_id = self.tables[table_idx].table_id;
542        let table = self.builder.schema().table(table_id)?;
543        let parsed =
544            parse_insert_tuple(row, table, &ctx.context, self.dialect, RowExtraction::Full)?;
545        Some((table_idx, parsed))
546    }
547
548    fn prepare_insert(&mut self, header: &[u8]) {
549        self.insert_ctx = None;
550        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, self.dialect);
551        if name.is_empty() {
552            return;
553        }
554        let key = Self::key(&name);
555        if let Some(&table_idx) = self.table_index.get(&key) {
556            let table_id = self.tables[table_idx].table_id;
557            let schema = self.builder.schema();
558            if let Some(table) = schema.table(table_id) {
559                let context = InsertRowContext::from_header(header, table, self.dialect);
560                self.insert_ctx = Some(InsertCtx { table_idx, context });
561            }
562        } else {
563            // Schema-late: remember the first header so the replay can rebuild
564            // context (single-layout-per-pending-table assumption — a later
565            // INSERT into the same table with a different column list would
566            // replay under this one).
567            self.pending
568                .entry(key)
569                .or_insert_with(PendingTable::new)
570                .header
571                .get_or_insert_with(|| header.to_vec());
572        }
573    }
574
575    /// Look up (creating if needed) the pending buffer for the INSERT whose
576    /// header names an as-yet-unknown table.
577    fn pending_insert_target(&mut self, header: &[u8]) -> Option<&mut PendingTable> {
578        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, self.dialect);
579        if name.is_empty() {
580            return None;
581        }
582        let key = Self::key(&name);
583        let entry = self.pending.entry(key).or_insert_with(PendingTable::new);
584        // Single-layout-per-pending-table: the first header wins for replay.
585        entry.header.get_or_insert_with(|| header.to_vec());
586        Some(entry)
587    }
588
589    // --- COPY path ---------------------------------------------------------
590
591    fn on_copy_start(&mut self, header: &[u8]) -> anyhow::Result<RowFlow> {
592        self.copy_ctx = None;
593        self.pending_copy_key = None;
594        let header_str = String::from_utf8_lossy(header);
595        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, self.dialect);
596        if name.is_empty() {
597            return Ok(RowFlow::Continue);
598        }
599        let columns = parse_copy_columns(&header_str);
600        let key = Self::key(&name);
601        if let Some(&table_idx) = self.table_index.get(&key) {
602            self.copy_ctx = Some(CopyCtx { table_idx, columns });
603        } else {
604            // Schema-late COPY: record which table this open block belongs to so
605            // its rows route unambiguously, and stash the column layout for
606            // replay (single-layout-per-pending-table assumption).
607            //
608            // TODO(deferred, L21): if a `CREATE TABLE` for this key arrives while
609            // this block is still open, `register_table` removes the pending
610            // entry, leaving `pending_copy_key` dangling so the block's remaining
611            // rows are silently dropped. Adopting the open block into the newly
612            // registered table would fix it. Deferred: pg_dump never interleaves
613            // a table definition inside its own open COPY block (malformed input
614            // only).
615            let entry = self
616                .pending
617                .entry(key.clone())
618                .or_insert_with(PendingTable::new);
619            entry.copy_columns.get_or_insert(columns);
620            self.pending_copy_key = Some(key);
621        }
622        Ok(RowFlow::Continue)
623    }
624
625    fn on_copy_row(&mut self, line: &[u8]) -> anyhow::Result<RowFlow> {
626        if let Some(table_idx) = self.copy_ctx.as_ref().map(|c| c.table_idx) {
627            // Known table. A blank line inside a COPY block is padding, not a
628            // row, so it must not count; every genuine data line counts toward
629            // the exact total whether or not its values decode.
630            let single_col = self.tables[table_idx].columns.len() == 1;
631            if !copy_line_is_data(line, single_col) {
632                return Ok(RowFlow::Continue);
633            }
634            match self.decode_copy_row(line) {
635                Some((idx, parsed)) => self.observe_copy(idx, &parsed),
636                None => {
637                    self.tables[table_idx].row_count += 1;
638                    self.warn_decode_skipped(table_idx);
639                }
640            }
641        } else if let Some(key) = self.pending_copy_key.clone() {
642            // Schema-late COPY: route by the explicitly tracked open-block key,
643            // never a predicate scan (which would misroute with two pending
644            // COPY tables). Buffer genuine data lines only. The COPY header's
645            // column list gives the arity even before the CREATE TABLE, so a
646            // single-column block correctly treats a blank line as an
647            // empty-string row rather than padding.
648            let cap = self.budget.sample_rows;
649            if let Some(table) = self.pending.get_mut(&key) {
650                let single_col = table
651                    .copy_columns
652                    .as_ref()
653                    .is_some_and(|columns| columns.len() == 1);
654                if copy_line_is_data(line, single_col) {
655                    table.push_copy(line, cap);
656                }
657            }
658        }
659        Ok(RowFlow::Continue)
660    }
661
662    /// Raise `GEN-PROFILE-DECODE-SKIPPED` once per table when a delivered row
663    /// failed value decoding: it is still counted in the exact row total, but
664    /// contributes no per-column evidence.
665    fn warn_decode_skipped(&mut self, table_idx: usize) {
666        let table = &mut self.tables[table_idx];
667        if table.decode_warned {
668            return;
669        }
670        table.decode_warned = true;
671        self.warnings.push(Diagnostic::warning(
672            &codes::PROFILE_DECODE_SKIPPED,
673            format!("tables.{}", table.name),
674            "rows failed value decoding; they are counted in the exact row total but \
675             contributed no per-column evidence",
676        ));
677    }
678
679    fn decode_copy_row(&self, line: &[u8]) -> Option<(usize, ParsedCopyRow)> {
680        let ctx = self.copy_ctx.as_ref()?;
681        let table_idx = ctx.table_idx;
682        let table_id = self.tables[table_idx].table_id;
683        let table = self.builder.schema().table(table_id)?;
684        let parsed = decode_copy_line(line, table, ctx.columns.clone())?;
685        Some((table_idx, parsed))
686    }
687
688    // --- Row observation ---------------------------------------------------
689
690    fn observe_insert(&mut self, table_idx: usize, row: &ParsedRow) {
691        let ncols = self.tables[table_idx].columns.len();
692        self.observe_row(
693            table_idx,
694            ncols,
695            |ord| row.get_column_value(ord),
696            row.pk.as_ref(),
697        );
698    }
699
700    fn observe_copy(&mut self, table_idx: usize, row: &ParsedCopyRow) {
701        let ncols = self.tables[table_idx].columns.len();
702        self.observe_row(
703            table_idx,
704            ncols,
705            |ord| row.get_column_value(ord),
706            row.pk.as_ref(),
707        );
708    }
709
710    /// The single per-row hot path shared by INSERT and COPY: tally total/null,
711    /// feed the value sketches, and (at Full depth) update FK/PK/temporal
712    /// evidence.
713    fn observe_row<'r>(
714        &mut self,
715        table_idx: usize,
716        ncols: usize,
717        value: impl Fn(usize) -> Option<&'r PkValue>,
718        pk: Option<&PkTuple>,
719    ) {
720        let full = self.depth == ProfileDepth::Full;
721        let cap = self.budget.sample_rows;
722        let table = &mut self.tables[table_idx];
723        table.row_count += 1;
724        table.profiled_row_count += 1;
725
726        for (ord, acc) in table.columns.iter_mut().enumerate().take(ncols) {
727            let Some(v) = value(ord) else { continue };
728            acc.total += 1;
729            if v.is_null() {
730                acc.nulls += 1;
731            }
732            if let Some(sketches) = &mut acc.sketches {
733                observe_pk_value(sketches, acc.kind, v);
734            }
735        }
736
737        if !full {
738            return;
739        }
740
741        if let Some(pk) = pk {
742            table.pk_hashes.insert(hash_pk_tuple(pk));
743        }
744        // Child FK values, hashed the same way parent PKs are, so coverage is a
745        // plain set-membership test at finish.
746        for candidate in &table.fk_candidates {
747            let mut tuple = PkTuple::new();
748            let mut complete = true;
749            for &ord in &candidate.ordinals {
750                match value(ord) {
751                    Some(v) if !v.is_null() => tuple.push(v.clone()),
752                    _ => {
753                        complete = false;
754                        break;
755                    }
756                }
757            }
758            if complete && !tuple.is_empty() {
759                table
760                    .fk_child
761                    .entry(candidate.fk_index)
762                    .or_insert_with(|| BoundedHashSet::new(cap))
763                    .insert(hash_pk_tuple(&tuple));
764            }
765        }
766        for pair in &mut table.temporal {
767            if let (Some(PkValue::Text(a)), Some(PkValue::Text(b))) =
768                (value(pair.from), value(pair.to))
769            {
770                pair.both_present += 1;
771                if a <= b {
772                    pair.ordered += 1;
773                }
774            }
775        }
776    }
777
778    // --- Schema-late replay ------------------------------------------------
779
780    fn replay_pending(&mut self, table_idx: usize, pending: PendingTable) {
781        let table_id = self.tables[table_idx].table_id;
782
783        // Replay every retained row through the normal decode/observe path.
784        for row in &pending.retained {
785            match row {
786                PendingRow::Insert(bytes) => {
787                    let parsed = pending.header.as_ref().and_then(|header| {
788                        let schema = self.builder.schema();
789                        let table = schema.table(table_id)?;
790                        let ctx = InsertRowContext::from_header(header, table, self.dialect);
791                        parse_insert_tuple(bytes, table, &ctx, self.dialect, RowExtraction::Full)
792                    });
793                    if let Some(parsed) = parsed {
794                        self.observe_insert(table_idx, &parsed);
795                    }
796                }
797                PendingRow::Copy(bytes) => {
798                    let cols = pending.copy_columns.clone().unwrap_or_default();
799                    let parsed = {
800                        let schema = self.builder.schema();
801                        schema
802                            .table(table_id)
803                            .and_then(|table| decode_copy_line(bytes, table, cols))
804                    };
805                    if let Some(parsed) = parsed {
806                        self.observe_copy(table_idx, &parsed);
807                    }
808                }
809            }
810        }
811
812        // The retained sample may be smaller than what actually streamed by:
813        // fix the row count to the true total and flag the coverage gap.
814        let observed = self.tables[table_idx].row_count;
815        if pending.row_count > observed {
816            self.tables[table_idx].row_count = pending.row_count;
817        }
818        if pending.overflowed {
819            self.warnings.push(Diagnostic::warning(
820                &codes::PROFILE_SCHEMA_LATE,
821                format!("tables.{}", self.tables[table_idx].name),
822                format!(
823                    "had {} data rows before its DDL; only {} were retained for column profiling \
824                     (the table row count is exact, but column counts and null rates cover retained rows only)",
825                    pending.row_count,
826                    pending.retained.len()
827                ),
828            ));
829        }
830    }
831
832    // --- Finalize ----------------------------------------------------------
833
834    fn finish(mut self) -> DumpProfile {
835        // Resolve FK references now that all DDL has been seen.
836        let schema = std::mem::take(&mut self.builder).build();
837
838        // Map table id -> profile index, so FK coverage can reach the parent's
839        // retained PK set.
840        let mut id_to_idx: AHashMap<u32, usize> = AHashMap::new();
841        for (idx, t) in self.tables.iter().enumerate() {
842            id_to_idx.insert(t.table_id.0, idx);
843        }
844
845        // Any pending table that never got its DDL: surface its exact row count
846        // and warn that its columns could not be profiled.
847        // Sort by table key so the warnings are deterministic; the pending map
848        // is a randomized-seed hashmap whose drain order varies run to run.
849        let mut leftovers: Vec<(String, PendingTable)> = self.pending.drain().collect();
850        leftovers.sort_by(|a, b| a.0.cmp(&b.0));
851        for (key, pending) in leftovers {
852            self.warnings.push(Diagnostic::warning(
853                &codes::PROFILE_SCHEMA_LATE,
854                format!("tables.{key}"),
855                format!(
856                    "had {} data rows but no CREATE TABLE was seen; it could not be profiled",
857                    pending.row_count
858                ),
859            ));
860        }
861
862        let depth = self.depth;
863        let relationships = self.compute_relationships(&schema, &id_to_idx);
864
865        let tables = self
866            .tables
867            .into_iter()
868            .enumerate()
869            .map(|(idx, table)| {
870                finish_table(table, relationships.get(&idx).cloned().unwrap_or_default())
871            })
872            .collect();
873
874        // The profiler already built the full DDL schema in this same pass;
875        // capture it as a portable snapshot so downstream inference never has
876        // to re-read the dump to recover it.
877        let portable = PortableSchema::from_runtime(&schema, self.dialect);
878
879        DumpProfile {
880            depth,
881            schema: portable,
882            tables,
883            warnings: self.warnings,
884        }
885    }
886
887    /// Build the Full-depth relationship evidence per table index.
888    fn compute_relationships(
889        &self,
890        schema: &Schema,
891        id_to_idx: &AHashMap<u32, usize>,
892    ) -> AHashMap<usize, Vec<RelationshipEvidence>> {
893        let mut out: AHashMap<usize, Vec<RelationshipEvidence>> = AHashMap::new();
894        if self.depth != ProfileDepth::Full {
895            return out;
896        }
897
898        for (idx, table) in self.tables.iter().enumerate() {
899            let Some(table_schema) = schema.table(table.table_id) else {
900                continue;
901            };
902            let mut rels = Vec::new();
903
904            // Declared foreign keys: child -> parent coverage over bounded sets.
905            for (fk_index, fk) in table_schema.foreign_keys.iter().enumerate() {
906                let Some(child) = table.fk_child.get(&(fk_index as u16)) else {
907                    continue;
908                };
909                if child.is_empty() {
910                    continue;
911                }
912                let Some(parent_id) = fk.referenced_table_id else {
913                    continue;
914                };
915                let Some(&parent_idx) = id_to_idx.get(&parent_id.0) else {
916                    continue;
917                };
918                let parent = &self.tables[parent_idx].pk_hashes;
919                let matched = child.set.iter().filter(|h| parent.contains(**h)).count();
920                let coverage = matched as f64 / child.set.len() as f64;
921                let bounded = child.overflowed || parent.overflowed;
922                rels.push(RelationshipEvidence {
923                    from_column: fk.column_names.join(","),
924                    to_table: fk.referenced_table.clone(),
925                    to_column: fk.referenced_columns.join(","),
926                    coverage,
927                    confidence: if bounded { 0.5 } else { 1.0 },
928                });
929            }
930
931            // Same-table temporal orderings.
932            for pair in &table.temporal {
933                if pair.both_present == 0 {
934                    continue;
935                }
936                let coverage = pair.ordered as f64 / pair.both_present as f64;
937                rels.push(RelationshipEvidence {
938                    from_column: table.columns[pair.from].name.clone(),
939                    to_table: table.name.clone(),
940                    to_column: table.columns[pair.to].name.clone(),
941                    coverage,
942                    confidence: coverage,
943                });
944            }
945
946            if !rels.is_empty() {
947                out.insert(idx, rels);
948            }
949        }
950        out
951    }
952}
953
954/// True when a raw COPY line is a genuine data row, matching
955/// [`CopyParser::parse_line`]'s own skip rules: the `\.` terminator and (for
956/// multi-column tables) a blank padding line are *not* rows. Lets the exact row
957/// count be decided independently of whether the value decode succeeds.
958fn copy_line_is_data(line: &[u8], empty_is_row: bool) -> bool {
959    let line = if line.last() == Some(&b'\r') {
960        &line[..line.len() - 1]
961    } else {
962        line
963    };
964    !(line == b"\\." || (line.is_empty() && !empty_is_row))
965}
966
967/// Decode one COPY data line into a [`ParsedCopyRow`] with full column identity,
968/// building a fresh (bounded, per-line) parser context bound to the schema.
969fn decode_copy_line(
970    line: &[u8],
971    table: &TableSchema,
972    columns: Vec<String>,
973) -> Option<ParsedCopyRow> {
974    let (parser, empty_is_row) = CopyParser::new(b"")
975        .with_schema(table)
976        .with_column_order(columns)
977        .with_extraction(RowExtraction::Full)
978        .prepared();
979    parser.parse_line(line, empty_is_row)
980}
981
982/// Fold one already-decoded column value into its sketches, interpreting it
983/// through the schema-derived [`ColumnKind`].
984fn observe_pk_value(sketches: &mut ColumnSketches, kind: ColumnKind, value: &PkValue) {
985    match value {
986        PkValue::Null => sketches.observe(ProfileValue::Null),
987        PkValue::Int(n) => observe_integer(sketches, kind, *n as i128),
988        PkValue::BigInt(n) => observe_integer(sketches, kind, *n),
989        PkValue::Text(s) => observe_text(sketches, kind, s),
990    }
991}
992
993fn observe_integer(sketches: &mut ColumnSketches, kind: ColumnKind, n: i128) {
994    match kind {
995        ColumnKind::Bool if n == 0 || n == 1 => {
996            sketches.observe(ProfileValue::Boolean(n == 1));
997        }
998        ColumnKind::Decimal => sketches.observe(ProfileValue::Decimal { minor: n, scale: 0 }),
999        _ => match i64::try_from(n) {
1000            Ok(v) => sketches.observe(ProfileValue::Integer(v)),
1001            Err(_) => sketches.observe(ProfileValue::Decimal { minor: n, scale: 0 }),
1002        },
1003    }
1004}
1005
1006fn observe_text(sketches: &mut ColumnSketches, kind: ColumnKind, s: &str) {
1007    match kind {
1008        ColumnKind::DateTime => sketches.observe(ProfileValue::DateTime(s)),
1009        ColumnKind::Json => sketches.observe(ProfileValue::Json(s)),
1010        ColumnKind::Bool => match parse_bool(s) {
1011            Some(b) => sketches.observe(ProfileValue::Boolean(b)),
1012            None => sketches.observe(ProfileValue::Text(s)),
1013        },
1014        ColumnKind::Decimal => match parse_decimal(s) {
1015            Some((minor, scale)) => sketches.observe(ProfileValue::Decimal { minor, scale }),
1016            None => sketches.observe(ProfileValue::Text(s)),
1017        },
1018        ColumnKind::Int | ColumnKind::BigInt => match s.parse::<i128>() {
1019            Ok(n) => observe_integer(sketches, kind, n),
1020            Err(_) => sketches.observe(ProfileValue::Text(s)),
1021        },
1022        ColumnKind::Text => sketches.observe(ProfileValue::Text(s)),
1023    }
1024}
1025
1026/// Parse a boolean rendered as text (`t`/`true`/`1`/`yes` and their negatives).
1027fn parse_bool(s: &str) -> Option<bool> {
1028    match s.trim().to_ascii_lowercase().as_str() {
1029        "t" | "true" | "yes" | "y" => Some(true),
1030        "f" | "false" | "no" | "n" => Some(false),
1031        _ => None,
1032    }
1033}
1034
1035/// Parse a plain fixed-point decimal string into `(minor, scale)` such that the
1036/// value equals `minor * 10^-scale`. Rejects anything that is not sign + digits
1037/// with at most one decimal point (scientific notation, currency, etc.).
1038fn parse_decimal(s: &str) -> Option<(i128, u8)> {
1039    let s = s.trim();
1040    let (neg, body) = match s.strip_prefix('-') {
1041        Some(rest) => (true, rest),
1042        None => (false, s.strip_prefix('+').unwrap_or(s)),
1043    };
1044    let (int_part, frac_part) = match body.split_once('.') {
1045        Some((a, b)) => (a, b),
1046        None => (body, ""),
1047    };
1048    if int_part.is_empty() && frac_part.is_empty() {
1049        return None;
1050    }
1051    if !int_part.bytes().all(|b| b.is_ascii_digit()) {
1052        return None;
1053    }
1054    if !frac_part.bytes().all(|b| b.is_ascii_digit()) {
1055        return None;
1056    }
1057    let mut digits = String::with_capacity(int_part.len() + frac_part.len());
1058    digits.push_str(int_part);
1059    digits.push_str(frac_part);
1060    let mut minor: i128 = digits.parse().ok()?;
1061    if neg {
1062        minor = -minor;
1063    }
1064    let scale = u8::try_from(frac_part.len()).ok()?;
1065    Some((minor, scale))
1066}
1067
1068/// Finalize one table's accumulated state into neutral evidence.
1069fn finish_table(table: TableProfile, relationships: Vec<RelationshipEvidence>) -> TableEvidence {
1070    let coverage = if table.row_count == 0 {
1071        0.0
1072    } else {
1073        table.profiled_row_count as f64 / table.row_count as f64
1074    };
1075    let columns = table
1076        .columns
1077        .into_iter()
1078        .map(|column| finish_column(column, coverage))
1079        .collect::<Vec<_>>();
1080    TableEvidence {
1081        table: table.name,
1082        row_count: Some(table.row_count),
1083        columns,
1084        relationships,
1085        confidence: coverage,
1086    }
1087}
1088
1089fn finish_column(acc: ColumnAccum, coverage: f64) -> ColumnEvidence {
1090    match acc.sketches {
1091        Some(sketches) => {
1092            let mut ev = sketches.finish();
1093            ev.name = acc.name;
1094            ev.confidence = ev.confidence.min(coverage);
1095            ev
1096        }
1097        None => {
1098            // Schema depth: exact counts, no value-derived evidence.
1099            let null_rate = if acc.total == 0 {
1100                0.0
1101            } else {
1102                acc.nulls as f64 / acc.total as f64
1103            };
1104            // Ad-hoc confidence: rises toward 1.0 with the non-null observation
1105            // count (mirrors `ColumnSketches::confidence`). Both paths share
1106            // this intentionally heuristic scale.
1107            let non_null = acc.total.saturating_sub(acc.nulls);
1108            ColumnEvidence {
1109                name: acc.name,
1110                total_count: acc.total,
1111                null_count: acc.nulls,
1112                null_rate,
1113                distinct_estimate: 0.0,
1114                sample_values: Vec::new(),
1115                truncated_sample_count: 0,
1116                boolean: None,
1117                numeric: None,
1118                decimal_scale: None,
1119                string_shape: None,
1120                top_k: Vec::new(),
1121                timestamp_range: None,
1122                json_valid_rate: None,
1123                confidence: (1.0 - 1.0 / (1.0 + non_null as f64)).min(coverage),
1124            }
1125        }
1126    }
1127}
1128
1129impl PendingTable {
1130    fn new() -> Self {
1131        Self {
1132            row_count: 0,
1133            retained: Vec::new(),
1134            overflowed: false,
1135            header: None,
1136            copy_columns: None,
1137        }
1138    }
1139
1140    fn push_insert(&mut self, row: &[u8], cap: usize) {
1141        self.row_count += 1;
1142        if self.retained.len() < cap {
1143            self.retained.push(PendingRow::Insert(row.to_vec()));
1144        } else {
1145            self.overflowed = true;
1146        }
1147    }
1148
1149    fn push_copy(&mut self, line: &[u8], cap: usize) {
1150        self.row_count += 1;
1151        if self.retained.len() < cap {
1152            self.retained.push(PendingRow::Copy(line.to_vec()));
1153        } else {
1154            self.overflowed = true;
1155        }
1156    }
1157}