glacier-web 0.1.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
//! 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];
    const PRIMARY_KEY: &'static str = "id";
    /// 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)>;
    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()
    }

    /// 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();
        format!(
            "{}/{}",
            Self::collection_path(),
            crate::router::encode_segment(&id)
        )
    }

    /// The URL of the collection, `/posts` by default.
    fn collection_path() -> String {
        format!("/{}", Self::TABLE)
    }

    /// 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
    }

    /// 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)
    }

    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`.
    fn find(id: impl ToValue) -> impl Future<Output = Result<Self>> + Send {
        let query = by_id::<Self>(id.to_value());
        async move { query.one().await }
    }

    /// 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()
    }

    /// 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),
    /// }
    /// ```
    fn create(
        changes: impl Into<Changeset<Self>>,
    ) -> impl Future<Output = Result<Save<Self>>> + Send {
        let changeset = changes.into();
        async move { changeset.insert().await }
    }

    /// 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.
    fn update_changeset(
        self,
        changes: impl Into<Changeset<Self>>,
    ) -> impl Future<Output = Result<Save<Self>>> + Send {
        let changeset = changes.into().attach(self);
        async move { changeset.update().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.before_destroy().await?;
            self.destroy_dependents().await?;
            by_id::<Self>(self.id_value()).delete_all().await?;
            self.touch_parents().await?;
            self.after_destroy().await
        }
    }

    /// 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());
        async move {
            query.delete_all().await?;
            Ok(())
        }
    }

    // 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
    }

    /// 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;
    }

    /// 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 saved = crate::db::savepoint(async {
                if !crate::db::record::save(&mut *self).await? || !self.save_nested(&params).await?
                {
                    return Err(crate::db::assoc::nested_invalid());
                }
                Ok(())
            })
            .await;
            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());
        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: `["title can't be blank"]`.
    fn full_messages(&self) -> Vec<String> {
        self.errors()
            .iter()
            .map(|(c, m)| format!("{} {m}", c.replace('_', " ")))
            .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()
            .find(|(c, _)| *c == column)
            .map(|(_, v)| v.to_text())
            .unwrap_or_default()
    }
}

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