glacier-web 0.4.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
//! Associations: `belongs_to` and `has_many`, loaded with `preload`.
//!
//! ```no_run
//! use glacier::db::{BelongsTo, HasMany};
//! use glacier::prelude::*;
//!
//! #[derive(Clone, Model)]
//! struct User { id: i64, name: String }
//!
//! #[derive(Clone, Model)]
//! struct Comment { id: i64, post_id: i64, body: String }
//!
//! #[derive(Model)]
//! struct Post {
//!     id: i64,
//!     author_id: i64,
//!     #[glacier(belongs_to)]          // uses `author_id`
//!     author: BelongsTo<User>,
//!     #[glacier(has_many)]            // uses `comments.post_id`
//!     comments: HasMany<Comment>,
//! }
//!
//! # async fn demo() -> glacier::Result<()> {
//! let posts = Post::all()
//!     .preload(|p| p.author)
//!     .preload(|p| p.comments)
//!     .await?;                        // 3 queries, however many posts
//! for post in &posts {
//!     println!("{} ({} comments)", post.author.name, post.comments.len());
//! }
//! # Ok(()) }
//! ```
//!
//! Associations are never loaded lazily: touching one that wasn't preloaded
//! panics with a message naming the fix. That turns an accidental N+1 query
//! into a bug you see the first time the code runs.

use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::sync::Arc;

use serde::{Serialize, Serializer};

use super::query::Expr;
use super::value::{ToValue, Value};
use super::{Connection, Query};
use crate::error::Result;
use crate::model::Model;

/// The parent record of a `belongs_to` association.
pub struct BelongsTo<M>(State<Option<M>>);

/// The child records of a `has_many` association.
pub struct HasMany<M>(State<Vec<M>>);

enum State<T> {
    NotLoaded,
    Loaded(T),
}

fn not_loaded<M>() -> ! {
    panic!(
        "association to `{}` was not preloaded; add `.preload(..)` to the query that \
         loaded this record",
        std::any::type_name::<M>()
    )
}

impl<M> BelongsTo<M> {
    pub fn loaded(record: Option<M>) -> Self {
        Self(State::Loaded(record))
    }

    pub fn is_loaded(&self) -> bool {
        matches!(self.0, State::Loaded(_))
    }

    /// The parent, or `None` if it wasn't loaded or doesn't exist.
    pub fn get(&self) -> Option<&M> {
        match &self.0 {
            State::Loaded(record) => record.as_ref(),
            State::NotLoaded => None,
        }
    }
}

/// `post.author.name` reads through to the loaded record.
///
/// # Panics
///
/// If the association wasn't preloaded, or the parent doesn't exist (for a
/// nullable foreign key; use `get` there).
impl<M> Deref for BelongsTo<M> {
    type Target = M;

    fn deref(&self) -> &M {
        match &self.0 {
            State::Loaded(Some(record)) => record,
            State::Loaded(None) => panic!(
                "association to `{}` is empty (the foreign key is NULL or dangling); \
                 use `.get()` for optional associations",
                std::any::type_name::<M>()
            ),
            State::NotLoaded => not_loaded::<M>(),
        }
    }
}

impl<M> HasMany<M> {
    pub fn loaded(records: Vec<M>) -> Self {
        Self(State::Loaded(records))
    }

    pub fn is_loaded(&self) -> bool {
        matches!(self.0, State::Loaded(_))
    }

    /// The children, or `None` if they weren't loaded.
    pub fn get(&self) -> Option<&[M]> {
        match &self.0 {
            State::Loaded(records) => Some(records),
            State::NotLoaded => None,
        }
    }
}

/// `post.comments.len()`, `for c in &post.comments`.
///
/// # Panics
///
/// If the association wasn't preloaded.
impl<M> Deref for HasMany<M> {
    type Target = [M];

    fn deref(&self) -> &[M] {
        self.get().unwrap_or_else(|| not_loaded::<M>())
    }
}

