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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//! Database models.
//!
//! `#[derive(Model)]` maps a struct to a table and gives it Rails-style
//! class methods. They run on the ambient connection (see `glacier::db`):
//!
//! ```no_run
//! use glacier::prelude::*;
//!
//! #[derive(Model)]
//! struct Post {
//!     id: i64,
//!     title: String,
//!     views: i64,
//! }
//!
//! # async fn demo() -> glacier::Result<()> {
//! let post = Post::find(1).await?;                        // 404 if missing
//! let recent = Post::all().order(|p| p.id.desc()).limit(5).await?;
//! let popular = Post::filter(|p| p.views.gt(100)).count().await?;
//! # Ok(()) }
//! ```
//!
//! The derive also generates a `PostColumns` struct with one typed column
//! per field; queries receive it in their closures (`|p| p.views.gt(100)`).
//!
//! Field attributes: `#[glacier(skip)]` (not a column; filled with
//! `Default::default()` when loading) and `#[glacier(primary_key)]` (when
//! the key isn't `id`). Struct attribute: `#[glacier(table = "…")]`. A
//! field named `inserted_at` or `updated_at` of type `Timestamp` is filled
//! in automatically on insert and update.

use std::future::Future;

use crate::context::Params;
use crate::db::{Changeset, Expr, Order, Preload, Query, Record, Row, Save, ToValue, Value};
use crate::error::Result;

/// Implemented via `#[derive(Model)]`.
///
/// ```
/// use glacier::Model;
///
/// #[derive(Model)]
/// struct BlogPost {
///     id: i64,
///     title: String,
///     #[glacier(skip)]
///     cached_html: Option<String>,
/// }
///
/// assert_eq!(BlogPost::TABLE, "blog_posts");
/// assert_eq!(BlogPost::COLUMNS, &["id", "title"]);
/// ```
/// Hooks around saving and destroying a record, run by
/// [`Model::save`]/[`Model::update`] (in Rails' order: `before_validation`,
/// validations, `before_save`, `before_create` or `before_update`, the
/// write, `after_create` or `after_update`, `after_save`) and
/// [`Model::destroy`]. Each does nothing unless implemented; an error stops
/// the save and is returned.
///
/// ```ignore
/// #[glacier::model(callbacks)]
/// pub struct Post { title: String, slug: String }
///
/// impl Callbacks for Post {
///     async fn before_save(&mut self) -> glacier::Result<()> {
///         self.slug = slugify(&self.title);
///         Ok(())
///     }
/// }
/// ```
///
/// The changeset path (`Post::create`, `update_changeset`) has no
/// callbacks, like Ecto.
pub trait Callbacks: Send {
    /// The model's own checks, beyond its fields' validations, as Rails'
    /// `validate do … end`: add to `errors` and the save fails with them.
    /// Runs on every record save, after `before_validation`.
    fn validate_record(&self, errors: &mut crate::db::Errors) {
        let _ = errors;
    }

