rust-ef 1.7.0

Rust Entity Framework - An EFCore-inspired ORM for Rust
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
//! `ChangeExecutor` — UPDATE and DELETE execution (batched + per-row fallback).

use crate::entity::{IEntitySnapshot, IEntityType, IGetKeyValues};
use crate::error::{EFError, EFResult};
use crate::metadata::{EntityTypeMeta, PropertyMeta};
use crate::provider::{DbValue, IAsyncConnection, IDatabaseProvider};
use crate::query::{collect_bool_expr_values, compile_bool_expr, BoolExpr};
use std::collections::HashMap;

use super::executor::ChangeExecutor;

impl ChangeExecutor {
    /// Executes UPDATE statements for all modified entities.
    ///
    /// When no concurrency tokens are present and the entity has a single-column
    /// primary key, rows are batched into a single `UPDATE ... SET col = CASE
    /// pk WHEN ? THEN ? ... END WHERE pk IN (...)` statement (≤900 params per
    /// batch) to minimize round trips. Otherwise (concurrency tokens, composite
    /// PK), falls back to per-row UPDATE so optimistic-concurrency checks run
    /// on each row.
    ///
    /// When `modified_properties` is populated (via `detect_changes`), only the
    /// dirty columns are SET. When empty (entity marked Modified via `update()`
    /// without detection), all non-PK columns are SET (backward compatible).
    ///
    /// When `query_filter` is `Some`, the filter is AND-ed into the WHERE
    /// clause so updates cannot cross the filter boundary (multi-tenant /
    /// soft-delete isolation).
    #[allow(clippy::type_complexity)]
    pub async fn execute_updates<E>(
        conn: &mut dyn IAsyncConnection,
        provider: &dyn IDatabaseProvider,
        entities: &[(
            &E,
            &EntityTypeMeta,
            Option<&HashMap<String, DbValue>>,
            &[String],
        )],
        query_filter: Option<&BoolExpr>,
    ) -> EFResult<usize>
    where
        E: IEntityType + IEntitySnapshot + IGetKeyValues,
    {
        if entities.is_empty() {
            return Ok(0);
        }
        let gen = provider.sql_generator();
        let meta = entities[0].1;
        let scalar_props: Vec<_> = meta.mapped_scalar_properties().collect();
        let pk_props: Vec<_> = scalar_props.iter().filter(|p| p.is_primary_key).collect();
        let has_concurrency_tokens = scalar_props.iter().any(|p| p.is_concurrency_token);

        // Compute the union of modified field names across all entities. When
        // non-empty, only those columns are SET (partial update). When empty
        // (no change detection ran), all non-PK columns are SET.
        let modified_fields: std::collections::HashSet<&str> = entities
            .iter()
            .flat_map(|(_, _, _, mods)| mods.iter().map(|s| s.as_str()))
            .collect();
        let set_props: Vec<&PropertyMeta> = if modified_fields.is_empty() {
            scalar_props
                .iter()
                .copied()
                .filter(|p| !p.is_primary_key)
                .collect()
        } else {
            scalar_props
                .iter()
                .copied()
                .filter(|p| !p.is_primary_key && modified_fields.contains(p.field_name.as_ref()))
                .collect()
        };
        let set_cols: Vec<&str> = set_props.iter().map(|p| p.column_name.as_ref()).collect();

        // Fall back to per-row UPDATE when optimistic concurrency tokens are
        // present (each row needs its own WHERE to check the token) or when
        // the PK is composite (CASE WHEN only works with a single column).
        if has_concurrency_tokens || pk_props.len() != 1 || set_cols.is_empty() {
            return Self::execute_updates_per_row(conn, gen, entities, query_filter).await;
        }

        let pk_col = pk_props[0].column_name.as_ref();
        let pk_field = pk_props[0].field_name.as_ref();

        // Pre-compute snapshots and keys to avoid re-hashing per batch.
        let entity_data: Vec<(HashMap<String, DbValue>, HashMap<String, DbValue>)> = entities
            .iter()
            .map(|(e, _, _, _)| (e.snapshot(), e.key_values()))
            .collect();

        // Filter params are constant across batches.
        let filter_params: Vec<DbValue> = match query_filter {
            Some(filter) => collect_bool_expr_values(filter),
            None => Vec::new(),
        };

        // For non-numbered placeholder dialects (SQLite/MySQL `?`), the filter
        // SQL is index-independent — compile once and reuse across batches.
        // PostgreSQL (`$N`) must recompile per batch because numbering shifts.
        let cached_filter_sql: Option<String> = if !gen.uses_numbered_placeholders() {
            query_filter.map(|f| {
                let mut idx = 1;
                compile_bool_expr(f, gen, &mut idx)
            })
        } else {
            None
        };

        // Each row consumes 2 * set_cols params (CASE WHEN pk/value pairs)
        // plus 1 param in the WHERE IN-list.
        const MAX_PARAMS: usize = 900;
        let params_per_row = 2 * set_cols.len() + 1;
        let batch_size =
            ((MAX_PARAMS.saturating_sub(filter_params.len())) / params_per_row.max(1)).max(1);

        let mut updated = 0usize;
        let mut start = 0usize;
        while start < entity_data.len() {
            let end = (start + batch_size).min(entity_data.len());
            let row_count = end - start;

            // SET clause consumes 2 * set_cols * row_count placeholders.
            let set_param_count = 2 * set_cols.len() * row_count;
            let mut idx = set_param_count + 1;

            // Build WHERE clause: pk_col IN (?, ...) [AND (filter)]
            let pk_placeholders: Vec<String> = (0..row_count)
                .map(|_| {
                    let ph = gen.parameter_placeholder(idx);
                    idx += 1;
                    ph
                })
                .collect();
            let mut where_clause = format!(
                "{} IN ({})",
                gen.quote_identifier(pk_col),
                pk_placeholders.join(", ")
            );

            // CASE WHEN params: for each col, for each entity: [pk_value, col_value]
            let mut params: Vec<DbValue> = Vec::with_capacity(set_param_count + row_count);
            for col_prop in &set_props {
                for (snap, keys) in entity_data[start..end].iter() {
                    let pk_val = keys.get(pk_field).cloned().unwrap_or(DbValue::Null);
                    let col_val = snap
                        .get(col_prop.field_name.as_ref())
                        .cloned()
                        .unwrap_or(DbValue::Null);
                    params.push(pk_val);
                    params.push(col_val);
                }
            }
            // WHERE IN params: pk values
            for (_, keys) in entity_data[start..end].iter() {
                let pk_val = keys.get(pk_field).cloned().unwrap_or(DbValue::Null);
                params.push(pk_val);
            }

            // Append filter to WHERE clause.
            if let Some(filter) = query_filter {
                let filter_sql = match &cached_filter_sql {
                    Some(cached) => cached.clone(),
                    None => compile_bool_expr(filter, gen, &mut idx),
                };
                params.extend(filter_params.iter().cloned());
                where_clause = format!("({}) AND ({})", where_clause, filter_sql);
            }

            let sql = gen.update_batch(
                meta.table_name.as_ref(),
                &set_cols,
                pk_col,
                row_count,
                &where_clause,
            );
            let rows = conn.execute(&sql, &params).await?;
            if rows == 0 && row_count > 0 {
                return Err(EFError::concurrency_conflict(format!(
                    "batch update affected 0 rows on {} (rows may have been modified or deleted)",
                    meta.table_name
                )));
            }
            updated += (rows as usize).min(row_count);
            start = end;
        }

        Ok(updated)
    }