/// `for c in post.comments.iter_mut()`: loaded records change in memory.
impl<M> DerefMut for HasMany<M> {
    fn deref_mut(&mut self) -> &mut [M] {
        match &mut self.0 {
            State::Loaded(records) => records,
            State::NotLoaded => not_loaded::<M>(),
        }
    }
}

impl<'a, M> IntoIterator for &'a HasMany<M> {
    type Item = &'a M;
    type IntoIter = std::slice::Iter<'a, M>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

macro_rules! assoc_impls {
    ($($ty:ident),*) => {$(
        impl<M> Default for $ty<M> {
            fn default() -> Self {
                Self(State::NotLoaded)
            }
        }

        impl<M: Clone> Clone for $ty<M> {
            fn clone(&self) -> Self {
                Self(match &self.0 {
                    State::NotLoaded => State::NotLoaded,
                    State::Loaded(v) => State::Loaded(v.clone()),
                })
            }
        }

        impl<M: fmt::Debug> fmt::Debug for $ty<M> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match &self.0 {
                    State::NotLoaded => f.write_str("NotLoaded"),
                    State::Loaded(v) => v.fmt(f),
                }
            }
        }

        /// Serializes the loaded value; not-loaded serializes as `null`.
        impl<M: Serialize> Serialize for $ty<M> {
            fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
                match &self.0 {
                    State::NotLoaded => s.serialize_none(),
                    State::Loaded(v) => v.serialize(s),
                }
            }
        }
    )*};
}

assoc_impls!(BelongsTo, HasMany);

type PreloadFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;

type LoadAll<M> = dyn for<'a> Fn(&'a mut [M], Connection) -> PreloadFuture<'a> + Send + Sync;

type LoadFn<M, C> = for<'a> fn(&'a mut [M], Connection, Vec<Preload<C>>) -> PreloadFuture<'a>;

/// An association to load alongside a query; from `.preload(|p|
/// p.author)`, or with its own associations: `.preload(|p|
/// p.comments.with(|c| c.author))`.
pub struct Preload<M> {
    load: Arc<LoadAll<M>>,
}

impl<M> Clone for Preload<M> {
    fn clone(&self) -> Self {
        Self {
            load: Arc::clone(&self.load),
        }
    }
}

impl<M> Preload<M> {
    pub(crate) fn run<'a>(&self, records: &'a mut [M], conn: Connection) -> PreloadFuture<'a> {
        (self.load)(records, conn)
    }
}

/// A model's association to `C`, as its `Columns` list it: preload it with
/// `.preload(|p| p.comments)`, and its own associations with `.with(…)`.
pub struct Association<M, C> {
    load: LoadFn<M, C>,
    /// The joining columns, `(this model's, the other's)`, for
    /// `Query::join`; `None` through a join table.
    pub(crate) join: Option<(&'static str, &'static str)>,
}

impl<M, C> Clone for Association<M, C> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<M, C> Copy for Association<M, C> {}

impl<M, C> Association<M, C> {
    #[doc(hidden)]
    pub const fn new(load: LoadFn<M, C>) -> Self {
        Self { load, join: None }
    }

    /// The columns joining the two tables: this model's, then the other's.
    #[doc(hidden)]
    pub const fn joined_on(mut self, own: &'static str, other: &'static str) -> Self {
        self.join = Some((own, other));
        self
    }

    /// Also preloads the associated records' own association:
    /// `p.comments.with(|c| c.author)`.
    pub fn with<P: Into<Preload<C>>>(
        self,
        association: impl FnOnce(&C::Columns) -> P,
    ) -> Nested<M, C>
    where
        C: Model,
    {
        Nested {
            load: self.load,
            nested: vec![association(&C::columns()).into()],
        }
    }
}

/// An association with preloads of its own, from [`Association::with`].
pub struct Nested<M, C> {
    load: LoadFn<M, C>,
    nested: Vec<Preload<C>>,
}

impl<M, C> Nested<M, C> {
    /// Preloads another of the associated records' associations.
    pub fn with<P: Into<Preload<C>>>(mut self, association: impl FnOnce(&C::Columns) -> P) -> Self
    where
        C: Model,
    {
        self.nested.push(association(&C::columns()).into());
        self
    }
}

