distributed 4.0.2

CQRS/ES framework for Rust using Plain Old Rust Structs — append-only events, replay, snapshots, outbox, service bus, and pluggable infrastructure
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
use sqlx::{Database, Encode, Executor, IntoArguments, QueryBuilder, Row, Transaction, Type};

use super::{
    initial_row_version, patch_values_preserving_key, push_key_predicates, quote_identifier,
    row_concurrency_conflict, row_values_from_key_and_patch, row_write_values,
    validate_row_expected_version, validate_sql_write_plan, validate_values_match_key,
    version_column, SqlxReadModelBackend,
};
use crate::sqlx_repo::{
    read_model_i64_from_u64, read_model_storage_error, read_model_u64_from_i64,
};
use crate::table::{
    key_fingerprint, validate_key, validate_row_values, DeleteTableRowMutation, ExpectedVersion,
    PatchMode, PatchTableRowMutation, RowKey, RowValue, RowValues, RowWriteMode, TableColumn,
    TableCommitOutcome, TableMutation, TableRowMutation, TableSchema, TableStoreError,
    TableWritePlan,
};

pub(crate) async fn begin_read_model_tx<DB: SqlxReadModelBackend>(
    pool: &sqlx::Pool<DB>,
) -> Result<Transaction<'_, DB>, TableStoreError> {
    pool.begin()
        .await
        .map_err(|err| read_model_storage_error(DB::BACKEND, "begin transaction", err))
}

pub(crate) async fn commit_read_model_tx<DB: SqlxReadModelBackend>(
    tx: Transaction<'_, DB>,
) -> Result<(), TableStoreError> {
    tx.commit()
        .await
        .map_err(|err| read_model_storage_error(DB::BACKEND, "commit transaction", err))
}

/// Full pool→tx→commit helper kept for adapter authors; production paths use the
/// split begin/apply/commit helpers above.
#[allow(dead_code)]
pub(crate) async fn commit_read_model_write_plan<DB>(
    pool: &sqlx::Pool<DB>,
    plan: TableWritePlan,
    notify_enabled: bool,
) -> Result<TableCommitOutcome, TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    validate_sql_write_plan(&plan)?;
    let tables: std::collections::BTreeSet<String> = plan
        .mutations
        .iter()
        .map(|m| m.table_name().to_string())
        .collect();
    let mut tx = begin_read_model_tx(pool).await?;
    let outcome = apply_read_model_write_plan_in_tx(&mut tx, plan).await?;
    if notify_enabled && !tables.is_empty() {
        DB::push_change_notify(&mut *tx, &tables).await?;
    }
    commit_read_model_tx(tx).await?;
    Ok(outcome)
}

pub(crate) async fn apply_read_model_write_plan_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    plan: TableWritePlan,
) -> Result<TableCommitOutcome, TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    validate_sql_write_plan(&plan)?;

    for mutation in plan.mutations {
        match mutation {
            TableMutation::UpsertRow(mutation) => {
                upsert_relational_row_in_tx(tx, mutation).await?;
            }
            TableMutation::PatchRow(mutation) => {
                patch_relational_row_in_tx(tx, mutation).await?;
            }
            TableMutation::DeleteRow(mutation) => {
                delete_relational_row_in_tx(tx, mutation).await?;
            }
        }
    }

    Ok(TableCommitOutcome::applied())
}

pub(crate) async fn upsert_relational_row_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    mutation: TableRowMutation,
) -> Result<(), TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    validate_key(mutation.schema, &mutation.key)?;
    validate_row_values(mutation.schema, &mutation.values, true)?;
    validate_values_match_key(mutation.schema, &mutation.key, &mutation.values)?;

    // The common case — upsert without an optimistic-version check — is a single
    // `INSERT ... ON CONFLICT (pk) DO UPDATE` round trip. Only version-checked
    // writes need to observe the current row first.
    if matches!(mutation.mode, RowWriteMode::Upsert)
        && matches!(mutation.expected_version, ExpectedVersion::Any)
    {
        return upsert_relational_row_on_conflict_in_tx(tx, mutation.schema, &mutation.values)
            .await;
    }

    let current_version = row_version_in_tx(tx, mutation.schema, &mutation.key).await?;
    validate_row_expected_version(
        mutation.schema,
        &mutation.key,
        &mutation.expected_version,
        current_version,
    )?;
    if matches!(mutation.mode, RowWriteMode::Insert) && current_version.is_some() {
        return Err(row_concurrency_conflict(
            mutation.schema,
            &mutation.key,
            0,
            current_version.unwrap_or_default(),
        ));
    }

    match current_version {
        Some(expected_version) => {
            let rows_affected = update_relational_row_values_in_tx(
                tx,
                mutation.schema,
                &mutation.key,
                &mutation.values,
                Some(expected_version),
            )
            .await?;
            if rows_affected == 0 {
                let actual = row_version_in_tx(tx, mutation.schema, &mutation.key)
                    .await?
                    .unwrap_or(expected_version);
                return Err(row_concurrency_conflict(
                    mutation.schema,
                    &mutation.key,
                    expected_version,
                    actual,
                ));
            }
        }
        None => {
            insert_relational_row_in_tx(
                tx,
                mutation.schema,
                &mutation.values,
                initial_row_version(),
            )
            .await?;
        }
    }

    Ok(())
}

