Skip to main content

prefetch_soft

Function prefetch_soft 

Source
pub async fn prefetch_soft<C, F>(
    pool: &PgPool,
    parent_pks: &[i64],
    target_fk_column: &'static str,
    extract: F,
) -> Result<HashMap<i64, Vec<C>>, ExecError>
where C: Model + for<'r> FromRow<'r, PgRow> + Send + Unpin + 'static, F: Fn(&C) -> i64,
Expand description

Soft-FK prefetch — fetch every row of C whose soft-FK column matches one of parent_pks, then group the results by the soft-FK value via the caller-supplied extractor closure. Returns a HashMap<i64, Vec<C>> keyed on the soft-FK value, mirroring the shape of crate::sql::fetch_with_prefetch but for columns that aren’t declared as a real Relation::Fk (no DDL FK constraint, no macro-generated reverse helper).

“Soft FK” = an integer column that conceptually points at another model’s PK without a declared FK relation. Use cases: optional cross-app references, migration-period references where the constraint can’t be enforced yet, audit-log entity_pk columns, denormalized_user_id snapshots, etc.

Two SQL round trips total max (one for the prefetch + the parent fetch the caller already did). Empty parent_pks short-circuits to an empty map without a round trip.

// After fetching parents:
let parent_pks: Vec<i64> = posts.iter().map(|p| p.id.get().copied().unwrap()).collect();
let by_post: HashMap<i64, Vec<Comment>> = prefetch_soft::<Comment, _>(
    &pool,
    &parent_pks,
    "post_id",        // the soft-FK column on the Comment table
    |c| c.post_id,    // extractor: how to read the value off &Comment
).await?;
for post in &posts {
    let comments = by_post.get(&post.id.get().copied().unwrap())
        .map(Vec::as_slice).unwrap_or(&[]);
    // ...
}

§Errors

Driver / SQL failures from the SELECT.