impl<M: 'static, C: 'static> From<Association<M, C>> for Preload<M> {
    fn from(association: Association<M, C>) -> Self {
        Nested {
            load: association.load,
            nested: Vec::new(),
        }
        .into()
    }
}

impl<M: 'static, C: 'static> From<Nested<M, C>> for Preload<M> {
    fn from(nested: Nested<M, C>) -> Self {
        let Nested { load, nested } = nested;
        let nested = Arc::new(nested);
        Preload {
            load: Arc::new(move |records, conn| load(records, conn, (*nested).clone())),
        }
    }
}

/// Runs `nested` preloads on records just loaded for an association.
async fn run_nested<C>(records: &mut [C], conn: &Connection, nested: &[Preload<C>]) -> Result<()> {
    for preload in nested {
        preload.run(records, conn.clone()).await?;
    }
    Ok(())
}

/// A hashable stand-in for a key value.
fn key(value: &Value) -> Option<String> {
    match value {
        Value::Null => None,
        other => Some(format!("{other:?}")),
    }
}

#[doc(hidden)]
pub async fn load_belongs_to<P, C>(
    parents: &mut [P],
    conn: Connection,
    nested: Vec<Preload<C>>,
    foreign_key: impl Fn(&P) -> Value,
    assign: impl Fn(&mut P, Option<C>),
) -> Result<()>
where
    P: Model,
    C: Model + Clone,
{
    let mut ids: Vec<Value> = Vec::new();
    for parent in parents.iter() {
        let id = foreign_key(parent);
        if key(&id).is_some() && !ids.contains(&id) {
            ids.push(id);
        }
    }
    let found: HashMap<String, C> = if ids.is_empty() {
        HashMap::new()
    } else {
        let mut records = Query::<C>::new()
            .via_association()
            .filter(|_| Expr::In {
                column: C::PRIMARY_KEY,
                values: ids,
            })
            .on(conn.clone())
            .all()
            .await?;
        run_nested(&mut records, &conn, &nested).await?;
        records
            .into_iter()
            .filter_map(|c| Some((key(&c.id_value())?, c)))
            .collect()
    };
    for parent in parents.iter_mut() {
        let record = key(&foreign_key(parent)).and_then(|k| found.get(&k).cloned());
        assign(parent, record);
    }
    Ok(())
}