    fn before_validation(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
    fn before_save(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
    fn before_create(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
    fn before_update(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
    fn after_create(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
    fn after_update(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
    fn after_save(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
    fn before_destroy(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
    fn after_destroy(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
}

pub trait Model: Callbacks + Sized + Send + Sync + 'static {
    /// Defaults to the snake_case, pluralized struct name.
    const TABLE: &'static str;
    const COLUMNS: &'static [&'static str];
    /// What a bare JSON body may set, which a controller's params wrap as
    /// Rails' `wrap_parameters` does: the columns, and the derive adds
    /// attributes that aren't stored and nested `<name>_attributes`.
    const ATTRIBUTES: &'static [&'static str] = Self::COLUMNS;
    /// The columns an [`Access`](crate::access::Access) owns rows by, each
    /// with the access's key it holds: `("org_id", "org_id")` for `owned_by
    /// :org` in `.glacier`, `("account_id", "org_id")` for `owned_by :org,
    /// foreign_key: :account_id`. Empty for a model that isn't scoped.
    const OWNER: &'static [(&'static str, &'static str)] = &[];
    /// The model's `belongs_to` parents, so saving checks that an owned
    /// parent is the same tenant's (a project of this note's org).
    const PARENTS: &'static [Parent] = &[];
    /// The columns stored encrypted (`field secret: String, encrypted`):
    /// written through [`crate::encryption`] and read back as plain text.
    const ENCRYPTED: &'static [&'static str] = &[];
    /// Rows with no owner (`org_id` NULL) that every tenant reads, as
    /// `owned_by :org, global: true` declares: shared templates, defaults.
    /// They change only `unscoped`.
    const GLOBAL_ROWS: bool = false;
    /// `soft_deletes`: the column (`deleted_at`) a deleted record's time
    /// goes in, rather than the row going. Queries leave such records out
    /// unless `with_trashed()`; `restore()` brings one back and
    /// `force_delete()` deletes it.
    const SOFT_DELETE: Option<&'static str> = None;
    /// The encrypted columns encrypted the same way every time
    /// (`encrypted(deterministic)`), so queries can find their values.
    const DETERMINISTIC: &'static [&'static str] = &[];
    /// The columns never written to JSON (`serialize::attributes`, the
    /// model's `Serialize` and its schema): `hidden` fields, `encrypted`
    /// ones and `*_digest` columns such as `password_digest`.
    const HIDDEN: &'static [&'static str] = &[];
    const PRIMARY_KEY: &'static str = "id";
    /// Whether the primary key is a number, so `find("12")` (a param, as
    /// text) parses it, and text that isn't a number finds nothing.
    const INTEGER_KEY: bool = true;
    /// The named database the model lives in (`database = "analytics"`),
    /// registered with `App::named_database`; `None` for the app's own.
    const DATABASE: Option<&'static str> = None;
    /// Whether the model has `has_attached` attachments. Generated by
    /// `#[glacier::model(attachments)]`.
    #[doc(hidden)]
    const ATTACHMENTS: bool = false;
    /// The column set when a record is inserted (`inserted_at`, or Rails'
    /// `created_at`), if the model has one.
    const CREATED_AT: Option<&'static str> = None;
    /// The column set on every write, if the model has one.
    const UPDATED_AT: Option<&'static str> = None;

    /// The generated struct of typed columns (`PostColumns`).
    type Columns;

    fn columns() -> Self::Columns;
    fn from_row(row: &Row) -> Result<Self>;
    /// Every column with its current value.
    fn values(&self) -> Vec<(&'static str, Value)>;
    /// Sets a column or virtual field from a `Value`, the reverse of
    /// [`values`](Self::values): `false` when there's no such field or the
    /// value doesn't fit it. Generated by the derive; how a record is made
    /// from a changeset, for its callbacks.
    /// `normalize:` fields, set to their normal form before validation:
    /// `field email: String, normalize: fn e -> e.trim().to_lowercase()
    /// end`. Generated by the derive.
    #[doc(hidden)]
    fn normalize_fields(&mut self) {}
    /// `belongs_to :account, default: …`: a new record's unset parent
    /// keys, filled before `before_validation`. Generated.
    #[doc(hidden)]
    fn belongs_to_defaults(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }
    /// `confirmation` and `acceptance` checks, on the record itself (they
    /// read virtual fields). Generated by the derive.
    #[doc(hidden)]
    fn validate_attributes(&self, errors: &mut crate::db::Errors) {
        let _ = errors;
    }
    #[doc(hidden)]
    fn set_value(&mut self, column: &str, value: Value) -> bool {
        let _ = (column, value);
        false
    }
    /// A new, empty record (`Default::default()`), or `None` for a model
    /// without one. Generated by the derive.
    #[doc(hidden)]
    fn blank() -> Option<Self> {
        None
    }
    /// The virtual fields (`#[glacier(attribute)]`) with their values.
    fn attribute_values(&self) -> Vec<(&'static str, Value)> {
        Vec::new()
    }
    fn id_value(&self) -> Value;

    /// The model's own validations, run on every insert and update.
    /// `#[validate(…)]` field attributes generate this.
    fn validate(changeset: Changeset<Self>) -> Changeset<Self> {
        changeset
    }

    /// A changeset casting the permitted fields from request params: every
    /// column except the primary key, timestamps and fields marked
    /// `#[glacier(protected)]`. Generated by the derive.
    fn from_params(params: &Params) -> Changeset<Self> {
        let _ = params;
        Changeset::new()
    }

    /// The JSON Schema of the params `from_params` takes, for OpenAPI's
    /// request bodies. Generated by the derive.
    fn params_schema() -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    /// This record's URL: `/posts/7` by default (the table name and the
    /// primary key). Override it when the routes differ.
    fn path(&self) -> String {
        let id = self.id_value().to_text();
        // A nested resource's params from the record's own columns
        // (`org_id`), else the request's.
        let values = self.values();
        let collection = crate::router::collection_path_of(Self::TABLE, |param| {
            values
                .iter()
                .find(|(column, _)| *column == param)
                .map(|(_, value)| value.to_text())
        });
        format!("{collection}/{}", crate::router::encode_segment(&id))
    }

    /// The URL of the collection, `/posts` by default.
    fn collection_path() -> String {
        crate::router::collection_path_of(Self::TABLE, |_| None)
    }

    /// All records, as a query to refine or `.await`.
    fn all() -> Query<Self> {
        Query::new()
    }

    /// Refines every query of the model, as Rails' `default_scope`:
    /// `default_scope order(:position)` in a `.glacier` model.
    fn default_scope(query: Query<Self>) -> Query<Self> {
        query
    }

    /// The records `access` may see, `Post.for(access)` in `.glacier`:
    /// those whose owner columns hold its values (the org's id). An
    /// access that owns none of them sees nothing. Records built from the
    /// query (`.build(params)`) get those values too.
    fn r#for(access: &dyn crate::access::Access) -> Query<Self> {
        Query::new().owned_by(access)
    }

    /// Sets an owner column (`org_id`) from its value as text. Generated
    /// by the derive for `OWNER`'s columns, which params never set.
    fn set_owner(&mut self, column: &str, value: &str) {
        let _ = (column, value);
    }

    /// All records, without the default scope.
    fn unscoped() -> Query<Self> {
        Query::unscoped()
    }

    fn filter(condition: impl FnOnce(&Self::Columns) -> Expr) -> Query<Self> {
        Query::new().filter(condition)
    }

    /// The records matching a condition in SQL, `?` for each of `values`,
    /// as Rails' `where("…", …)`: see [`Query::where_sql`].
    fn where_sql(sql: &str, values: impl IntoIterator<Item = crate::db::Value>) -> Query<Self> {
        Self::all().where_sql(sql, values)
    }

    fn order(order: impl FnOnce(&Self::Columns) -> Order) -> Query<Self> {
        Query::new().order(order)
    }

    /// All records with an association loaded: `Country::preload(|c|
    /// c.installations)`, `Country.preload(:installations)` in `.glacier`.
    fn preload<P: Into<Preload<Self>>>(
        association: impl FnOnce(&Self::Columns) -> P,
    ) -> Query<Self> {
        Query::new().preload(association)
    }

    /// The record with this primary key, or `404 Not Found`.
    /// The record with this primary key, or a `404 Not Found`. A key given
    /// as text, such as `params[:id]`, is parsed for a numeric key, as
    /// Rails' `find` is: text that isn't a number finds nothing.
    fn find(id: impl ToValue) -> impl Future<Output = Result<Self>> + Send {
        let id = match id.to_value() {
            crate::db::Value::Text(text) if Self::INTEGER_KEY => {
                text.trim().parse::<i64>().map(crate::db::Value::Int).ok()
            }
            value => Some(value),
        };
        let query = id.map(by_id::<Self>);
        async move {
            match query {
                Some(query) => query.one().await,
                None => Err(crate::Error::not_found()),
            }
        }
    }

    /// The first record matching `condition`, if any.
    fn find_by(
        condition: impl FnOnce(&Self::Columns) -> Expr,
    ) -> impl Future<Output = Result<Option<Self>>> + Send {
        let query = Self::filter(condition);
        async move { query.first().await }
    }

    /// The first record matching `condition`, or a new unsaved one set up
    /// by `init`, as Rails' `find_or_initialize_by`:
    /// `Tag.find_or_initialize_by(name: "rust")` in `.glacier`.
    fn find_or_initialize_by(
        condition: impl FnOnce(&Self::Columns) -> Expr,
        init: impl FnOnce(&mut Self) + Send,
    ) -> impl Future<Output = Result<Self>> + Send
    where
        Self: Default,
    {
        let query = Self::filter(condition);
        async move {
            Ok(match query.first().await? {
                Some(found) => found,
                None => Self::default().tap(init),
            })
        }
    }

    /// The first record matching `condition`, or one set up by `init` and
    /// saved, as Rails' `find_or_create_by`. A record that fails validation
    /// comes back unsaved, with its errors.
    fn find_or_create_by(
        condition: impl FnOnce(&Self::Columns) -> Expr,
        init: impl FnOnce(&mut Self) + Send,
    ) -> impl Future<Output = Result<Self>> + Send
    where
        Self: Default + Clone,
    {
        let query = Self::filter(condition);
        async move {
            if let Some(found) = query.first().await? {
                return Ok(found);
            }
            let mut record = Self::default().tap(init);
            record.save().await?;
            Ok(record)
        }
    }

    /// The first record by primary key, if any.
    fn first() -> impl Future<Output = Result<Option<Self>>> + Send {
        Query::<Self>::new().first()
    }

    /// The last record by primary key, if any.
    fn last() -> impl Future<Output = Result<Option<Self>>> + Send {
        Query::<Self>::new().last()
    }

    /// The first `n` records by primary key.
    fn take(n: u64) -> impl Future<Output = Result<Vec<Self>>> + Send {
        Query::<Self>::new()
            .order(|_| Order::by(Self::PRIMARY_KEY, false))
            .take(n)
    }

    fn count() -> impl Future<Output = Result<i64>> + Send {
        Query::<Self>::new().count()
    }

    /// Every record's primary key: `Book.ids()!`, as Rails' `Book.ids`.
    fn ids() -> impl Future<Output = Result<Vec<i64>>> + Send {
        Query::<Self>::new().ids()
    }

    /// Whether there are any records at all: `User.exists()!`, as
    /// Rails' `User.exists?` (`User.exists(email: e)!` for some).
    fn exists() -> impl Future<Output = Result<bool>> + Send {
        Query::<Self>::new().exists()
    }

    /// Records with a related record meeting a condition:
    /// `Post::join(|p| p.author, |a| a.name.eq("Ada"))`.
    fn join<C: Model>(
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
        condition: impl FnOnce(&C::Columns) -> Expr,
    ) -> Query<Self> {
        Query::new().join(association, condition)
    }

    /// Records with at least one related record: `Post::joins(|p| p.comments)`.
    fn joins<C: Model>(
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
    ) -> Query<Self> {
        Query::new().joins(association)
    }

    /// Every record grouped by a column, to count or total each group:
    /// `Post::group(|p| p.status).count()`, `Post.group(:status).count()`.
    fn group<K: crate::db::FromColumn>(
        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, K>,
    ) -> crate::db::Grouped<Self, K> {
        Query::new().group(column)
    }

    /// The sum of a numeric column over every record: `Post.sum(:views)`.
    fn sum<T: crate::db::Summable>(
        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
    ) -> impl Future<Output = Result<T::Sum>> + Send {
        Query::<Self>::new().sum(column)
    }

    /// The mean of a numeric column over every record.
    fn average<T: crate::db::Summable>(
        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
    ) -> impl Future<Output = Result<Option<f64>>> + Send {
        Query::<Self>::new().average(column)
    }

    /// The smallest value of a column.
    fn minimum<T: crate::db::Aggregable>(
        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
    ) -> impl Future<Output = Result<Option<T::Value>>> + Send {
        Query::<Self>::new().minimum(column)
    }

    /// The largest value of a column.
    fn maximum<T: crate::db::Aggregable>(
        column: impl FnOnce(&Self::Columns) -> crate::db::Col<Self, T>,
    ) -> impl Future<Output = Result<Option<T::Value>>> + Send {
        Query::<Self>::new().maximum(column)
    }

    /// Inserts a record from params, a changeset, or anything convertible
    /// into one:
    ///
    /// ```ignore
    /// match Post::create(ctx.params()).await? {
    ///     Saved(post) => redirect!(post, notice: "Post created."),
    ///     Invalid(changeset) => render!(changeset; template = new, status = 422),
    /// }
    /// ```
    ///
    /// The model's callbacks run, as Rails' `create` runs them;
    /// `changeset.insert()` is the write without them.
    fn create(
        changes: impl Into<Changeset<Self>>,
    ) -> impl Future<Output = Result<Save<Self>>> + Send {
        let changeset = changes.into();
        async move { crate::db::record::write_changeset(changeset, true).await }
    }

    /// Inserts a new record its fields set by `change`, running the
    /// callbacks and validations as [`save`](Self::save) does:
    /// `.glacier`'s `Post.create(title: "Hi")!`. Returns `Saved(post)` or
    /// `Invalid` with its errors.
    fn create_with(
        change: impl FnOnce(&mut Self),
    ) -> impl Future<Output = Result<Save<Self>>> + Send
    where
        Self: Default + Clone,
    {
        let mut record = Self::build_with(change);
        async move {
            if record.save().await? {
                return Ok(Save::Saved(record));
            }
            let mut changeset = Changeset::<Self>::new();
            for (column, message) in record.errors() {
                changeset = changeset.push_error(column, message.clone());
            }
            Ok(Save::Invalid(changeset))
        }
    }

    /// A changeset for a new record: `Post::changeset().set(|p| p.title, t)`.
    fn changeset() -> Changeset<Self> {
        Changeset::new()
    }

    /// An empty changeset for this record, to build an update by hand.
    fn change(self) -> Changeset<Self> {
        Changeset::for_record(self)
    }

    /// Applies params, a changeset or anything convertible into one to this
    /// record, Ecto-style, returning `Saved(record)` or `Invalid(changeset)`.
    /// [`update`](Self::update) is the Active Record-style version.
    ///
    /// The model's callbacks run, as `update` runs them;
    /// `changeset.update()` is the write without them.
    fn update_changeset(
        self,
        changes: impl Into<Changeset<Self>>,
    ) -> impl Future<Output = Result<Save<Self>>> + Send {
        let changeset = changes.into().attach(self);
        async move { crate::db::record::write_changeset(changeset, false).await }
    }

    /// Deletes the record, running `before_destroy`, then removing its
    /// `dependent` children, then `after_destroy`.
    fn destroy(mut self) -> impl Future<Output = Result<()>> + Send {
        async move {
            self.check_not_shared()?;
            self.before_destroy().await?;
            // A soft delete keeps its children, to come back with it.
            if Self::SOFT_DELETE.is_none() {
                self.destroy_dependents().await?;
            }
            by_id::<Self>(self.id_value())
                .of_record()
                .delete_all()
                .await?;
            for file in self.attached_files() {
                file.remove().await?;
            }
            self.touch_parents().await?;
            self.after_destroy().await
        }
    }

    /// The uploads waiting to be kept by `has_attached`, taken from the
    /// record (its columns set from them) as it saves. Generated by
    /// `#[glacier::model(attachments)]`.
    #[doc(hidden)]
    fn take_attachments(&mut self) -> Vec<crate::attachment::Pending> {
        Vec::new()
    }

    /// The files the record keeps through `has_attached`, removed with it.
    #[doc(hidden)]
    fn attached_files(&self) -> Vec<crate::attachment::Attached> {
        Vec::new()
    }

    /// Sets `updated_at` on the parents of `belongs_to … touch`
    /// associations, after a write. Generated by `#[glacier::model]`.
    #[doc(hidden)]
    fn touch_parents(&self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }

    /// Removes the children of `has_many … dependent` associations.
    /// Generated by `#[glacier::model]`.
    #[doc(hidden)]
    fn destroy_dependents(&self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }

    /// Deletes the record without callbacks.
    fn delete(self) -> impl Future<Output = Result<()>> + Send {
        let query = by_id::<Self>(self.id_value()).of_record();
        let shared = self.check_not_shared();
        async move {
            shared?;
            query.delete_all().await?;
            Ok(())
        }
    }

    /// Whether it's been soft-deleted (`soft_deletes`): `deleted_at` set.
    fn is_trashed(&self) -> bool {
        Self::SOFT_DELETE.is_some_and(|column| {
            self.values()
                .into_iter()
                .any(|(c, value)| c == column && !value.is_null())
        })
    }

    /// Brings a soft-deleted record back: `deleted_at` cleared, in the
    /// database and on the record.
    fn restore(&mut self) -> impl Future<Output = Result<()>> + Send {
        let column = Self::SOFT_DELETE;
        let query = by_id::<Self>(self.id_value()).of_record().with_trashed();
        if let Some(column) = column {
            self.set_value(column, Value::Null);
        }
        async move {
            let Some(column) = column else {
                return Err(crate::Error::internal(
                    "restore is for a model with `soft_deletes`",
                ));
            };
            query
                .update_all(|_| [crate::db::Assign::new(column, Value::Null)])
                .await?;
            Ok(())
        }
    }

    /// Deletes the row for good, even with `soft_deletes`; no callbacks.
    fn force_delete(self) -> impl Future<Output = Result<()>> + Send {
        let query = by_id::<Self>(self.id_value()).of_record().with_trashed();
        let shared = self.check_not_shared();
        async move {
            shared?;
            query.force_delete_all().await?;
            Ok(())
        }
    }

    /// The records with an associated record matching `inner`:
    /// `Author.where_has(:books, published: true)`.
    fn where_has<C: Model>(
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
        inner: impl FnOnce(Query<C>) -> Query<C>,
    ) -> Query<Self> {
        Query::new().where_has(association, inner)
    }

    /// The records with no associated record: `Author.without(:books)`.
    fn without<C: Model>(
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
    ) -> Query<Self> {
        Query::new().without(association)
    }

    /// Every record, soft-deleted ones too.
    fn with_trashed() -> Query<Self> {
        Query::new().with_trashed()
    }

    /// Only the soft-deleted records.
    fn only_trashed() -> Query<Self> {
        Query::new().only_trashed()
    }

    /// `Err(403)` for a shared row (no owner, in a `global` model) changed
    /// under a tenant's access: those change only `unscoped`.
    #[doc(hidden)]
    fn check_not_shared(&self) -> Result<()> {
        if !Self::GLOBAL_ROWS || crate::access::may_change_shared() {
            return Ok(());
        }
        let values = self.values();
        let shared = Self::OWNER.iter().all(|(column, _)| {
            values
                .iter()
                .find(|(c, _)| c == column)
                .is_none_or(|(_, value)| value.is_null())
        });
        if shared {
            Err(crate::Error::new(
                http::StatusCode::FORBIDDEN,
                "a shared row changes only `unscoped`",
            ))
        } else {
            Ok(())
        }
    }

    /// Sets the record's `updated_at` to now in the database, without
    /// callbacks or validation, as Rails' `touch`. The record in hand keeps
    /// its old `updated_at`. Nothing happens without that column.
    fn touch(&self) -> impl Future<Output = Result<()>> + Send {
        crate::db::assoc::touch_parent::<Self>(self.id_value())
    }

    // Active Record style: the record carries its state (see
    // `glacier::db::Record`, which `#[glacier::model]` adds).

    /// The record's state, when the model has one (`#[glacier::model]`).
    fn record(&self) -> Option<&Record> {
        None
    }

    fn record_mut(&mut self) -> Option<&mut Record> {
        None
    }

    /// A new, unsaved record with default values: `Post::new()`.
    fn new() -> Self
    where
        Self: Default,
    {
        Self::default()
    }

    /// Changes fields in a closure and returns the record:
    /// `Post::new().tap(|p| p.title = "Hi".into())`.
    fn tap(mut self, change: impl FnOnce(&mut Self)) -> Self {
        change(&mut self);
        self
    }

    /// A new record from form params: `Post::build(ctx.params())`.
    fn build(params: impl Into<Params>) -> Self
    where
        Self: Default,
    {
        let mut record = Self::default();
        record.assign(&params.into());
        record
    }

    /// A new record, with `change` setting its fields: `Note.build(title:
    /// "…")` in `.glacier`.
    fn build_with(change: impl FnOnce(&mut Self)) -> Self
    where
        Self: Default,
    {
        let mut record = Self::default();
        change(&mut record);
        record
    }

    /// Loads an association of this record now, as `preload` does for a
    /// query's: `post.load(:comments)!`, then `post.comments`.
    fn load<P: Into<crate::db::Preload<Self>>>(
        &mut self,
        association: impl FnOnce(&Self::Columns) -> P,
    ) -> impl Future<Output = Result<()>> + Send {
        let preload = association(&Self::columns()).into();
        async move {
            let conn = crate::db::current_in(Self::DATABASE)?;
            preload.run(std::slice::from_mut(self), conn).await
        }
    }

    /// A new record of a `has_many` association, its foreign key this
    /// record's, `change` setting its fields: `post.build(:comments, body:
    /// "…")` in `.glacier`, as Rails' `post.comments.build`.
    fn build_in<C: Model + Default>(
        &self,
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
        change: impl FnOnce(&mut C),
    ) -> C {
        let association = association(&Self::columns());
        let (own, other) = association
            .join
            .expect("build_in is for a `has_many` (not `through` a join table)");
        let key = self
            .values()
            .into_iter()
            .find(|(column, _)| *column == own)
            .map_or(Value::Null, |(_, value)| value);
        let mut child = C::default();
        change(&mut child);
        child.set_value(other, key);
        // A polymorphic child names this model too.
        if let Some((column, name)) = association.kind {
            child.set_value(column, Value::Text(name.to_owned()));
        }
        child
    }

    /// Links this record to more records of a `has_many … through:` (by
    /// id), as Laravel's `attach`: `book.attach(:tags, [tag.id])!`.
    /// Links that exist already are left alone.
    fn attach<C: Model>(
        &self,
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
        ids: impl IntoIterator<Item = i64>,
    ) -> impl Future<Output = Result<()>> + Send {
        self.write_links(association, ids, crate::db::assoc::Links::Add)
    }

    /// Unlinks records of a `has_many … through:` (by id): `detach`.
    fn detach<C: Model>(
        &self,
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
        ids: impl IntoIterator<Item = i64>,
    ) -> impl Future<Output = Result<()>> + Send {
        self.write_links(association, ids, crate::db::assoc::Links::Remove)
    }

    /// Links this record to exactly these records of a `has_many …
    /// through:` (by id), as Laravel's `sync`.
    fn sync<C: Model>(
        &self,
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
        ids: impl IntoIterator<Item = i64>,
    ) -> impl Future<Output = Result<()>> + Send {
        self.write_links(association, ids, crate::db::assoc::Links::Exactly)
    }

    #[doc(hidden)]
    fn write_links<C: Model>(
        &self,
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
        ids: impl IntoIterator<Item = i64>,
        links: crate::db::assoc::Links,
    ) -> impl Future<Output = Result<()>> + Send {
        let through = association(&Self::columns()).through;
        let owner = self.id_value();
        let ids: Vec<i64> = ids.into_iter().collect();
        async move {
            let (table, owner_key, target_key) = through.ok_or_else(|| {
                crate::Error::internal("attach, detach and sync are for a `has_many … through:`")
            })?;
            crate::db::assoc::write_through_ids(owner, table, owner_key, target_key, ids, links)
                .await
        }
    }

    /// `build_in`, then saved: `post.create(:comments, body: "…")!`.
    fn create_in<C: Model + Default + Clone>(
        &self,
        association: impl FnOnce(&Self::Columns) -> crate::db::Association<Self, C>,
        change: impl FnOnce(&mut C),
    ) -> impl Future<Output = Result<crate::db::Save<C>>> + Send {
        let mut child = self.build_in(association, change);
        async move {
            if child.save().await? {
                return Ok(crate::db::Save::Saved(child));
            }
            let mut changeset = crate::db::Changeset::<C>::new();
            for (column, message) in child.errors() {
                changeset = changeset.push_error(column, message.clone());
            }
            Ok(crate::db::Save::Invalid(changeset))
        }
    }

    /// Sets the permitted fields from params, keeping input that doesn't
    /// cast (and why) for the form. Generated by the derive.
    fn assign(&mut self, params: &Params) {
        let _ = params;
    }

    /// Sets the protected fields too, which params never set: for trusted
    /// code only, as a test's factory is. Generated by the derive.
    #[doc(hidden)]
    fn assign_protected(&mut self, params: &Params) {
        let _ = params;
    }

    /// Whether the record hasn't been saved yet.
    fn is_new(&self) -> bool {
        match self.record() {
            Some(state) => !state.is_persisted(),
            None => matches!(self.id_value(), Value::Null | Value::Int(0)),
        }
    }

    fn is_persisted(&self) -> bool {
        !self.is_new()
    }

    /// The columns that differ from what was loaded (every column for a new
    /// record), as `save` would write them.
    fn changes(&self) -> Vec<(&'static str, Value)> {
        crate::db::record::changes(self)
    }

    fn is_changed(&self) -> bool {
        !self.changes().is_empty()
    }

    /// Whether `column` differs from what was loaded.
    fn changed(&self, column: &str) -> bool {
        self.changes().iter().any(|(c, _)| *c == column)
    }

    /// The column's value as loaded, before any change.
    fn was(&self, column: &str) -> Option<Value> {
        self.record()?.original(column).cloned()
    }

    /// Validates and saves the record (insert or update), in place: `true`
    /// when saved; `false` with [`errors`](Self::errors) when invalid.
    fn save(&mut self) -> impl Future<Output = Result<bool>> + Send
    where
        Self: Clone,
    {
        crate::db::record::save(self)
    }

    /// Sets fields from params and saves, in place: `true` when saved,
    /// `false` with [`errors`](Self::errors) when invalid.
    ///
    /// ```ignore
    /// if post.update(ctx.params()).await? { … } else { … }
    /// ```
    fn update(&mut self, params: impl Into<Params>) -> impl Future<Output = Result<bool>> + Send
    where
        Self: Clone,
    {
        let params = params.into();
        self.assign(&params);
        async move {
            if !Self::HAS_NESTED {
                return crate::db::record::save(self).await;
            }
            // With nested attributes, the record and its children are saved
            // together or not at all.
            let state = self.record().cloned();
            let kept: Vec<(&'static str, Value)> = self
                .values()
                .into_iter()
                .filter(|(column, _)| {
                    *column == Self::PRIMARY_KEY
                        || Some(*column) == Self::CREATED_AT
                        || Some(*column) == Self::UPDATED_AT
                })
                .collect();
            let saved = crate::db::savepoint_in(Self::DATABASE, async {
                if !crate::db::record::save(&mut *self).await? || !self.save_nested(&params).await?
                {
                    return Err(crate::db::assoc::nested_invalid());
                }
                Ok(())
            })
            .await;
            if saved.is_err() {
                // Rolled back, so the record is as it was before the
                // save, as Rails restores it: new if it was (its id gone),
                // its changes still to write, the errors kept.
                for (column, value) in kept {
                    self.set_value(column, value);
                }
                if let (Some(state), Some(now)) = (state, self.record_mut()) {
                    let errors = now.errors().to_vec();
                    *now = state;
                    now.set_errors(errors);
                }
            }
            match saved {
                Ok(()) => Ok(true),
                Err(err) if crate::db::assoc::is_nested_invalid(&err) => Ok(false),
                Err(err) => Err(err),
            }
        }
    }

    /// Whether the model takes nested attributes (`has_many … nested`).
    #[doc(hidden)]
    const HAS_NESTED: bool = false;

    /// Applies `<association>_attributes` from `params` to the children,
    /// adding their errors to this record's; `false` if any is invalid.
    /// Generated by `#[glacier::model]`.
    #[doc(hidden)]
    fn save_nested<'a>(
        &'a mut self,
        params: &'a Params,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>> {
        let _ = params;
        Box::pin(async { Ok(true) })
    }

    /// Changes fields in a closure, then saves:
    /// `post.update_with(|p| p.title = "New".into()).await?`.
    fn update_with(
        &mut self,
        change: impl FnOnce(&mut Self),
    ) -> impl Future<Output = Result<bool>> + Send
    where
        Self: Clone,
    {
        change(self);
        crate::db::record::save(self)
    }

    /// Loads the record again from the database, dropping unsaved changes.
    fn reload(&mut self) -> impl Future<Output = Result<()>> + Send {
        let query = by_id::<Self>(self.id_value()).of_record();
        async move {
            *self = query.one().await?;
            Ok(())
        }
    }

    /// The errors from the last `save`: `(column, message)`.
    fn errors(&self) -> &[(&'static str, String)] {
        self.record().map_or(&[], Record::errors)
    }

    /// Error messages for one column, to show next to its form field.
    fn errors_on(&self, column: &str) -> Vec<&str> {
        self.errors()
            .iter()
            .filter(|(c, _)| *c == column)
            .map(|(_, m)| m.as_str())
            .collect()
    }

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

    /// Messages with their column, lower case: `["title can't be blank"]`,
    /// for matching in tests and building nested records' errors.
    fn messages(&self) -> Vec<String> {
        self.errors()
            .iter()
            .map(|(c, m)| format!("{} {m}", c.replace('_', " ")))
            .collect()
    }

    /// Messages with their column, as Rails shows them:
    /// `["Title can't be blank"]`.
    fn full_messages(&self) -> Vec<String> {
        self.errors()
            .iter()
            .map(|(c, m)| format!("{} {m}", crate::db::humanize(c)))
            .collect()
    }

    /// One field for a form, its value and errors, for the `<.input>`
    /// component: `<.input field={post.field("title")} />`.
    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(),
        )
    }

    /// The column's value as text for a form field, or the input that
    /// couldn't be cast: `value="{{ post.text("price") }}"`.
    fn text(&self, column: &str) -> String {
        if let Some(raw) = self.record().and_then(|r| r.raw(column)) {
            return raw.to_owned();
        }
        self.values()
            .into_iter()
            .chain(self.attribute_values())
            .find(|(c, _)| *c == column)
            .map(|(_, v)| v.to_text())
            .unwrap_or_default()
    }
}

/// A `belongs_to` parent, as [`Model::PARENTS`] lists them.
#[derive(Debug, Clone, Copy)]
pub struct Parent {
    /// The key column on this model: `project_id`.
    pub column: &'static str,
    /// The parent's table and primary key.
    pub table: &'static str,
    pub key: &'static str,
    /// The parent's owner columns and the access keys they hold.
    pub owner: &'static [(&'static str, &'static str)],
}

pub(crate) fn by_id<M: Model>(id: Value) -> Query<M> {
    Query::new().filter(|_| Expr::Compare {
        column: M::PRIMARY_KEY,
        op: "=",
        value: id,
    })
}