navree-orm 1.2.1

Navree ORM: active-record models, a typed query builder, dirty tracking and pagination on PostgreSQL/TimescaleDB, MySQL and SQLite.
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! The persistence flows of a [`Record`]: insert, update, delete, refresh,
//! touch and increment, with their lifecycle hooks, timestamps, generated
//! keys and change events.
//!
//! Insert: `saving` → `creating` → generate an empty key → fill empty
//! timestamps → `INSERT` → read a database-assigned key back → `created`
//! change event → `created` → `saved` → sync the original.
//!
//! Update: `saving` → (only when dirty) `updating` → `updated_at` unless
//! the caller changed it → `UPDATE` of the dirty columns by the original
//! key → sync the changes → `updated` change event → `updated` → `saved` →
//! sync the original. A clean record still runs `saving` and `saved`.
//!
//! Delete: `deleting` → `DELETE` (soft-deleting models: `UPDATE` of the
//! deleted-at and updated-at columns, unless the record is being force
//! deleted) → `deleted` change event → (`trashed` for a soft delete) →
//! `deleted`.

use std::borrow::Cow;

use navree_db::{ChangeEvent, ChangeOp};

use crate::attributes::{CastContext, in_model_scope};
use crate::column::{Assignment, Column};
use crate::error::{OrmError, Result};
use crate::exec::{ExecContext, Target};
use crate::hooks::{Flow, Hooks, ModelEvent};
use crate::ir::{
    ArithmeticOp, ColumnRef, DeleteIr, Expr, InsertIr, OnConflict, Operator, TableRef, UpdateIr,
    Where, WhereClause,
};
use crate::model::{KeyKind, Model, PrimaryKey};
use crate::query::Builder;
use crate::record::Record;
use crate::value::{Field, Kind, Numeric, Value, is_null, to_json};

/// `WHERE table.key = key`.
fn by_key<M: Model>(key: &M::Key) -> Vec<WhereClause> {
    let meta = M::meta();
    vec![WhereClause::and(Where::Compare {
        left: Expr::Column(ColumnRef::new(Some(meta.table()), meta.key_column())),
        op: Operator::Eq,
        right: Expr::Value(key.to_value()),
    })]
}

/// The key the stored row has: the original one (the key column may have
/// been changed in memory).
fn stored_key<M: Model>(record: &Record<M>) -> M::Key {
    match &record.original {
        Some(original) => original.key(),
        None => record.model.key(),
    }
}

/// The conditions identifying `record`'s stored row: its key and, for a
/// pivot model without an `id` column (`#[model(pivot(..))]`, keyed by one
/// pivot column), the other pivot column too.
fn identity<M: Model>(record: &Record<M>) -> Result<Vec<WhereClause>> {
    let meta = M::meta();
    let mut wheres = by_key::<M>(&stored_key(record));
    // A pivot model keyed by one of its two pivot keys is identified by
    // both; one with an id of its own, by the id alone.
    let pivot_keys = meta.pivot_key_columns().filter(|(foreign, related)| {
        meta.key_column() == *foreign || meta.key_column() == *related
    });
    if let Some((foreign, related)) = pivot_keys {
        let other = if meta.key_column() == related {
            foreign
        } else {
            related
        };
        let source = record.original.as_ref().unwrap_or(&record.model);
        let value = source
            .value(other)?
            .ok_or_else(|| crate::model::derive_support::unknown_column::<M>(other))?;
        wheres.push(WhereClause::and(Where::Compare {
            left: Expr::Column(ColumnRef::new(Some(meta.table()), other)),
            op: Operator::Eq,
            right: Expr::Value(value),
        }));
    }
    Ok(wheres)
}