#[doc(hidden)]
pub async fn load_has_many<P, C>(
    parents: &mut [P],
    conn: Connection,
    nested: Vec<Preload<C>>,
    foreign_key_column: &'static str,
    order: Option<(&'static str, bool)>,
    foreign_key: impl Fn(&C) -> Value,
    assign: impl Fn(&mut P, Vec<C>),
) -> Result<()>
where
    P: Model,
    C: Model,
{
    let ids: Vec<Value> = parents.iter().map(Model::id_value).collect();
    let mut grouped: HashMap<String, Vec<C>> = HashMap::new();
    if !ids.is_empty() {
        let mut query = Query::<C>::new().via_association().filter(|_| Expr::In {
            column: foreign_key_column,
            values: ids,
        });
        if let Some((column, descending)) = order {
            query = query.order(|_| super::query::Order::by(column, descending));
        }
        let mut children = query
            .order(|_| super::query::Order::by(C::PRIMARY_KEY, false))
            .on(conn.clone())
            .all()
            .await?;
        run_nested(&mut children, &conn, &nested).await?;
        for child in children {
            if let Some(k) = key(&foreign_key(&child)) {
                grouped.entry(k).or_default().push(child);
            }
        }
    }
    for parent in parents.iter_mut() {
        let children = key(&parent.id_value())
            .and_then(|k| grouped.remove(&k))
            .unwrap_or_default();
        assign(parent, children);
    }
    Ok(())
}

/// `has_many :x, through: join_table`: the join rows linking each parent
/// to its children, then the children, in two queries.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub async fn load_has_many_through<P, C>(
    parents: &mut [P],
    conn: Connection,
    nested: Vec<Preload<C>>,
    join_table: &'static str,
    owner_key: &'static str,
    target_key: &'static str,
    order: Option<(&'static str, bool)>,
    assign: impl Fn(&mut P, Vec<C>),
) -> Result<()>
where
    P: Model,
    C: Model + Clone,
{
    let ids: Vec<Value> = parents
        .iter()
        .map(Model::id_value)
        .filter(|id| key(id).is_some())
        .collect();
    let mut targets: HashMap<String, Vec<String>> = HashMap::new();
    let mut found: HashMap<String, C> = HashMap::new();
    // Each child's place in the ordered query, for an `order` option.
    let mut rank: HashMap<String, usize> = HashMap::new();
    if !ids.is_empty() {
        let mut sql = super::Sql::new();
        sql.push(&format!(
            "SELECT CAST({owner_key} AS BIGINT) AS owner, CAST({target_key} AS BIGINT) AS target \
             FROM {join_table} WHERE {owner_key}"
        ));
        sql.push_in(ids);
        let rows = conn.read_all(&sql).await?;
        let mut target_ids: Vec<Value> = Vec::new();
        for row in rows.iter() {
            let (Some(owner), Some(target)) = (
                row.get::<Option<i64>>("owner")?,
                row.get::<Option<i64>>("target")?,
            ) else {
                continue;
            };
            let target = Value::Int(target);
            if !target_ids.contains(&target) {
                target_ids.push(target.clone());
            }
            targets
                .entry(key(&Value::Int(owner)).unwrap_or_default())
                .or_default()
                .extend(key(&target));
        }
        if !target_ids.is_empty() {
            let mut query = Query::<C>::new().via_association().filter(|_| Expr::In {
                column: C::PRIMARY_KEY,
                values: target_ids,
            });
            if let Some((column, descending)) = order {
                query = query.order(|_| super::query::Order::by(column, descending));
            }
            let mut children = query.on(conn.clone()).all().await?;
            run_nested(&mut children, &conn, &nested).await?;
            for (i, child) in children.into_iter().enumerate() {
                if let Some(k) = key(&child.id_value()) {
                    rank.insert(k.clone(), i);
                    found.insert(k, child);
                }
            }
        }
    }
    for parent in parents.iter_mut() {
        let mut keys: Vec<&String> = key(&parent.id_value())
            .and_then(|k| targets.get(&k))
            .into_iter()
            .flatten()
            .collect();
        if order.is_some() {
            keys.sort_by_key(|k| rank.get(*k).copied().unwrap_or(usize::MAX));
        }
        let children: Vec<C> = keys
            .into_iter()
            .filter_map(|k| found.get(k).cloned())
            .collect();
        assign(parent, children);
    }
    Ok(())
}

/// `has_many :x, through: join_table`'s `set_x_ids`, as Rails'
/// `x_ids=`: links `owner` to exactly `ids`, deleting the join rows for
/// ids not listed and adding the missing ones in order, so links kept
/// keep their rows.
#[doc(hidden)]
pub async fn set_through_ids(
    owner: Value,
    join_table: &'static str,
    owner_key: &'static str,
    target_key: &'static str,
    ids: Vec<i64>,
) -> Result<()> {
    let conn = super::current()?;
    let mut sql = super::Sql::new();
    sql.push(&format!(
        "SELECT CAST({target_key} AS BIGINT) AS target FROM {join_table} WHERE {owner_key} = "
    ));
    sql.push_value(owner.clone());
    let mut existing = Vec::new();
    for row in conn.fetch_all(&sql).await? {
        if let Some(id) = row.get::<Option<i64>>("target")? {
            existing.push(id);
        }
    }
    let gone: Vec<Value> = existing
        .iter()
        .filter(|id| !ids.contains(id))
        .map(|id| Value::Int(*id))
        .collect();
    if !gone.is_empty() {
        let mut sql = super::Sql::new();
        sql.push(&format!("DELETE FROM {join_table} WHERE {owner_key} = "));
        sql.push_value(owner.clone());
        sql.push(&format!(" AND {target_key}"));
        sql.push_in(gone);
        conn.execute(&sql).await?;
    }
    let mut added = Vec::new();
    for id in ids {
        if existing.contains(&id) || added.contains(&id) {
            continue;
        }
        let mut sql = super::Sql::new();
        sql.push(&format!(
            "INSERT INTO {join_table} ({owner_key}, {target_key}) VALUES ("
        ));
        sql.push_value(owner.clone());
        sql.push(", ");
        sql.push_value(Value::Int(id));
        sql.push(")");
        conn.execute(&sql).await?;
        added.push(id);
    }
    Ok(())
}

/// Used by generated code to turn a field into a `Value`.
#[doc(hidden)]
pub fn value_of<T: ToValue>(value: &T) -> Value {
    value.to_value()
}

/// Sets a parent's `updated_at` to now, for `belongs_to … touch`. Nothing
/// happens without a parent (a null key) or an `updated_at` column.
#[doc(hidden)]
pub async fn touch_parent<P: crate::model::Model>(id: Value) -> Result<()> {
    let Some(column) = P::UPDATED_AT else {
        return Ok(());
    };
    if id.is_null() {
        return Ok(());
    }
    let mut sql = crate::db::Sql::new();
    sql.push("UPDATE ")
        .push_ident(P::TABLE)
        .push(" SET ")
        .push_ident(column)
        .push(" = ");
    sql.push_value(Value::Timestamp(crate::time::now()));
    sql.push(" WHERE ").push_ident(P::PRIMARY_KEY).push(" = ");
    sql.push_value(id);
    crate::db::current_in(P::DATABASE)?.execute(&sql).await?;
    Ok(())
}

const NESTED_INVALID: &str = "glacier: a nested record is invalid";

/// The error that rolls back a save whose nested records are invalid.
#[doc(hidden)]
pub fn nested_invalid() -> crate::Error {
    crate::Error::unprocessable(NESTED_INVALID)
}

#[doc(hidden)]
pub fn is_nested_invalid(err: &crate::Error) -> bool {
    err.message() == NESTED_INVALID
}

/// One entry of `has_many … nested` attributes, as Rails applies it: an
/// `id` updates that child (one of the parent's, else `404`), `_destroy`
/// destroys it (when allowed), and no `id` creates one. Returns the
/// child's errors, if it's invalid.
#[doc(hidden)]
pub async fn save_nested_child<C>(
    parent_id: Value,
    foreign_key: &'static str,
    entry: &crate::Params,
    allow_destroy: bool,
) -> Result<Vec<String>>
where
    C: crate::model::Model + Default + Clone,
{
    let id = entry.get("id").map(str::trim).filter(|id| !id.is_empty());
    let Some(id) = id else {
        let mut params = entry.clone().without("_destroy");
        params.insert(foreign_key, parent_id.to_text());
        let mut child = C::default();
        return Ok(if child.update(params).await? {
            Vec::new()
        } else {
            child.messages()
        });
    };
    let id = id.parse::<i64>().map_err(|_| crate::Error::not_found())?;
    let child = Query::<C>::new()
        .via_association()
        .filter(|_| Expr::Compare {
            column: C::PRIMARY_KEY,
            op: "=",
            value: Value::Int(id),
        })
        .filter(|_| Expr::Compare {
            column: foreign_key,
            op: "=",
            value: parent_id,
        })
        .first()
        .await?;
    let Some(mut child) = child else {
        return Err(crate::Error::not_found());
    };
    let destroy = entry
        .get("_destroy")
        .is_some_and(|d| matches!(d.trim(), "1" | "true" | "on" | "yes"));
    if destroy && allow_destroy {
        child.destroy().await?;
        return Ok(Vec::new());
    }
    let params = entry.clone().without("id").without("_destroy");
    Ok(if child.update(params).await? {
        Vec::new()
    } else {
        child.messages()
    })
}