glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
//! Changesets: the one way records are written, with validation.
//!
//! Borrowed from Ecto. A changeset collects the changes to apply to a record
//! (new or existing), validates them, and is either saved or handed back
//! with errors to re-render the form. Most code never builds one by hand:
//! `#[model]` declares the validations and params are cast for you.
//!
//! ```no_run
//! use glacier::prelude::*;
//!
//! #[glacier::model]
//! struct Post {
//!     #[validate(required, length = 3..=120)]
//!     title: String,
//! }
//!
//! # async fn create(ctx: Context) -> Result {
//! match Post::create(ctx.params()).await? {
//!     Saved(post) => redirect!(post, notice: "Created."),
//!     Invalid(changeset) => Ok(Response::text(changeset.full_messages().join(", "))),
//! }
//! # }
//! ```
//!
//! By hand, for writes that don't come from a form:
//!
//! ```no_run
//! # use glacier::prelude::*;
//! # #[glacier::model] struct Post { title: String }
//! # async fn demo(post: Post) -> glacier::Result<()> {
//! let post = post.change().set(|p| p.title, "Renamed").update().await?.unwrap();
//! # Ok(()) }
//! ```

use std::fmt;
use std::ops::{Bound, RangeBounds};
use std::sync::atomic::{AtomicU64, Ordering};

use super::cast::Cast;
use super::query::Col;
use super::sql::{Dialect, Sql};
use super::value::{Timestamp, ToValue, Value};
use super::{Connection, current_in};
use crate::context::Params;
use crate::error::{Error, Result};
use crate::model::Model;

static SAVEPOINTS: AtomicU64 = AtomicU64::new(0);

/// The outcome of a save: the stored record, or the changeset back with
/// errors to re-render the form. `Saved` and `Invalid` are in the prelude.
#[derive(Debug)]
pub enum Save<M> {
    Saved(M),
    Invalid(Changeset<M>),
}

impl<M: Model> Save<M> {
    /// The saved record, if any.
    pub fn saved(self) -> Option<M> {
        match self {
            Save::Saved(record) => Some(record),
            Save::Invalid(_) => None,
        }
    }

    /// The saved record.
    ///
    /// # Panics
    ///
    /// If validation failed, listing the errors. Handy in tests and seeds.
    #[track_caller]
    pub fn unwrap(self) -> M {
        match self {
            Save::Saved(record) => record,
            Save::Invalid(changeset) => panic!(
                "expected a saved record, but it was invalid: {:?}",
                changeset.full_messages()
            ),
        }
    }

    /// The invalid changeset.
    ///
    /// # Panics
    ///
    /// If the record was saved.
    #[track_caller]
    pub fn unwrap_invalid(self) -> Changeset<M> {
        match self {
            Save::Invalid(changeset) => changeset,
            Save::Saved(_) => panic!("expected validation errors, but the record was saved"),
        }
    }
}

/// `Post::create(ctx.params())`: casts the model's permitted fields.
impl<M: Model> From<Params> for Changeset<M> {
    fn from(params: Params) -> Self {
        let mut changeset = M::from_params(&params);
        // Kept for the callbacks' record, which also takes the virtual
        // fields (a `password`) the columns don't hold.
        changeset.params = Some(Box::new(params));
        changeset
    }
}

pub struct Changeset<M> {
    data: Option<M>,
    changes: Vec<(&'static str, Value)>,
    errors: Vec<(&'static str, String)>,
    unique: Vec<&'static str>,
    /// Unique columns and the columns scoping them, checked by a query
    /// before writing, as Rails' `uniqueness` validation does.
    unique_scopes: Vec<(&'static str, Vec<&'static str>)>,
    conn: Option<Connection>,
    /// The params it was cast from, when it was (boxed: a `Save` is
    /// mostly its changeset).
    params: Option<Box<Params>>,
}

impl<M: Model> Default for Changeset<M> {
    fn default() -> Self {
        Self::new()
    }
}

impl<M: fmt::Debug> fmt::Debug for Changeset<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Changeset")
            .field("data", &self.data)
            .field("changes", &self.changes)
            .field("errors", &self.errors)
            .finish()
    }
}