/// `values` as a JSON object (change events).
fn json_object(values: &[(&'static str, Value)]) -> serde_json::Value {
    serde_json::Value::Object(
        values
            .iter()
            .map(|(column, value)| ((*column).to_owned(), to_json(value)))
            .collect(),
    )
}

/// Records a change where the target keeps them: the unit of work the
/// statement ran in, or a document store's recorder.
fn record_change<M: Model>(
    target: &Target<'_>,
    key: &M::Key,
    op: ChangeOp,
    old: Option<serde_json::Value>,
    new: Option<serde_json::Value>,
) {
    target.record_change(ChangeEvent {
        entity: M::meta().table().to_owned(),
        id: key.to_key_string(),
        op,
        old,
        new,
    });
}

/// Runs the casts' asynchronous preparation of `record` (hashing, rounding
/// to the stored precision) before its values are written.
async fn prepare<M: Model>(record: &mut Record<M>) -> Result<()> {
    let context = CastContext::current();
    record.model.prepare_for_write(&context).await
}

/// Inserts or updates `record`.
pub(crate) async fn save<M: Model>(target: &Target<'_>, record: &mut Record<M>) -> Result<bool> {
    let ctx = target.context();
    in_model_scope::<M, _, _>(&ctx, save_in_scope(target, &ctx, record)).await
}

async fn save_in_scope<M: Model>(
    target: &Target<'_>,
    ctx: &ExecContext,
    record: &mut Record<M>,
) -> Result<bool> {
    let ctx = ctx.clone();
    let hooks = Hooks::<M>::resolve(&ctx).await?;
    if hooks.before(ModelEvent::Saving, &ctx, record).await? == Flow::Cancel {
        return Ok(false);
    }
    let changed = !record.exists || record.is_dirty();
    let saved = if record.exists {
        if record.is_dirty() {
            update(target, &ctx, &hooks, record).await?
        } else {
            true
        }
    } else {
        insert(target, &ctx, &hooks, record, None).await?
    };
    if !saved {
        return Ok(false);
    }
    hooks.after(ModelEvent::Saved, &ctx, record).await?;
    if changed {
        crate::relations::touch::touch_owners(target, record).await?;
    }
    record.sync_original();
    record.keep_cast_context();
    Ok(true)
}

/// Inserts the new `record` like [`save`] does; with `on_conflict`, a row
/// that conflicts with a unique index is skipped and `false` returned (the
/// record stays new, and no hook after `creating` runs).
pub(crate) async fn save_new<M: Model>(
    target: &Target<'_>,
    record: &mut Record<M>,
    on_conflict: Option<OnConflict>,
) -> Result<bool> {
    let ctx = target.context();
    let hooks = Hooks::<M>::resolve(&ctx).await?;
    if hooks.before(ModelEvent::Saving, &ctx, record).await? == Flow::Cancel {
        return Ok(false);
    }
    if !insert(target, &ctx, &hooks, record, on_conflict).await? {
        return Ok(false);
    }
    hooks.after(ModelEvent::Saved, &ctx, record).await?;
    record.sync_original();
    Ok(true)
}

async fn insert<M: Model>(
    target: &Target<'_>,
    ctx: &ExecContext,
    hooks: &Hooks<M>,
    record: &mut Record<M>,
    on_conflict: Option<OnConflict>,
) -> Result<bool> {
    if hooks.before(ModelEvent::Creating, ctx, record).await? == Flow::Cancel {
        return Ok(false);
    }
    let meta = M::meta();

    let mut assigned_by_database = false;
    if record.model.key().is_empty() {
        match meta.key_kind() {
            KeyKind::Increments => assigned_by_database = true,
            KeyKind::Manual => {
                return Err(OrmError::MissingKey {
                    model: Cow::Borrowed(meta.name()),
                    column: meta.key_column(),
                });
            }
            kind => {
                let key = M::Key::generate(kind).ok_or_else(|| {
                    OrmError::invalid(format!(
                        "{}'s key type {kind:?} cannot be generated for its key field of type {}",
                        meta.name(),
                        M::Key::type_name()
                    ))
                })?;
                record.model.set_key(key);
            }
        }
    }

    if meta.uses_timestamps() {
        let now = ctx.now().await;
        for column in [meta.created_at(), meta.updated_at()].into_iter().flatten() {
            if record.model.timestamp_is_empty(column) {
                record.model.touch_timestamp(column, now)?;
            }
        }
    }

    prepare(record).await?;
    let values = record.model.values()?;
    let (columns, row): (Vec<Cow<'static, str>>, Vec<Expr>) = values
        .iter()
        .filter(|(column, _)| !(assigned_by_database && *column == meta.key_column()))
        .map(|(column, value)| (Cow::Borrowed(*column), Expr::Value(value.clone())))
        .unzip();
    let mut insert =
        InsertIr::new(meta.table(), columns, vec![row]).returning(if assigned_by_database {
            vec![Cow::Borrowed(meta.key_column())]
        } else {
            Vec::new()
        });
    let skips_conflicts = on_conflict.is_some();
    insert.on_conflict = on_conflict;
    let outcome = target.insert(&insert).await?;
    if skips_conflicts && outcome.rows_affected == 0 {
        // The row conflicted and was skipped: the record stays new.
        return Ok(false);
    }

    if assigned_by_database {
        let key = match (outcome.returned.first(), outcome.last_insert_id) {
            (Some(row), _) => row.value(meta.key_column())?,
            (None, Some(id)) => Value::U64(id),
            (None, None) => {
                return Err(OrmError::invalid(format!(
                    "the database did not return the key of the new {}",
                    meta.name()
                )));
            }
        };
        record.model.set_value(meta.key_column(), key)?;
    }

    record.exists = true;
    record.recently_created = true;
    record.changes.clear();
    record.previous.clear();
    let key = record.model.key();
    let stored = record.model.values()?;
    record_change::<M>(
        target,
        &key,
        ChangeOp::Created,
        None,
        Some(json_object(&stored)),
    );
    hooks.after(ModelEvent::Created, ctx, record).await?;
    Ok(true)
}

async fn update<M: Model>(
    target: &Target<'_>,
    ctx: &ExecContext,
    hooks: &Hooks<M>,
    record: &mut Record<M>,
) -> Result<bool> {
    if hooks.before(ModelEvent::Updating, ctx, record).await? == Flow::Cancel {
        return Ok(false);
    }
    let meta = M::meta();
    if let Some(updated_at) = meta.updated_at()
        && !record.is_dirty_on([updated_at])
    {
        let now = ctx.now().await;
        record.model.touch_timestamp(updated_at, now)?;
    }
    prepare(record).await?;
    let dirty = record.get_dirty()?;
    if dirty.is_empty() {
        return Ok(true);
    }
    let key = stored_key(record);
    let update = UpdateIr {
        table: TableRef::new(meta.table()),
        sets: dirty
            .iter()
            .map(|(column, value)| (Cow::Borrowed(*column), Expr::Value(value.clone())))
            .collect(),
        wheres: identity(record)?,
    };
    target.update(&update).await?;
    record.sync_changes(dirty)?;
    record_change::<M>(
        target,
        &key,
        ChangeOp::Updated,
        Some(json_object(&record.previous)),
        Some(json_object(&record.changes)),
    );
    hooks.after(ModelEvent::Updated, ctx, record).await?;
    Ok(true)
}

/// Deletes `record`: soft-deletes it when the model soft-deletes (firing
/// `deleting`, `trashed`, `deleted`), removes the row otherwise or while
/// the record is being force deleted (`deleting`, `deleted`).
pub(crate) async fn delete<M: Model>(target: &Target<'_>, record: &mut Record<M>) -> Result<bool> {
    if !record.exists {
        return Ok(false);
    }
    let ctx = target.context();
    in_model_scope::<M, _, _>(&ctx, delete_in_scope(target, &ctx, record)).await
}

async fn delete_in_scope<M: Model>(
    target: &Target<'_>,
    ctx: &ExecContext,
    record: &mut Record<M>,
) -> Result<bool> {
    let ctx = ctx.clone();
    let hooks = Hooks::<M>::resolve(&ctx).await?;
    if hooks.before(ModelEvent::Deleting, &ctx, record).await? == Flow::Cancel {
        return Ok(false);
    }
    // The owners are touched while the row (and its pivot rows) still
    // exist.
    crate::relations::touch::touch_owners(target, record).await?;
    let meta = M::meta();
    let key = stored_key(record);
    let wheres = identity(record)?;
    let before = match &record.original {
        Some(original) => original.values()?,
        None => record.model.values()?,
    };

    match meta.deleted_at().filter(|_| !record.force_deleting) {
        Some(deleted_at) => {
            let now = ctx.now().await;
            record.model.touch_timestamp(deleted_at, now)?;
            let mut columns = vec![deleted_at];
            if let Some(updated_at) = meta.updated_at() {
                record.model.touch_timestamp(updated_at, now)?;
                columns.push(updated_at);
            }
            let mut sets = Vec::with_capacity(columns.len());
            for column in &columns {
                let value = record
                    .model
                    .value(column)?
                    .ok_or_else(|| crate::model::derive_support::unknown_column::<M>(column))?;
                sets.push((Cow::Borrowed(*column), Expr::Value(value)));
            }
            let update = UpdateIr {
                table: TableRef::new(meta.table()),
                sets,
                wheres,
            };
            target.update(&update).await?;
            record.sync_original_on(columns)?;
            record_change::<M>(
                target,
                &key,
                ChangeOp::Deleted,
                Some(json_object(&before)),
                None,
            );
            hooks.after(ModelEvent::Trashed, &ctx, record).await?;
            hooks.after(ModelEvent::Deleted, &ctx, record).await?;
        }
        None => {
            let delete = DeleteIr {
                table: TableRef::new(meta.table()),
                wheres,
            };
            target.delete(&delete).await?;
            record.exists = false;
            record_change::<M>(
                target,
                &key,
                ChangeOp::Deleted,
                Some(json_object(&before)),
                None,
            );
            hooks.after(ModelEvent::Deleted, &ctx, record).await?;
        }
    }
    Ok(true)
}

/// The stored row of `record`, read without global scopes.
async fn reload<M: Model>(target: &Target<'_>, record: &Record<M>) -> Result<Option<Record<M>>> {
    let mut query = Builder::<M>::new().without_global_scopes().limit(1);
    query.ir.wheres = identity(record)?;
    query
        .fetch(target)
        .await
        .map(|records| records.into_vec().into_iter().next())
}

/// Reloads `record`'s columns, and the relations it has loaded (pivots and
/// values set by hand stay as they are).
pub(crate) async fn refresh<M: Model>(target: &Target<'_>, record: &mut Record<M>) -> Result<()> {
    if !record.exists {
        return Ok(());
    }
    let fresh = reload(target, record).await?.ok_or_else(|| {
        OrmError::not_found(M::meta().name(), vec![stored_key(record).to_key_string()])
    })?;
    record.model = fresh.model;
    record.extras = fresh.extras;
    record.sync_original();
    record.attributes.stale = fresh.attributes.stale;
    if fresh.attributes.context.is_some() {
        record.attributes.context = fresh.attributes.context;
    }
    crate::relations::lazy::reload_relations(target, record).await
}

/// Reloads `record`'s columns and locks its row for update until the
/// transaction ends.
pub(crate) async fn refresh_for_update<M: Model>(
    target: &Target<'_>,
    record: &mut Record<M>,
) -> Result<()> {
    if !record.exists {
        return Err(Record::<M>::not_persisted("lock"));
    }
    let fresh = Builder::<M>::new()
        .without_global_scopes()
        .where_key(stored_key(record))
        .limit(1)
        .lock_for_update()
        .fetch(target)
        .await?
        .into_vec()
        .into_iter()
        .next()
        .ok_or_else(|| {
            OrmError::not_found(M::meta().name(), vec![stored_key(record).to_key_string()])
        })?;
    record.model = fresh.model;
    record.extras = fresh.extras;
    record.sync_original();
    Ok(())
}

/// `record` as stored now.
pub(crate) async fn fresh<M: Model>(
    target: &Target<'_>,
    record: &Record<M>,
) -> Result<Option<Record<M>>> {
    if !record.exists {
        return Ok(None);
    }
    reload(target, record).await
}

/// Sets the update timestamp (or `column`) to now and saves.
pub(crate) async fn touch<M: Model>(
    target: &Target<'_>,
    record: &mut Record<M>,
    column: Option<&str>,
) -> Result<bool> {
    let ctx = target.context();
    let meta = M::meta();
    match column {
        None => {
            let Some(updated_at) = meta.updated_at() else {
                return Ok(false);
            };
            let now = ctx.now().await;
            record.model.touch_timestamp(updated_at, now)?;
            if !record.exists
                && let Some(created_at) = meta.created_at()
                && record.model.timestamp_is_empty(created_at)
            {
                record.model.touch_timestamp(created_at, now)?;
            }
        }
        Some(column) => {
            let now = ctx.now().await;
            record.model.set_value(column, Value::Timestamp(now))?;
        }
    }
    save(target, record).await
}

/// `column = column ± amount` for each of `steps` on the stored record (in
/// one statement), plus `extra` columns and the update timestamp.
pub(crate) async fn increment<M: Model, T: Numeric>(
    target: &Target<'_>,
    record: &mut Record<M>,
    steps: Vec<(Column<M, T>, T)>,
    decrement: bool,
    extra: Vec<Assignment>,
) -> Result<bool> {
    let action = if decrement { "decrement" } else { "increment" };
    if !record.exists {
        return Err(Record::<M>::not_persisted(action));
    }
    let meta = M::meta();
    let names: Vec<String> = steps
        .iter()
        .map(|(column, _)| column.column_ref().name.into_owned())
        .collect();
    if names.is_empty() {
        return Err(OrmError::invalid(format!(
            "{action} needs at least one column of {}",
            meta.name()
        )));
    }
    if let Some(twice) = names
        .iter()
        .enumerate()
        .find_map(|(at, name)| names[..at].contains(name).then_some(name))
    {
        return Err(OrmError::invalid(format!(
            "{} `{twice}` of {} is listed twice: each column steps once per statement",
            if decrement {
                "decrementing"
            } else {
                "incrementing"
            },
            meta.name()
        )));
    }

    let mut amounts = Vec::with_capacity(steps.len());
    for ((_, amount), name) in steps.into_iter().zip(names) {
        let current = record
            .model
            .value(&name)?
            .ok_or_else(|| crate::model::derive_support::unknown_column::<M>(&name))?;
        let next = if is_null(&current) {
            current
        } else {
            let current = T::from_value(current).map_err(|error| {
                crate::row::decode_error(meta.name(), &name, T::type_name(), &error)
            })?;
            let next = if decrement {
                current.checked_sub(amount)
            } else {
                current.checked_add(amount)
            };
            next.ok_or_else(|| {
                OrmError::invalid(format!(
                    "{} `{name}` would overflow {}",
                    if decrement {
                        "decrementing"
                    } else {
                        "incrementing"
                    },
                    T::type_name()
                ))
            })?
            .to_value()
        };
        record.model.set_value(&name, next)?;
        amounts.push((name, amount.to_value()));
    }
    let ctx = target.context();
    in_model_scope::<M, _, _>(
        &ctx,
        apply_increment(target, &ctx, record, amounts, decrement, extra),
    )
    .await
}

/// `column = column ± amount` on the stored record through `column`'s cast
/// ([`Cast::increment`](crate::cast::Cast::increment)): the record's field
/// moves by `amount`, the database's column by `amount`'s stored form.
pub(crate) async fn increment_cast<M: Model, T>(
    target: &Target<'_>,
    record: &mut Record<M>,
    column: &Column<M, T>,
    amount: &T,
    decrement: bool,
    extra: Vec<Assignment>,
) -> Result<bool> {
    if !record.exists {
        return Err(Record::<M>::not_persisted(if decrement {
            "decrement"
        } else {
            "increment"
        }));
    }
    let ctx = target.context();
    let name = column.column_ref().name.into_owned();
    in_model_scope::<M, _, _>(&ctx, async {
        let stored = column.encode(amount).map_err(|message| OrmError::Cast {
            model: M::meta().name().into(),
            column: name.clone(),
            message,
        })?;
        if !is_number(&stored) {
            return Err(OrmError::invalid(format!(
                "`{name}` of {} stores {}, which the database cannot add to: increments through a cast need a numeric stored form",
                M::meta().name(),
                crate::value::describe(&stored)
            )));
        }
        record.model.increment_cast(&name, stored.clone(), decrement)?;
        apply_increment(
            target,
            &ctx,
            record,
            vec![(name.clone(), stored)],
            decrement,
            extra,
        )
        .await
    })
    .await
}

/// Whether `value` is a number the database can add to.
fn is_number(value: &Value) -> bool {
    matches!(
        value,
        Value::I8(_)
            | Value::I16(_)
            | Value::I32(_)
            | Value::I64(_)
            | Value::U8(_)
            | Value::U16(_)
            | Value::U32(_)
            | Value::U64(_)
            | Value::F32(_)
            | Value::F64(_)
            | Value::Decimal(_)
    )
}

/// Writes increments the record already holds in memory: `name = name ±
/// amount` for each of `amounts` (stored forms), plus `extra` columns and
/// the update timestamp, with the `updating` / `updated` hooks and the
/// change event.
async fn apply_increment<M: Model>(
    target: &Target<'_>,
    ctx: &ExecContext,
    record: &mut Record<M>,
    amounts: Vec<(String, Value)>,
    decrement: bool,
    extra: Vec<Assignment>,
) -> Result<bool> {
    let meta = M::meta();
    let mut sets: Vec<(Cow<'static, str>, Expr)> = Vec::with_capacity(amounts.len());
    let mut written = Vec::with_capacity(amounts.len());
    for (name, amount) in amounts {
        sets.push((
            Cow::Owned(name.clone()),
            Expr::Arithmetic {
                left: Box::new(Expr::Column(ColumnRef::new(None::<&str>, name.clone()))),
                op: if decrement {
                    ArithmeticOp::Sub
                } else {
                    ArithmeticOp::Add
                },
                right: Box::new(Expr::Value(amount)),
            },
        ));
        written.push(name);
    }
    for assignment in extra {
        let (extra_column, value) = assignment.into_set().map_err(OrmError::invalid)?;
        if let Expr::Value(value) = &value {
            record.model.set_value(&extra_column, value.clone())?;
        }
        written.push(extra_column.to_string());
        sets.push((extra_column, value));
    }
    if let Some(updated_at) = meta.updated_at()
        && !written.iter().any(|column| column == updated_at)
    {
        let now = ctx.now().await;
        record.model.touch_timestamp(updated_at, now)?;
        let value = record
            .model
            .value(updated_at)?
            .unwrap_or(Value::Null(Kind::String));
        sets.push((Cow::Borrowed(updated_at), Expr::Value(value)));
        written.push(updated_at.to_owned());
    }

    let hooks = Hooks::<M>::resolve(ctx).await?;
    // Cancelled: the new values stay on the record, unsaved (dirty).
    if hooks.before(ModelEvent::Updating, ctx, record).await? == Flow::Cancel {
        return Ok(false);
    }
    let key = stored_key(record);
    let update = UpdateIr {
        table: TableRef::new(meta.table()),
        sets,
        wheres: identity(record)?,
    };
    target.update(&update).await?;
    let dirty = record.get_dirty()?;
    record.sync_changes(dirty)?;
    record_change::<M>(
        target,
        &key,
        ChangeOp::Updated,
        Some(json_object(&record.previous)),
        Some(json_object(&record.changes)),
    );
    hooks.after(ModelEvent::Updated, ctx, record).await?;
    record.sync_original_on(written.iter().map(String::as_str))?;
    Ok(true)
}