pub(crate) async fn patch_relational_row_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    mutation: PatchTableRowMutation,
) -> Result<(), TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    validate_key(mutation.schema, &mutation.key)?;

    // `NotExists` is the only shape that has to observe the row before writing;
    // `Any`/`Exact` run the UPDATE directly and only re-read on a miss to tell
    // "not found" apart from a version conflict.
    if matches!(mutation.expected_version, ExpectedVersion::NotExists) {
        let current_version = row_version_in_tx(tx, mutation.schema, &mutation.key).await?;
        validate_row_expected_version(
            mutation.schema,
            &mutation.key,
            &mutation.expected_version,
            current_version,
        )?;
        if !matches!(mutation.mode, PatchMode::InsertMissing) {
            return Err(TableStoreError::NotFound {
                collection: mutation.schema.table_name.clone(),
                id: key_fingerprint(&mutation.key),
            });
        }
        let values = row_values_from_key_and_patch(mutation.schema, &mutation.key, mutation.patch)?;
        return insert_relational_row_in_tx(tx, mutation.schema, &values, initial_row_version())
            .await;
    }

    let expected_version = match mutation.expected_version {
        ExpectedVersion::Exact(expected) => Some(expected),
        _ => None,
    };
    let patch_values =
        patch_values_preserving_key(mutation.schema, &mutation.key, &mutation.patch)?;
    let rows_affected = update_relational_columns_in_tx(
        tx,
        mutation.schema,
        &mutation.key,
        patch_values,
        expected_version,
    )
    .await?;
    if rows_affected == 0 {
        if let Some(expected_version) = expected_version {
            return match row_version_in_tx(tx, mutation.schema, &mutation.key).await? {
                Some(actual) => Err(row_concurrency_conflict(
                    mutation.schema,
                    &mutation.key,
                    expected_version,
                    actual,
                )),
                None => Err(TableStoreError::NotFound {
                    collection: mutation.schema.table_name.clone(),
                    id: key_fingerprint(&mutation.key),
                }),
            };
        }
        if matches!(mutation.mode, PatchMode::InsertMissing) {
            let values =
                row_values_from_key_and_patch(mutation.schema, &mutation.key, mutation.patch)?;
            insert_relational_row_in_tx(tx, mutation.schema, &values, initial_row_version())
                .await?;
        } else {
            return Err(TableStoreError::NotFound {
                collection: mutation.schema.table_name.clone(),
                id: key_fingerprint(&mutation.key),
            });
        }
    }

    Ok(())
}

pub(crate) async fn delete_relational_row_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    mutation: DeleteTableRowMutation,
) -> Result<(), TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    validate_key(mutation.schema, &mutation.key)?;

    match mutation.expected_version {
        // The row must not exist: nothing to delete, but surface a conflict if it does.
        ExpectedVersion::NotExists => {
            let current_version = row_version_in_tx(tx, mutation.schema, &mutation.key).await?;
            validate_row_expected_version(
                mutation.schema,
                &mutation.key,
                &mutation.expected_version,
                current_version,
            )?;
            Ok(())
        }
        // No version check: one DELETE; deleting a missing row is a no-op.
        ExpectedVersion::Any => {
            delete_relational_row_where_version_in_tx(tx, mutation.schema, &mutation.key, None)
                .await?;
            Ok(())
        }
        // Version-checked delete: only re-read on a miss to tell "not found"
        // apart from a version conflict.
        ExpectedVersion::Exact(expected_version) => {
            let rows_affected = delete_relational_row_where_version_in_tx(
                tx,
                mutation.schema,
                &mutation.key,
                Some(expected_version),
            )
            .await?;
            if rows_affected == 0 {
                return match row_version_in_tx(tx, mutation.schema, &mutation.key).await? {
                    Some(actual) => Err(row_concurrency_conflict(
                        mutation.schema,
                        &mutation.key,
                        expected_version,
                        actual,
                    )),
                    None => Err(TableStoreError::NotFound {
                        collection: mutation.schema.table_name.clone(),
                        id: key_fingerprint(&mutation.key),
                    }),
                };
            }
            Ok(())
        }
    }
}

