es-entity 0.12.7

Event Sourcing Entity Framework
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
mod entities;
mod helpers;

use entities::{order::*, profile::*, user::*};
use es_entity::*;
use sqlx::PgPool;

#[derive(EsRepo, Debug)]
#[es_repo(entity = "User", columns(name(ty = "String", list_for)))]
pub struct Users {
    pool: PgPool,
}

impl Users {
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

/// Profiles repo with custom accessors:
/// - `name`: field-path accessor (`data.name`) — accesses nested struct field
/// - `display_name`: method-call accessor (`display_name()`) — returns owned String
/// - `email`: direct field access — no custom accessor
#[derive(EsRepo, Debug)]
#[es_repo(
    entity = "Profile",
    columns(
        name(ty = "String", update(accessor = "data.name")),
        display_name(
            ty = "String",
            create(accessor = "display_name()"),
            update(accessor = "display_name()")
        ),
        email(ty = "String"),
    )
)]
pub struct Profiles {
    pool: PgPool,
}

impl Profiles {
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

/// Same shape as the nested repo in tests/nested_entities.rs — used here
/// standalone to violate the hand-written `order_items_order_id_fkey` foreign
/// key through generated ops.
#[derive(EsRepo, Debug)]
#[es_repo(
    entity = "OrderItem",
    delete = "soft",
    columns(order_id(ty = "OrderId", update(persist = false), parent))
)]
pub struct OrderItems {
    pool: PgPool,
}

impl OrderItems {
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

// ===========================================================================
// Constraint violation tests
// ===========================================================================

#[tokio::test]
async fn create_duplicate_email_returns_constraint_violation_with_value() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let profiles = Profiles::new(pool);

    let email = format!("unique_{}@test.com", ProfileId::new());

    let first = NewProfile::builder()
        .id(ProfileId::new())
        .name("First")
        .email(&email)
        .build()
        .unwrap();
    profiles.create(first).await?;

    let duplicate = NewProfile::builder()
        .id(ProfileId::new())
        .name("Second")
        .email(&email)
        .build()
        .unwrap();
    let err = match profiles.create(duplicate).await {
        Err(e) => e,
        Ok(_) => panic!("expected constraint violation"),
    };

    assert!(err.was_duplicate());
    assert!(err.was_duplicate_by(ProfileColumn::Email));
    assert_eq!(err.duplicate_value(), Some(email.as_str()));
    assert_eq!(err.constraint_name(), Some("idx_profiles_email"));
    assert_eq!(
        err.violated_constraint(),
        Some(ProfileConstraint::IdxProfilesEmail)
    );
    assert_eq!(
        ProfileConstraint::IdxProfilesEmail.kind(),
        ConstraintKind::Unique
    );
    assert!(!err.was_foreign_key_violation());
    assert!(!err.was_check_violation());

    Ok(())
}

#[tokio::test]
async fn create_duplicate_id_returns_constraint_violation_with_value() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let users = Users::new(pool);

    let id = UserId::new();

    let first = NewUser::builder().id(id).name("First").build().unwrap();
    users.create(first).await?;

    let duplicate = NewUser::builder().id(id).name("Second").build().unwrap();
    let err = match users.create(duplicate).await {
        Err(e) => e,
        Ok(_) => panic!("expected constraint violation"),
    };

    assert!(err.was_duplicate());
    assert!(err.was_duplicate_by(UserColumn::Id));
    assert_eq!(err.duplicate_value(), Some(id.to_string().as_str()));
    assert_eq!(err.constraint_name(), Some("users_pkey"));
    assert_eq!(err.violated_constraint(), Some(UserConstraint::Pkey));
    assert_eq!(UserConstraint::Pkey.kind(), ConstraintKind::Unique);

    Ok(())
}

/// Regression test for the #196 combined index+events write: Postgres
/// interleaves the CTE (index insert) and main statement (events insert), so
/// for an intra-batch duplicate id either the index-table pkey or the
/// events-table `(id, sequence)` pkey may fire first. Both must classify as
/// the duplicate-id `ConstraintViolation` — never `ConcurrentModification`.
#[tokio::test]
async fn create_all_intra_batch_duplicate_id_classifies_as_duplicate() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let users = Users::new(pool);

    // Duplicate in different positions and batch sizes, in case the chosen
    // plan (and therefore which constraint fires first) varies with shape.
    for batch_size in [2usize, 5] {
        for dup_pos in [0usize, batch_size - 1] {
            let dup_id = UserId::new();
            let new_users: Vec<_> = (0..=batch_size)
                .map(|i| {
                    let id = if i == dup_pos || i == batch_size {
                        dup_id
                    } else {
                        UserId::new()
                    };
                    NewUser::builder()
                        .id(id)
                        .name(format!("User{i}"))
                        .build()
                        .unwrap()
                })
                .collect();

            let err = match users.create_all(new_users).await {
                Err(e) => e,
                Ok(_) => panic!("expected constraint violation"),
            };

            assert!(
                !err.was_concurrent_modification(),
                "duplicate id must not classify as ConcurrentModification: {err:?}"
            );
            assert!(err.was_duplicate(), "expected duplicate: {err:?}");
            assert!(
                err.was_duplicate_by(UserColumn::Id),
                "wrong column: {err:?}"
            );
            assert_eq!(err.duplicate_value(), Some(dup_id.to_string().as_str()));

            // The whole batch rolls back.
            assert!(users.find_by_id(dup_id).await.is_err());
        }
    }

    Ok(())
}