    /// Per-row UPDATE fallback used when concurrency tokens or composite PKs
    /// prevent batching. Each row gets its own `UPDATE ... SET ... WHERE
    /// pk = ? AND ...`. When `modified_properties` is non-empty for an entity,
    /// only those columns are SET (partial update); otherwise all non-PK
    /// columns are SET (backward compatible).
    #[allow(clippy::type_complexity)]
    async fn execute_updates_per_row<E>(
        conn: &mut dyn IAsyncConnection,
        gen: &'static dyn crate::provider::ISqlGenerator,
        entities: &[(
            &E,
            &EntityTypeMeta,
            Option<&HashMap<String, DbValue>>,
            &[String],
        )],
        query_filter: Option<&BoolExpr>,
    ) -> EFResult<usize>
    where
        E: IEntityType + IEntitySnapshot + IGetKeyValues,
    {
        let mut updated = 0;
        let mut sql_cache: HashMap<(String, Vec<String>, String), String> = HashMap::new();

        // Hoist metadata-derived collections outside the per-entity loop —
        // all entities share the same EntityTypeMeta (same type E), so
        // scalar_props and concurrency_tokens are identical for every row.
        let meta0 = entities[0].1;
        let scalar_props: Vec<&PropertyMeta> = meta0.mapped_scalar_properties().collect();
        let concurrency_tokens: Vec<&PropertyMeta> = scalar_props
            .iter()
            .copied()
            .filter(|p| p.is_concurrency_token)
            .collect();
        let table_name = meta0.table_name.as_ref();

        for (entity, _meta, original, modified_props) in entities {
            let snap = entity.snapshot();
            let keys = entity.key_values();

            // When modified_properties is populated, SET only those columns
            // (partial update). When empty, SET all non-PK columns.
            let set_props: Vec<&PropertyMeta> = if modified_props.is_empty() {
                scalar_props
                    .iter()
                    .copied()
                    .filter(|p| !p.is_primary_key)
                    .collect()
            } else {
                let modified_set: std::collections::HashSet<&str> =
                    modified_props.iter().map(|s| s.as_str()).collect();
                scalar_props
                    .iter()
                    .copied()
                    .filter(|p| !p.is_primary_key && modified_set.contains(p.field_name.as_ref()))
                    .collect()
            };
            let set_cols: Vec<&str> = set_props.iter().map(|p| p.column_name.as_ref()).collect();

            if set_cols.is_empty() || keys.is_empty() {
                continue;
            }

            let (mut where_clause, mut where_params) = build_where_with_concurrency(
                gen,
                &keys,
                &concurrency_tokens,
                *original,
                set_cols.len() + 1,
            )?;

            if let Some(filter) = query_filter {
                let mut idx = set_cols.len() + where_params.len() + 1;
                let filter_sql = compile_bool_expr(filter, gen, &mut idx);
                where_params.extend(collect_bool_expr_values(filter));
                where_clause = format!("({}) AND ({})", where_clause, filter_sql);
            }

            let sql = sql_cache
                .entry((
                    table_name.to_string(),
                    set_cols.iter().map(|s| (*s).to_string()).collect(),
                    where_clause.clone(),
                ))
                .or_insert_with(|| gen.update(table_name, &set_cols, &where_clause))
                .clone();

            let mut params: Vec<DbValue> = set_props
                .iter()
                .map(|p| {
                    snap.get(p.field_name.as_ref())
                        .cloned()
                        .unwrap_or(DbValue::Null)
                })
                .collect();
            params.extend(where_params);

            let rows = conn.execute(&sql, &params).await?;
            if rows == 0 {
                return Err(EFError::concurrency_conflict(format!(
                    "update affected 0 rows on {} (row may have been modified or deleted)",
                    table_name
                )));
            }
            updated += 1;
        }

        Ok(updated)
    }