impl<M: Model> Changeset<M> {
    /// A changeset for a new record.
    pub fn new() -> Self {
        Self {
            data: None,
            changes: Vec::new(),
            errors: Vec::new(),
            unique: Vec::new(),
            unique_scopes: Vec::new(),
            conn: None,
            params: None,
        }
    }

    /// A changeset for an existing record; usually via `record.change()`.
    pub fn for_record(record: M) -> Self {
        Self {
            data: Some(record),
            ..Self::new()
        }
    }

    /// A new record with these changes, for its callbacks: from params,
    /// one assigned from them (virtual fields and all), then each change
    /// set on it. `None` for a model without `Default`.
    pub(crate) fn new_record(&self) -> Option<M> {
        let mut record = M::blank()?;
        if let Some(params) = &self.params {
            record.assign(params);
        }
        for (column, value) in &self.changes {
            record.set_value(column, value.clone());
        }
        Some(record)
    }

    /// The record being updated, with the changes set on it, taken out
    /// for its callbacks, and what the changed fields held before, to put
    /// back if it turns out invalid; `attach` returns it.
    pub(crate) fn take_record(&mut self) -> Option<(M, Vec<(&'static str, Value)>)> {
        let mut record = self.data.take()?;
        let held: Vec<(&'static str, Value)> = record
            .values()
            .into_iter()
            .chain(record.attribute_values())
            .collect();
        let mut was = Vec::new();
        if let Some(params) = &self.params {
            for (column, value) in record.attribute_values() {
                if params.get(column).is_some() {
                    was.push((column, value));
                }
            }
            record.assign(params);
        }
        for (column, value) in &self.changes {
            if let Some((name, old)) = held.iter().find(|(c, _)| c == column) {
                was.push((*name, old.clone()));
            }
            record.set_value(column, value.clone());
        }
        Some((record, was))
    }

    /// Takes in what callbacks changed on `record` since `before` (its
    /// columns' values then): a slug made from the title, say.
    pub(crate) fn changed_by(mut self, record: &M, before: &[(&'static str, Value)]) -> Self {
        for (column, value) in record.values() {
            let was = before.iter().find(|(c, _)| *c == column).map(|(_, v)| v);
            if was != Some(&value) {
                self = self.put(column, value);
            }
        }
        self
    }

    pub(crate) fn data_mut(&mut self) -> Option<&mut M> {
        self.data.as_mut()
    }

    pub(crate) fn take_data(&mut self) -> Option<M> {
        self.data.take()
    }

    pub(crate) fn attach(mut self, record: M) -> Self {
        self.data = Some(record);
        self
    }

    /// Sets a column by name, from an already converted value.
    pub(crate) fn put(mut self, column: &'static str, value: Value) -> Self {
        self.changes.retain(|(n, _)| *n != column);
        self.changes.push((column, value));
        self
    }

    pub(crate) fn push_error(mut self, column: &'static str, message: String) -> Self {
        self.errors.push((column, message));
        self
    }

    /// Sets a column. Setting it again replaces the earlier value.
    pub fn set<T: ToValue>(
        mut self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        value: impl Into<T>,
    ) -> Self {
        let name = column(&M::columns()).name();
        let value = value.into().to_value();
        self.changes.retain(|(n, _)| *n != name);
        self.changes.push((name, value));
        self
    }

    /// Casts the column from `params` if present: sets it, or records why
    /// the text didn't fit ("is not a number"). Absent keys are left alone,
    /// so updates only touch what the form sent.
    pub fn cast<T: Cast + ToValue>(
        mut self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        params: &Params,
    ) -> Self {
        let name = column(&M::columns()).name();
        if let Some(raw) = params.get(name) {
            match T::cast(raw) {
                Ok(value) => {
                    self.changes.retain(|(n, _)| *n != name);
                    self.changes.push((name, value.to_value()));
                }
                Err(message) => {
                    // Keep the raw input so the form can show it again.
                    self.changes.retain(|(n, _)| *n != name);
                    self.changes.push((name, Value::Text(raw.to_owned())));
                    self.errors.push((name, message));
                }
            }
        }
        self
    }

    /// The column's value after the changes: the change if there is one,
    /// otherwise the record's current value.
    pub fn value(&self, column: &str) -> Option<Value> {
        self.changes
            .iter()
            .find(|(n, _)| *n == column)
            .map(|(_, v)| v.clone())
            .or_else(|| {
                let data = self.data.as_ref()?;
                data.values()
                    .into_iter()
                    .find(|(n, _)| *n == column)
                    .map(|(_, v)| v)
            })
    }

    /// The column's value as text, to refill a form field after a failed
    /// save: `<input name="title" value="{{ changeset.text("title") }}">`.
    pub fn text(&self, column: &str) -> String {
        self.value(column).map(|v| v.to_text()).unwrap_or_default()
    }

    pub fn changes(&self) -> &[(&'static str, Value)] {
        &self.changes
    }

    pub fn data(&self) -> Option<&M> {
        self.data.as_ref()
    }

    /// The changeset with its validation errors dropped, keeping what it
    /// writes and the uniqueness checks to run as it's written.
    pub(crate) fn without_errors(mut self) -> Self {
        self.errors.clear();
        self
    }

    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    /// The errors as Rails renders them in JSON: `{"title": ["can't be blank"]}`.
    pub fn errors_json(&self) -> serde_json::Value {
        crate::db::record::errors_json(&self.errors)
    }

    pub fn errors(&self) -> &[(&'static str, String)] {
        &self.errors
    }

    /// Error messages for one column, e.g. to show next to a form field.
    /// One field for a form, its value and errors, as a record's
    /// `field` gives: `<.input field={changeset.field("title")} />`.
    pub fn field(&self, column: &str) -> crate::view::Field {
        crate::view::Field::new(
            column,
            self.text(column),
            self.errors_on(column)
                .into_iter()
                .map(str::to_owned)
                .collect(),
        )
    }

    pub fn errors_on(&self, column: &str) -> Vec<&str> {
        self.errors
            .iter()
            .filter(|(n, _)| *n == column)
            .map(|(_, m)| m.as_str())
            .collect()
    }

    /// Error messages with the column name, as Rails shows them:
    /// `"Title can't be blank"`, `"Password confirmation doesn't match"`.
    pub fn full_messages(&self) -> Vec<String> {
        self.errors
            .iter()
            .map(|(n, m)| format!("{} {m}", humanize(n)))
            .collect()
    }

    /// Each error as `column message`, lower case (`title can't be
    /// blank`): what tests match on with `errors_on`.
    pub fn messages(&self) -> Vec<String> {
        self.errors
            .iter()
            .map(|(n, m)| format!("{} {m}", n.replace('_', " ")))
            .collect()
    }

    pub fn add_error<T>(
        mut self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        message: impl Into<String>,
    ) -> Self {
        let name = column(&M::columns()).name();
        self.errors.push((name, message.into()));
        self
    }

    /// Requires a non-null value that isn't empty or whitespace-only text.
    pub fn validate_required<T>(self, column: impl FnOnce(&M::Columns) -> Col<M, T>) -> Self {
        self.validate_required_message(column, "can't be blank")
    }

    /// [`validate_required`](Self::validate_required) with its own message,
    /// as Rails' `presence: {message: "…"}`.
    pub fn validate_required_message<T>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        message: &str,
    ) -> Self {
        self.validate_with(column, |value| {
            let blank = match value {
                None | Some(Value::Null) => true,
                Some(Value::Text(text)) => text.trim().is_empty(),
                Some(_) => false,
            };
            blank.then(|| message.to_owned())
        })
    }

    /// Requires the text's length (in characters) to fall within `range`.
    /// Missing values pass; combine with `validate_required` to forbid them.
    pub fn validate_length<T>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        range: impl RangeBounds<usize>,
    ) -> Self {
        let min = match range.start_bound() {
            Bound::Included(&n) => Some(n),
            Bound::Excluded(&n) => Some(n + 1),
            Bound::Unbounded => None,
        };
        let max = match range.end_bound() {
            Bound::Included(&n) => Some(n),
            Bound::Excluded(&n) => Some(n.saturating_sub(1)),
            Bound::Unbounded => None,
        };
        self.validate_with(column, move |value| {
            let Some(Value::Text(text)) = value else {
                return None;
            };
            let len = text.chars().count();
            match (min, max) {
                (Some(min), _) if len < min => {
                    Some(format!("is too short (minimum is {min} characters)"))
                }
                (_, Some(max)) if len > max => {
                    Some(format!("is too long (maximum is {max} characters)"))
                }
                _ => None,
            }
        })
    }

    /// Requires text to match a regular expression, as Rails' `format: {with:
    /// /…/}`: "is invalid" otherwise. Missing values pass.
    ///
    /// # Panics
    ///
    /// If `pattern` isn't a valid regular expression.
    pub fn validate_format<T>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        pattern: &str,
    ) -> Self {
        let regex = cached_regex(pattern);
        self.validate_with(column, |value| match value {
            Some(Value::Text(text)) if !regex.is_match(text) => Some("is invalid".to_owned()),
            _ => None,
        })
    }

    /// Requires the value to be one of `allowed` (compared as text), as
    /// Rails' `inclusion: {in: […]}`: "is not included in the list".
    /// Missing values pass.
    pub fn validate_inclusion<T>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        allowed: &[&str],
    ) -> Self {
        self.validate_with(column, |value| match value {
            None | Some(Value::Null) => None,
            Some(value) => (!allowed.contains(&value.to_text().as_str()))
                .then(|| "is not included in the list".to_owned()),
        })
    }

    /// Requires a number within the rules, with Rails' `numericality`
    /// messages ("is not a number", "must be greater than 0", "must be an
    /// integer"). Missing values pass.
    pub fn validate_numericality<T>(
        self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        rules: Numericality,
    ) -> Self {
        self.validate_with(column, move |value| {
            let number = match value {
                None | Some(Value::Null) => return None,
                Some(Value::Int(n)) => *n as f64,
                Some(Value::Float(n)) => *n,
                Some(Value::Decimal(n)) => n.to_string().parse().ok()?,
                Some(Value::Text(text)) => match text.trim().parse::<f64>() {
                    Ok(n) => n,
                    Err(_) => return Some("is not a number".to_owned()),
                },
                Some(_) => return Some("is not a number".to_owned()),
            };
            rules.check(number)
        })
    }

    /// Runs a custom check on the column's value (after changes); return
    /// `Some(message)` to add an error.
    ///
    /// Like Ecto, a column that already has an error isn't checked again,
    /// so a blank title reports "can't be blank" rather than also "is too
    /// short".
    pub fn validate_with<T>(
        mut self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        check: impl FnOnce(Option<&Value>) -> Option<String>,
    ) -> Self {
        let name = column(&M::columns()).name();
        if self.errors.iter().any(|(n, _)| *n == name) {
            return self;
        }
        let value = self.value(name);
        if let Some(message) = check(value.as_ref()) {
            self.errors.push((name, message));
        }
        self
    }

    /// Requires the column's value to be unique, as Rails' `uniqueness`:
    /// a query checks before writing, and if a unique index still rejects
    /// the write (a race), the changeset comes back with
    /// "has already been taken" on that column instead of an error.
    pub fn unique<T>(self, column: impl FnOnce(&M::Columns) -> Col<M, T>) -> Self {
        self.unique_scoped(column, &[])
    }

    /// [`unique`](Self::unique) among records with the same `scope`
    /// columns, as Rails' `uniqueness: {scope: :platform}`.
    pub fn unique_scoped<T>(
        mut self,
        column: impl FnOnce(&M::Columns) -> Col<M, T>,
        scope: &[&'static str],
    ) -> Self {
        let column = column(&M::columns()).name();
        self.unique.push(column);
        // On an owned model, unique within its owner (an org's names).
        let mut scope = scope.to_vec();
        for (owner, _) in M::OWNER {
            if *owner != column && !scope.contains(owner) {
                scope.push(owner);
            }
        }
        self.unique_scopes.push((column, scope));
        self
    }

    /// A column's value after this change: changed, or the record's.
    fn value_of(&self, column: &str) -> Value {
        if let Some((_, value)) = self.changes.iter().find(|(c, _)| *c == column) {
            return value.clone();
        }
        self.data
            .as_ref()
            .and_then(|data| data.values().into_iter().find(|(c, _)| *c == column))
            .map_or(Value::Null, |(_, value)| value)
    }

    /// For an owned model, checks each owned parent it names is the same
    /// tenant's: a note's `project_id` must be a project of the note's
    /// org, whatever params said. Otherwise "isn't one of yours".
    async fn check_parents(&mut self, conn: &Connection) -> Result<()> {
        if M::OWNER.is_empty() {
            return Ok(());
        }
        for parent in M::PARENTS {
            let changed = self.changes.iter().any(|(name, _)| *name == parent.column);
            if self.data.is_some() && !changed {
                continue;
            }
            let id = self.value_of(parent.column);
            if id == Value::Null {
                continue;
            }
            // The parent's owner columns this record shares (same key).
            let mut shared = Vec::new();
            for (parent_column, key) in parent.owner {
                if let Some((column, _)) = M::OWNER.iter().find(|(_, k)| k == key) {
                    shared.push((*parent_column, self.value_of(column)));
                }
            }
            if shared.is_empty() {
                continue;
            }
            let mut sql = Sql::new();
            sql.push("SELECT 1 FROM ")
                .push_ident(parent.table)
                .push(" WHERE ")
                .push_ident(parent.key)
                .push(" = ")
                .push_value(id);
            for (column, value) in shared {
                sql.push(" AND ")
                    .push_ident(column)
                    .push(" = ")
                    .push_value(value);
            }
            sql.push(" LIMIT 1");
            if conn.fetch_all(&sql).await?.is_empty() {
                self.errors
                    .push((parent.column, "isn't one of yours".to_owned()));
            }
        }
        Ok(())
    }

    /// Queries for records that already have each unique value, adding
    /// "has already been taken" for those that do.
    pub(crate) async fn check_unique(&mut self, conn: &Connection) -> Result<()> {
        self.check_parents(conn).await?;
        let checks = self.unique_scopes.clone();
        for (column, scope) in checks {
            let changed = |c: &str| self.changes.iter().any(|(name, _)| *name == c);
            if self.data.is_some() && !changed(column) && !scope.iter().any(|c| changed(c)) {
                continue;
            }
            let value = self.value_of(column);
            if value == Value::Null || self.errors.iter().any(|(c, _)| *c == column) {
                continue;
            }
            let mut sql = Sql::new();
            sql.push("SELECT 1 FROM ")
                .push_ident(M::TABLE)
                .push(" WHERE ");
            if M::DETERMINISTIC.contains(&column) {
                // As it's stored, by any key: `unique` on an encrypted email.
                sql.push_ident(column).push(" IN (");
                let variants = crate::encryption::deterministic_variants(&value.to_text())?;
                for (i, text) in variants.into_iter().enumerate() {
                    if i > 0 {
                        sql.push(", ");
                    }
                    sql.push_value(Value::Text(text));
                }
                sql.push(")");
            } else {
                sql.push_ident(column).push(" = ").push_value(value);
            }
            for scoped in &scope {
                sql.push(" AND ").push_ident(scoped);
                match self.value_of(scoped) {
                    Value::Null => sql.push(" IS NULL"),
                    value => sql.push(" = ").push_value(value),
                };
            }
            if let Some(data) = &self.data {
                sql.push(" AND ").push_ident(M::PRIMARY_KEY).push(" <> ");
                sql.push_value(data.id_value());
            }
            sql.push(" LIMIT 1");
            if !conn.fetch_all(&sql).await?.is_empty() {
                // Where Rails lists it, in the order the fields' checks are
                // declared: before the first error of a later field.
                let place = |c: &str| M::ATTRIBUTES.iter().position(|a| *a == c);
                let at = self
                    .errors
                    .iter()
                    .position(|(c, _)| match (place(c), place(column)) {
                        (Some(theirs), Some(ours)) => theirs > ours,
                        (None, _) => true,
                        _ => false,
                    })
                    .unwrap_or(self.errors.len());
                self.errors
                    .insert(at, (column, "has already been taken".to_owned()));
            }
        }
        Ok(())
    }

    /// Runs on `conn` instead of the ambient connection.
    pub fn on(mut self, conn: impl Into<Connection>) -> Self {
        self.conn = Some(conn.into());
        self
    }

    pub(crate) fn connection(&self) -> Result<Connection> {
        match &self.conn {
            Some(conn) => Ok(conn.clone()),
            None => current_in(M::DATABASE),
        }
    }

    fn touch(&mut self, column: &'static str, now: Timestamp) {
        if !self.changes.iter().any(|(n, _)| *n == column) {
            self.changes.push((column, Value::Timestamp(now)));
        }
    }

    /// Inserts a new record after running the model's validations.
    pub async fn insert(self) -> Result<Save<M>> {
        let mut changeset = M::validate(self);
        if !changeset.is_valid() {
            // As Rails, every error at once: "has already been taken" too.
            let conn = changeset.connection()?;
            changeset.check_unique(&conn).await?;
            return Ok(Save::Invalid(changeset));
        }
        changeset.insert_valid().await
    }

    pub(crate) async fn insert_valid(mut self) -> Result<Save<M>> {
        let conn = self.connection()?;
        self.check_unique(&conn).await?;
        if !self.is_valid() {
            return Ok(Save::Invalid(self));
        }
        let now = crate::time::now();
        if let Some(column) = M::CREATED_AT {
            self.touch(column, now);
        }
        if let Some(column) = M::UPDATED_AT {
            self.touch(column, now);
        }

        let mut sql = Sql::new();
        sql.push("INSERT INTO ").push_ident(M::TABLE);
        if self.changes.is_empty() {
            sql.push(" DEFAULT VALUES");
        } else {
            sql.push(" (");
            for (i, (column, _)) in self.changes.iter().enumerate() {
                if i > 0 {
                    sql.push(", ");
                }
                sql.push_ident(column);
            }
            sql.push(") VALUES (");
            for (i, (column, value)) in self.changes.iter().enumerate() {
                if i > 0 {
                    sql.push(", ");
                }
                sql.push_value(crate::encryption::stored::<M>(column, value.clone())?);
            }
            sql.push(")");
        }
        sql.push(" RETURNING *");
        self.save(&conn, &sql).await
    }

    /// Updates the attached record with the changes, after running the
    /// model's validations. With no changes, the record is returned
    /// untouched without querying.
    pub async fn update(self) -> Result<Save<M>> {
        let mut changeset = M::validate(self);
        if !changeset.is_valid() {
            let conn = changeset.connection()?;
            changeset.check_unique(&conn).await?;
            return Ok(Save::Invalid(changeset));
        }
        changeset.update_valid().await
    }

    pub(crate) async fn update_valid(mut self) -> Result<Save<M>> {
        let Some(data) = &self.data else {
            return Err(Error::internal(
                "update needs a record; use record.change()",
            ));
        };
        if self.changes.is_empty() {
            return Ok(Save::Saved(self.data.take().expect("checked above")));
        }
        data.check_not_shared()?;
        let id = data.id_value();
        let conn = self.connection()?;
        self.check_unique(&conn).await?;
        if !self.is_valid() {
            return Ok(Save::Invalid(self));
        }
        if let Some(column) = M::UPDATED_AT {
            self.touch(column, crate::time::now());
        }

        let mut sql = Sql::new();
        sql.push("UPDATE ").push_ident(M::TABLE).push(" SET ");
        for (i, (column, value)) in self.changes.iter().enumerate() {
            if i > 0 {
                sql.push(", ");
            }
            sql.push_ident(column).push(" = ");
            sql.push_value(crate::encryption::stored::<M>(column, value.clone())?);
        }
        sql.push(" WHERE ").push_ident(M::PRIMARY_KEY).push(" = ");
        sql.push_value(id);
        sql.push(" RETURNING *");
        self.save(&conn, &sql).await
    }

    async fn save(self, conn: &Connection, sql: &Sql) -> Result<Save<M>> {
        // On Postgres a failed statement aborts the whole transaction. When a
        // unique violation is expected to come back as a changeset error,
        // isolate the write in a savepoint so the transaction stays usable.
        let savepoint = (conn.in_transaction()
            && conn.dialect() == Dialect::Postgres
            && !self.unique.is_empty())
        .then(|| format!("glacier_{}", SAVEPOINTS.fetch_add(1, Ordering::Relaxed)));
        if let Some(name) = &savepoint {
            conn.execute(Sql::new().push(&format!("SAVEPOINT {name}")))
                .await?;
        }
        let result = conn.fetch_all(sql).await;
        if let Some(name) = &savepoint {
            let finish = if result.is_ok() {
                format!("RELEASE SAVEPOINT {name}")
            } else {
                format!("ROLLBACK TO SAVEPOINT {name}")
            };
            conn.execute(Sql::new().push(&finish)).await?;
        }
        match result {
            Ok(rows) => match rows.first() {
                Some(row) => {
                    let saved = M::from_row(row)?;
                    // `belongs_to … touch`: the parents' `updated_at` too.
                    saved.touch_parents().await?;
                    Ok(Save::Saved(saved))
                }
                None => Err(Error::not_found()),
            },
            Err(sqlx::Error::Database(err)) if err.is_unique_violation() => {
                match self.unique_column(err.message(), err.constraint()) {
                    Some(column) => {
                        let mut changeset = self;
                        changeset
                            .errors
                            .push((column, "has already been taken".to_owned()));
                        Ok(Save::Invalid(changeset))
                    }
                    None => Err(sqlx::Error::Database(err).into()),
                }
            }
            Err(err) => Err(err.into()),
        }
    }

    /// Which declared-unique column a violation is about, judging by the
    /// error text (constraint names and messages mention the column).
    fn unique_column(&self, message: &str, constraint: Option<&str>) -> Option<&'static str> {
        let haystack = format!("{message} {}", constraint.unwrap_or_default());
        self.unique
            .iter()
            .copied()
            .find(|column| haystack.contains(column))
            .or_else(|| (self.unique.len() == 1).then(|| self.unique[0]))
    }
}

/// Rules for [`Changeset::validate_numericality`], as Rails'
/// `numericality` options; unset rules don't apply.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Numericality {
    pub only_integer: bool,
    pub greater_than: Option<f64>,
    pub greater_than_or_equal_to: Option<f64>,
    pub less_than: Option<f64>,
    pub less_than_or_equal_to: Option<f64>,
}

impl Numericality {
    fn check(&self, n: f64) -> Option<String> {
        // As Rails writes the bound: `0`, not `0.0`.
        let shown = |bound: f64| {
            if bound.fract() == 0.0 && bound.abs() < 1e15 {
                format!("{}", bound as i64)
            } else {
                bound.to_string()
            }
        };
        if self.only_integer && n.fract() != 0.0 {
            return Some("must be an integer".to_owned());
        }
        if let Some(b) = self.greater_than.filter(|b| n <= *b) {
            return Some(format!("must be greater than {}", shown(b)));
        }
        if let Some(b) = self.greater_than_or_equal_to.filter(|b| n < *b) {
            return Some(format!("must be greater than or equal to {}", shown(b)));
        }
        if let Some(b) = self.less_than.filter(|b| n >= *b) {
            return Some(format!("must be less than {}", shown(b)));
        }
        if let Some(b) = self.less_than_or_equal_to.filter(|b| n > *b) {
            return Some(format!("must be less than or equal to {}", shown(b)));
        }
        None
    }
}

/// A compiled regex, kept for the next validation with the same pattern.
fn cached_regex(pattern: &str) -> regex::Regex {
    use std::collections::HashMap;
    use std::sync::{Mutex, OnceLock};
    static CACHE: OnceLock<Mutex<HashMap<String, regex::Regex>>> = OnceLock::new();
    let mut cache = CACHE
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    cache
        .entry(pattern.to_owned())
        .or_insert_with(|| {
            regex::Regex::new(pattern)
                .unwrap_or_else(|e| panic!("invalid format pattern {pattern:?}: {e}"))
        })
        .clone()
}

/// A column as Rails' `humanize` shows it: `password_confirmation` is
/// `Password confirmation`, `author_id` is `Author`.
pub(crate) fn humanize(column: &str) -> String {
    let words = column
        .strip_suffix("_id")
        .unwrap_or(column)
        .replace('_', " ");
    let mut chars = words.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().chain(chars).collect(),
        None => String::new(),
    }
}