pub(crate) async fn row_version_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    schema: &TableSchema,
    key: &RowKey,
) -> Result<Option<u64>, TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    let version_column = version_column(schema)?;
    let mut builder = QueryBuilder::<DB>::new("SELECT ");
    builder.push(quote_identifier(version_column));
    builder.push(" FROM ");
    builder.push(quote_identifier(&schema.table_name));
    push_key_predicates(&mut builder, schema, key)?;

    let row = builder
        .build()
        .fetch_optional(&mut **tx)
        .await
        .map_err(|err| read_model_storage_error(DB::BACKEND, "load relational row version", err))?;

    row.map(|row| {
        read_model_u64_from_i64(
            DB::BACKEND,
            row.try_get::<i64, _>(version_column).map_err(|err| {
                read_model_storage_error(DB::BACKEND, "decode relational row version", err)
            })?,
            version_column,
        )
    })
    .transpose()
}

pub(crate) async fn insert_relational_row_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    schema: &TableSchema,
    values: &RowValues,
    version: u64,
) -> Result<(), TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    let version_column = version_column(schema)?;
    let write_values = row_write_values(schema, values)?;
    let has_write_values = !write_values.is_empty();
    let mut builder = QueryBuilder::<DB>::new("INSERT INTO ");
    builder.push(quote_identifier(&schema.table_name));
    builder.push(" (");
    for (index, (column, _)) in write_values.iter().enumerate() {
        if index > 0 {
            builder.push(", ");
        }
        builder.push(quote_identifier(&column.column_name));
    }
    if has_write_values {
        builder.push(", ");
    }
    builder.push(quote_identifier(version_column));
    builder.push(") VALUES (");
    for (index, (column, value)) in write_values.into_iter().enumerate() {
        if index > 0 {
            builder.push(", ");
        }
        DB::push_row_value_bind(&mut builder, value, column)?;
    }
    if has_write_values {
        builder.push(", ");
    }
    builder.push_bind(read_model_i64_from_u64(
        DB::BACKEND,
        version,
        version_column,
        DB::INTEGER_STORAGE,
    )?);
    builder.push(")");

    builder
        .build()
        .execute(&mut **tx)
        .await
        .map_err(|err| read_model_storage_error(DB::BACKEND, "insert relational row", err))?;

    Ok(())
}

/// Upsert one row in a single statement: `INSERT ... ON CONFLICT (pk) DO UPDATE
/// SET <non-pk columns> = excluded.<column>, <version> = <version> + 1`.
///
/// Both Postgres and SQLite (≥ 3.35) support `ON CONFLICT` with an explicit
/// column-list target and the `excluded` pseudo-table. New rows start at
/// version 1; conflicting rows bump their version in-database (an increment
/// past `i64::MAX` fails as a storage error).
pub(crate) async fn upsert_relational_row_on_conflict_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    schema: &TableSchema,
    values: &RowValues,
) -> Result<(), TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    let version_column = version_column(schema)?;
    let write_values = row_write_values(schema, values)?;
    let mut builder = QueryBuilder::<DB>::new("INSERT INTO ");
    builder.push(quote_identifier(&schema.table_name));
    builder.push(" (");
    for (column, _) in &write_values {
        builder.push(quote_identifier(&column.column_name));
        builder.push(", ");
    }
    builder.push(quote_identifier(version_column));
    builder.push(") VALUES (");
    for (column, value) in write_values.iter().cloned() {
        DB::push_row_value_bind(&mut builder, value, column)?;
        builder.push(", ");
    }
    builder.push_bind(read_model_i64_from_u64(
        DB::BACKEND,
        initial_row_version(),
        version_column,
        DB::INTEGER_STORAGE,
    )?);
    builder.push(") ON CONFLICT (");
    for (index, column_name) in schema.primary_key.columns.iter().enumerate() {
        if index > 0 {
            builder.push(", ");
        }
        builder.push(quote_identifier(column_name));
    }
    builder.push(") DO UPDATE SET ");
    for (column, _) in write_values
        .iter()
        .filter(|(column, _)| !column.primary_key)
    {
        builder.push(quote_identifier(&column.column_name));
        builder.push(" = excluded.");
        builder.push(quote_identifier(&column.column_name));
        builder.push(", ");
    }
    // Qualify the existing-row reference with the table name: inside `DO UPDATE`
    // an unqualified column is ambiguous with `excluded` on Postgres.
    builder.push(quote_identifier(version_column));
    builder.push(" = ");
    builder.push(quote_identifier(&schema.table_name));
    builder.push(".");
    builder.push(quote_identifier(version_column));
    builder.push(" + 1");

    builder
        .build()
        .execute(&mut **tx)
        .await
        .map_err(|err| read_model_storage_error(DB::BACKEND, "upsert relational row", err))?;

    Ok(())
}

