Skip to main content

sql_splitter/
pk.rs

1//! Shared primary key hashing and formatting utilities.
2//!
3//! This module is the single home for compact 64-bit hash representations of
4//! primary keys and for human-readable PK formatting, used by both the
5//! `validate` and `diff` commands for memory-efficient PK tracking. Keeping
6//! one implementation matters: these hashes are compared across modules, so
7//! divergent copies would silently break PK/FK and row comparisons.
8
9use crate::parser::mysql_insert::PkValue;
10use std::hash::{Hash, Hasher};
11
12/// Compact primary key hash (64-bit).
13/// Collision risk is negligible for realistic dump sizes.
14pub type PkHash = u64;
15
16/// Feed a single PK/FK value into `hasher`, tag-discriminated so that e.g.
17/// `Int(1)` and `Text("1")` hash differently.
18pub fn hash_pk_value_into<H: Hasher>(value: &PkValue, hasher: &mut H) {
19    match value {
20        PkValue::Int(i) => {
21            0u8.hash(hasher);
22            i.hash(hasher);
23        }
24        PkValue::BigInt(i) => {
25            1u8.hash(hasher);
26            i.hash(hasher);
27        }
28        PkValue::Text(s) => {
29            2u8.hash(hasher);
30            s.hash(hasher);
31        }
32        PkValue::Null => {
33            3u8.hash(hasher);
34        }
35    }
36}
37
38/// Hash a list of PK/FK values into a compact 64-bit hash.
39/// Uses AHash for fast, high-quality hashing.
40pub fn hash_pk_values(values: &[PkValue]) -> PkHash {
41    let mut hasher = ahash::AHasher::default();
42
43    // Include arity (number of columns) in the hash to distinguish (1) from (1, NULL)
44    (values.len() as u8).hash(&mut hasher);
45
46    for v in values {
47        hash_pk_value_into(v, &mut hasher);
48    }
49
50    hasher.finish()
51}
52
53/// Format a single PK value as a string.
54pub fn format_single_pk(v: &PkValue) -> String {
55    match v {
56        PkValue::Int(i) => i.to_string(),
57        PkValue::BigInt(i) => i.to_string(),
58        PkValue::Text(s) => s.to_string(),
59        PkValue::Null => "NULL".to_string(),
60    }
61}
62
63/// Format a PK tuple as a string (single value as-is, composite as "(val1, val2)").
64pub fn format_pk_tuple(pk: &[PkValue]) -> String {
65    if pk.len() == 1 {
66        format_single_pk(&pk[0])
67    } else {
68        let parts: Vec<String> = pk.iter().map(format_single_pk).collect();
69        format!("({})", parts.join(", "))
70    }
71}