    /// Executes DELETE statements for all deleted entities.
    ///
    /// When no concurrency tokens are present and the entity has a single-column
    /// primary key, rows are batched into `DELETE ... WHERE pk IN (?, ?, ...)`
    /// statements (≤900 params per batch) to minimize round trips. Otherwise
    /// (concurrency tokens, composite PK), falls back to per-row DELETE so
    /// optimistic-concurrency checks run on each row.
    ///
    /// When `query_filter` is `Some`, the filter is AND-ed into the WHERE
    /// clause so deletes cannot cross the filter boundary.
    #[allow(clippy::type_complexity)]
    pub async fn execute_deletes<E>(
        conn: &mut dyn IAsyncConnection,
        provider: &dyn IDatabaseProvider,
        entities: &[(&E, &EntityTypeMeta, Option<&HashMap<String, DbValue>>)],
        query_filter: Option<&BoolExpr>,
    ) -> EFResult<usize>
    where
        E: IEntityType + IGetKeyValues,
    {
        if entities.is_empty() {
            return Ok(0);
        }
        let gen = provider.sql_generator();
        let meta = entities[0].1;
        let scalar_props: Vec<_> = meta.mapped_scalar_properties().collect();
        let has_concurrency_tokens = scalar_props.iter().any(|p| p.is_concurrency_token);
        let pk_props: Vec<_> = scalar_props.iter().filter(|p| p.is_primary_key).collect();

        // Fall back to per-row DELETE when optimistic concurrency tokens are
        // present (each row needs its own WHERE to check the token) or when
        // the PK is composite (IN clause only works for a single column).
        if has_concurrency_tokens || pk_props.len() != 1 {
            return Self::execute_deletes_per_row(conn, gen, entities, query_filter).await;
        }

        let pk_col = pk_props[0].column_name.as_ref();
        let pk_field = pk_props[0].field_name.as_ref();

        // Collect PK values; entities missing the PK value are skipped.
        let pk_values: Vec<DbValue> = entities
            .iter()
            .filter_map(|(e, _, _)| e.key_values().get(pk_field).cloned())
            .collect();
        if pk_values.is_empty() {
            return Ok(0);
        }

        // Filter params are constant across batches; their SQL is recomputed
        // per batch for numbered-placeholder dialects (Postgres `$N`).
        // For `?` dialects (SQLite/MySQL), the filter SQL is index-independent
        // and can be compiled once and reused.
        let filter_params: Vec<DbValue> = match query_filter {
            Some(filter) => collect_bool_expr_values(filter),
            None => Vec::new(),
        };
        let cached_filter_sql: Option<String> = if !gen.uses_numbered_placeholders() {
            query_filter.map(|f| {
                let mut idx = 1;
                compile_bool_expr(f, gen, &mut idx)
            })
        } else {
            None
        };
        const MAX_PARAMS: usize = 900;
        let batch_size = MAX_PARAMS.saturating_sub(filter_params.len()).max(1);

        let mut deleted = 0usize;
        let mut start = 0usize;
        while start < pk_values.len() {
            let end = (start + batch_size).min(pk_values.len());
            let batch = &pk_values[start..end];
            let pk_count = batch.len();

            let pk_placeholders: Vec<String> = (1..=pk_count)
                .map(|i| gen.parameter_placeholder(i))
                .collect();
            let mut where_clause = format!(
                "{} IN ({})",
                gen.quote_identifier(pk_col),
                pk_placeholders.join(", "),
            );
            let mut params: Vec<DbValue> = batch.to_vec();
            if let Some(filter) = query_filter {
                let filter_sql = match &cached_filter_sql {
                    Some(cached) => cached.clone(),
                    None => {
                        let mut idx = pk_count + 1;
                        compile_bool_expr(filter, gen, &mut idx)
                    }
                };
                params.extend(filter_params.iter().cloned());
                where_clause = format!("({}) AND ({})", where_clause, filter_sql);
            }

            let sql = gen.delete(meta.table_name.as_ref(), &where_clause);
            let rows = conn.execute(&sql, &params).await?;
            if rows == 0 && pk_count > 0 {
                return Err(EFError::concurrency_conflict(format!(
                    "batch delete affected 0 rows on {} (rows may have been modified or deleted)",
                    meta.table_name
                )));
            }
            deleted += (rows as usize).min(pk_count);
            start = end;
        }

        Ok(deleted)
    }

