use crate::schema::types::{DatabaseSchema, Table};
use indexmap::IndexMap;
use rand::Rng;
use std::collections::{BTreeSet, HashMap};
use crate::generate::value::Value;
pub struct ForeignKeyPool {
pools: HashMap<(String, String), Vec<Value>>,
tuples: HashMap<String, HashMap<Vec<String>, Vec<Vec<Value>>>>,
}
impl ForeignKeyPool {
pub fn new() -> Self {
Self {
pools: HashMap::new(),
tuples: HashMap::new(),
}
}
pub(crate) fn record_table(
&mut self,
table: &Table,
rows: &[IndexMap<String, Value>],
schema: &DatabaseSchema,
offset: u64,
) {
let mut keys: BTreeSet<&[String]> = schema
.tables
.values()
.flat_map(|t| t.local_foreign_keys())
.filter(|fk| fk.referenced_table == table.name)
.map(|fk| fk.referenced_columns.as_slice())
.collect();
if let Some(pk) = &table.primary_key {
keys.extend(pk.columns.iter().map(std::slice::from_ref));
}
for columns in keys {
for (index, row) in rows.iter().enumerate() {
let tuple: Option<Vec<_>> = columns
.iter()
.map(|name| {
row.get(name)
.cloned()
.or_else(|| {
let col = table.columns.get(name)?;
(col.is_auto_increment || col.data_type.is_serial())
.then(|| Value::Int((offset + index as u64 + 1) as i64))
})
.filter(|v| !v.is_null())
})
.collect();
if let Some(values) = tuple {
if let [name] = columns {
self.record_value(&table.name, name, values.into_iter().next().unwrap());
} else {
self.tuples
.entry(table.name.clone())
.or_default()
.entry(columns.to_vec())
.or_default()
.push(values);
}
}
}
}
}
pub(crate) fn tuples(&self, table: &str, columns: &[String]) -> &[Vec<Value>] {
self.tuples
.get(table)
.and_then(|keys| keys.get(columns))
.map(Vec::as_slice)
.unwrap_or_default()
}
pub fn record_value(&mut self, table_name: &str, column_name: &str, value: Value) {
self.pools
.entry((table_name.to_string(), column_name.to_string()))
.or_default()
.push(value);
}
pub fn pick_reference(
&self,
table_name: &str,
column_name: &str,
rng: &mut impl Rng,
) -> Option<Value> {
self.pools
.get(&(table_name.to_string(), column_name.to_string()))
.and_then(|pool| {
if pool.is_empty() {
None
} else {
Some(pool[rng.random_range(0..pool.len())].clone())
}
})
}
pub fn pool_size(&self, table_name: &str, column_name: &str) -> usize {
self.pools
.get(&(table_name.to_string(), column_name.to_string()))
.map(|p| p.len())
.unwrap_or(0)
}
pub fn get_pool(&self, table_name: &str, column_name: &str) -> Option<&[Value]> {
self.pools
.get(&(table_name.to_string(), column_name.to_string()))
.map(|v| v.as_slice())
}
}
impl Default for ForeignKeyPool {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::SeedableRng;
#[test]
fn test_record_and_pick() {
let mut pool = ForeignKeyPool::new();
let mut rng = rand::rngs::StdRng::seed_from_u64(42);
pool.record_value("users", "id", Value::Int(1));
pool.record_value("users", "id", Value::Int(2));
pool.record_value("users", "id", Value::Int(3));
let picked = pool.pick_reference("users", "id", &mut rng);
assert!(picked.is_some());
if let Some(Value::Int(v)) = picked {
assert!((1..=3).contains(&v));
}
}
#[test]
fn test_empty_pool() {
let pool = ForeignKeyPool::new();
let mut rng = rand::rngs::StdRng::seed_from_u64(42);
assert!(pool.pick_reference("users", "id", &mut rng).is_none());
}
}