pub(crate) async fn update_relational_row_values_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    schema: &TableSchema,
    key: &RowKey,
    values: &RowValues,
    expected_version: Option<u64>,
) -> Result<u64, TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    let mut write_values = row_write_values(schema, values)?;
    write_values.retain(|(column, _)| !column.primary_key);
    update_relational_columns_in_tx(tx, schema, key, write_values, expected_version).await
}

/// `UPDATE <table> SET <columns>, <version> = <version> + 1 WHERE <pk> [AND
/// <version> = <expected>]`, returning the affected-row count. The version bump
/// happens in-database; an increment past `i64::MAX` fails as a storage error.
pub(crate) async fn update_relational_columns_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    schema: &TableSchema,
    key: &RowKey,
    write_values: Vec<(&TableColumn, RowValue)>,
    expected_version: Option<u64>,
) -> Result<u64, TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    let version_column = version_column(schema)?;
    let mut builder = QueryBuilder::<DB>::new("UPDATE ");
    builder.push(quote_identifier(&schema.table_name));
    builder.push(" SET ");
    for (column, value) in write_values {
        builder.push(quote_identifier(&column.column_name));
        builder.push(" = ");
        DB::push_row_value_bind(&mut builder, value, column)?;
        builder.push(", ");
    }
    builder.push(quote_identifier(version_column));
    builder.push(" = ");
    builder.push(quote_identifier(version_column));
    builder.push(" + 1");
    push_key_predicates(&mut builder, schema, key)?;
    if let Some(expected_version) = expected_version {
        builder.push(" AND ");
        builder.push(quote_identifier(version_column));
        builder.push(" = ");
        builder.push_bind(read_model_i64_from_u64(
            DB::BACKEND,
            expected_version,
            "expected version",
            DB::INTEGER_STORAGE,
        )?);
    }

    let result = builder
        .build()
        .execute(&mut **tx)
        .await
        .map_err(|err| read_model_storage_error(DB::BACKEND, "update relational row", err))?;
    Ok(DB::rows_affected(&result))
}

pub(crate) async fn delete_relational_row_where_version_in_tx<DB>(
    tx: &mut Transaction<'_, DB>,
    schema: &TableSchema,
    key: &RowKey,
    expected_version: Option<u64>,
) -> Result<u64, TableStoreError>
where
    DB: SqlxReadModelBackend,
    for<'c> &'c mut <DB as Database>::Connection: Executor<'c, Database = DB>,
    <DB as Database>::Arguments: IntoArguments<DB>,
    for<'q> i64: Encode<'q, DB> + Type<DB> + sqlx::Decode<'q, DB>,
    for<'r> &'r str: sqlx::ColumnIndex<<DB as Database>::Row>,
{
    let mut builder = QueryBuilder::<DB>::new("DELETE FROM ");
    builder.push(quote_identifier(&schema.table_name));
    push_key_predicates(&mut builder, schema, key)?;
    if let Some(version) = expected_version {
        let version_column = version_column(schema)?;
        builder.push(" AND ");
        builder.push(quote_identifier(version_column));
        builder.push(" = ");
        builder.push_bind(read_model_i64_from_u64(
            DB::BACKEND,
            version,
            "expected version",
            DB::INTEGER_STORAGE,
        )?);
    }

    let result = builder
        .build()
        .execute(&mut **tx)
        .await
        .map_err(|err| read_model_storage_error(DB::BACKEND, "delete relational row", err))?;
    Ok(DB::rows_affected(&result))
}