/// A `create_all` batch containing an id that already exists in the database
/// must classify the same way as the intra-batch case.
#[tokio::test]
async fn create_all_preexisting_duplicate_id_classifies_as_duplicate() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let users = Users::new(pool);

    let id = UserId::new();
    users
        .create(NewUser::builder().id(id).name("First").build().unwrap())
        .await?;

    let new_users = vec![
        NewUser::builder()
            .id(UserId::new())
            .name("Fresh")
            .build()
            .unwrap(),
        NewUser::builder().id(id).name("Dup").build().unwrap(),
    ];
    let err = match users.create_all(new_users).await {
        Err(e) => e,
        Ok(_) => panic!("expected constraint violation"),
    };

    assert!(!err.was_concurrent_modification());
    assert!(err.was_duplicate());
    assert!(err.was_duplicate_by(UserColumn::Id));
    assert_eq!(err.duplicate_value(), Some(id.to_string().as_str()));

    Ok(())
}

#[tokio::test]
async fn update_to_duplicate_email_returns_constraint_violation_with_value() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let profiles = Profiles::new(pool);

    let email_a = format!("update_a_{}@test.com", ProfileId::new());
    let email_b = format!("update_b_{}@test.com", ProfileId::new());

    let profile_a = NewProfile::builder()
        .id(ProfileId::new())
        .name("A")
        .email(&email_a)
        .build()
        .unwrap();
    profiles.create(profile_a).await?;

    let profile_b = NewProfile::builder()
        .id(ProfileId::new())
        .name("B")
        .email(&email_b)
        .build()
        .unwrap();
    let mut b = profiles.create(profile_b).await?;

    // Update B's email to A's email — should trigger constraint violation
    let _ = b.update_email(email_a.clone());
    let err = match profiles.update(&mut b).await {
        Err(e) => e,
        Ok(_) => panic!("expected constraint violation"),
    };

    assert!(err.was_duplicate());
    assert!(err.was_duplicate_by(ProfileColumn::Email));
    assert_eq!(err.duplicate_value(), Some(email_a.as_str()));

    Ok(())
}

// ===========================================================================
// Non-unique constraint classification tests (foreign key / check)
// ===========================================================================

#[tokio::test]
async fn create_fk_violation_returns_constraint_violation() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let order_items = OrderItems::new(pool);

    // No such order exists — violates order_items_order_id_fkey.
    let item = NewOrderItem::builder()
        .id(OrderItemId::new())
        .order_id(OrderId::new())
        .product_name("Orphan")
        .quantity(1)
        .price(1.0)
        .build()
        .unwrap();
    let err = match order_items.create(item).await {
        Err(e) => e,
        Ok(_) => panic!("expected constraint violation"),
    };

    // FK violations are classified but are not duplicates.
    assert!(!err.was_duplicate());
    assert!(err.was_foreign_key_violation());
    assert!(!err.was_check_violation());
    assert_eq!(err.constraint_name(), Some("order_items_order_id_fkey"));
    assert_eq!(
        err.violated_constraint(),
        Some(OrderItemConstraint::OrderIdFkey)
    );
    assert_eq!(
        OrderItemConstraint::OrderIdFkey.kind(),
        ConstraintKind::ForeignKey
    );
    assert_eq!(err.duplicate_value(), None);
    match &err {
        OrderItemCreateError::ConstraintViolation { column: None, .. } => {}
        other => panic!("expected ConstraintViolation without column, got: {other:?}"),
    }

    Ok(())
}

#[tokio::test]
async fn create_all_fk_violation_returns_constraint_violation() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let order_items = OrderItems::new(pool);

    let item = NewOrderItem::builder()
        .id(OrderItemId::new())
        .order_id(OrderId::new())
        .product_name("Orphan")
        .quantity(1)
        .price(1.0)
        .build()
        .unwrap();
    let err = match order_items.create_all(vec![item]).await {
        Err(e) => e,
        Ok(_) => panic!("expected constraint violation"),
    };

    assert!(!err.was_duplicate());
    assert!(err.was_foreign_key_violation());
    assert_eq!(err.constraint_name(), Some("order_items_order_id_fkey"));
    assert_eq!(
        err.violated_constraint(),
        Some(OrderItemConstraint::OrderIdFkey)
    );
    match &err {
        OrderItemCreateError::ConstraintViolation { column: None, .. } => {}
        other => panic!("expected ConstraintViolation without column, got: {other:?}"),
    }

    Ok(())
}