    /// Per-row DELETE fallback used when concurrency tokens or composite PKs
    /// prevent batching. Each row gets its own `DELETE ... WHERE pk = ? AND ...`.
    #[allow(clippy::type_complexity)]
    async fn execute_deletes_per_row<E>(
        conn: &mut dyn IAsyncConnection,
        gen: &'static dyn crate::provider::ISqlGenerator,
        entities: &[(&E, &EntityTypeMeta, Option<&HashMap<String, DbValue>>)],
        query_filter: Option<&BoolExpr>,
    ) -> EFResult<usize>
    where
        E: IEntityType + IGetKeyValues,
    {
        let mut deleted = 0;

        // Hoist metadata-derived collections outside the per-entity loop —
        // all entities share the same EntityTypeMeta (same type E).
        let meta0 = entities[0].1;
        let concurrency_tokens: Vec<&PropertyMeta> = meta0
            .mapped_scalar_properties()
            .filter(|p| p.is_concurrency_token)
            .collect();
        let table_name = meta0.table_name.as_ref();

        for (entity, _meta, original) in entities {
            let keys = entity.key_values();
            if keys.is_empty() {
                continue;
            }

            let (mut where_clause, mut where_params) =
                build_where_with_concurrency(gen, &keys, &concurrency_tokens, *original, 1)?;

            if let Some(filter) = query_filter {
                let mut idx = where_params.len() + 1;
                let filter_sql = compile_bool_expr(filter, gen, &mut idx);
                where_params.extend(collect_bool_expr_values(filter));
                where_clause = format!("({}) AND ({})", where_clause, filter_sql);
            }

            let sql = gen.delete(table_name, &where_clause);
            let rows = conn.execute(&sql, &where_params).await?;
            if rows == 0 {
                return Err(EFError::concurrency_conflict(format!(
                    "delete affected 0 rows on {} (row may have been modified or deleted)",
                    table_name
                )));
            }
            deleted += 1;
        }
        Ok(deleted)
    }
}

fn build_where_with_concurrency(
    gen: &dyn crate::provider::ISqlGenerator,
    keys: &HashMap<String, DbValue>,
    concurrency_tokens: &[&PropertyMeta],
    original: Option<&HashMap<String, DbValue>>,
    start_param_idx: usize,
) -> EFResult<(String, Vec<DbValue>)> {
    let mut where_parts: Vec<String> = keys
        .keys()
        .enumerate()
        .map(|(i, k)| {
            format!(
                "{} = {}",
                gen.quote_identifier(k),
                gen.parameter_placeholder(start_param_idx + i)
            )
        })
        .collect();

    let mut params: Vec<DbValue> = keys.values().cloned().collect();

    for (next_idx, token) in (start_param_idx + keys.len()..).zip(concurrency_tokens.iter()) {
        where_parts.push(format!(
            "{} = {}",
            gen.quote_identifier(token.column_name.as_ref()),
            gen.parameter_placeholder(next_idx)
        ));

        let original_val = original
            .and_then(|o| o.get(token.field_name.as_ref()))
            .ok_or_else(|| {
                EFError::change_tracking(format!(
                    "missing original concurrency token for '{}'",
                    token.field_name
                ))
            })?;
        params.push(original_val.clone());
    }

    Ok((where_parts.join(" AND "), params))
}