#[tokio::test]
async fn create_check_violation_returns_constraint_violation() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let profiles = Profiles::new(pool);

    // Blank email violates the profiles_email_not_blank CHECK constraint.
    let profile = NewProfile::builder()
        .id(ProfileId::new())
        .name("Blank")
        .email("")
        .build()
        .unwrap();
    let err = match profiles.create(profile).await {
        Err(e) => e,
        Ok(_) => panic!("expected constraint violation"),
    };

    assert!(!err.was_duplicate());
    assert!(err.was_check_violation());
    assert!(!err.was_foreign_key_violation());
    assert_eq!(err.constraint_name(), Some("profiles_email_not_blank"));
    assert_eq!(
        err.violated_constraint(),
        Some(ProfileConstraint::EmailNotBlank)
    );
    assert_eq!(
        ProfileConstraint::EmailNotBlank.kind(),
        ConstraintKind::Check
    );
    assert_eq!(err.duplicate_value(), None);
    match &err {
        ProfileCreateError::ConstraintViolation { column: None, .. } => {}
        other => panic!("expected ConstraintViolation without column, got: {other:?}"),
    }

    Ok(())
}

#[tokio::test]
async fn update_check_violation_returns_constraint_violation() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let profiles = Profiles::new(pool);

    let email = format!("check_{}@test.com", ProfileId::new());
    let profile = NewProfile::builder()
        .id(ProfileId::new())
        .name("Check")
        .email(&email)
        .build()
        .unwrap();
    let mut profile = profiles.create(profile).await?;

    let _ = profile.update_email(String::new());
    let err = match profiles.update(&mut profile).await {
        Err(e) => e,
        Ok(_) => panic!("expected constraint violation"),
    };

    assert!(!err.was_duplicate());
    assert!(err.was_check_violation());
    assert_eq!(err.constraint_name(), Some("profiles_email_not_blank"));
    assert_eq!(
        err.violated_constraint(),
        Some(ProfileConstraint::EmailNotBlank)
    );
    match &err {
        ProfileModifyError::ConstraintViolation { column: None, .. } => {}
        other => panic!("expected ConstraintViolation without column, got: {other:?}"),
    }

    Ok(())
}

// ===========================================================================
// Not-found error tests
// ===========================================================================

#[tokio::test]
async fn find_by_id_not_found_has_column_and_value() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let users = Users::new(pool);

    let missing_id = UserId::new();
    let err = match users.find_by_id(missing_id).await {
        Err(e) => e,
        Ok(_) => panic!("expected NotFound error"),
    };

    // Column-agnostic check
    assert!(err.was_not_found());

    // Column-specific check
    assert!(err.was_not_found_by(UserColumn::Id));
    assert!(!err.was_not_found_by(UserColumn::Name));

    // Value should use Display format and be parseable back into the ID type
    let value = err.not_found_value().expect("should have a value");
    let parsed: UserId = value
        .parse()
        .expect("not_found_value should be parseable as UserId");
    assert_eq!(parsed, missing_id);

    // Pattern matching on the variant
    match &err {
        UserFindError::NotFound {
            column: Some(UserColumn::Id),
            value,
            ..
        } => {
            let parsed: UserId = value.parse().expect("value should be parseable as UserId");
            assert_eq!(parsed, missing_id);
        }
        other => panic!("expected NotFound with column Id, got: {other:?}"),
    }

    Ok(())
}

#[tokio::test]
async fn find_by_name_not_found_has_column_and_value() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let users = Users::new(pool);

    let missing_name = format!("nonexistent_{}", UserId::new());
    let err = match users.find_by_name(&missing_name).await {
        Err(e) => e,
        Ok(_) => panic!("expected NotFound error"),
    };

    assert!(err.was_not_found());
    assert!(err.was_not_found_by(UserColumn::Name));
    assert!(!err.was_not_found_by(UserColumn::Id));

    let value = err.not_found_value().expect("should have a value");
    assert!(
        value.contains(&missing_name),
        "not_found_value should contain the name: got {value}"
    );

    // Pattern matching on the variant
    match &err {
        UserFindError::NotFound {
            column: Some(UserColumn::Name),
            ..
        } => {}
        other => panic!("expected NotFound with column Name, got: {other:?}"),
    }

    Ok(())
}