rustrails-record 0.1.2

ORM layer (ActiveRecord equivalent)
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
use std::collections::HashMap;

use crate::{Record, Relation};

/// A named scope that transforms a [`Relation`].
pub type ScopeFunction<T> = Box<dyn Fn(Relation<T>) -> Relation<T> + Send + Sync>;

/// Registry of named scopes for a record type.
pub struct ScopeRegistry<T: Record> {
    scopes: HashMap<String, ScopeFunction<T>>,
}

impl<T: Record> Default for ScopeRegistry<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Record> ScopeRegistry<T> {
    /// Creates an empty scope registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            scopes: HashMap::new(),
        }
    }

    /// Registers or replaces a named scope.
    pub fn add(
        &mut self,
        name: impl Into<String>,
        scope: impl Fn(Relation<T>) -> Relation<T> + Send + Sync + 'static,
    ) {
        self.scopes.insert(name.into(), Box::new(scope));
    }

    /// Applies a named scope to the provided relation.
    #[must_use]
    pub fn apply(&self, name: &str, relation: Relation<T>) -> Option<Relation<T>> {
        self.scopes.get(name).map(|scope| scope(relation))
    }

    /// Returns the registered scope names.
    #[must_use]
    pub fn names(&self) -> Vec<&String> {
        self.scopes.keys().collect()
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use serde_json::json;

    use super::ScopeRegistry;
    use crate::{
        OrderDirection, Relation,
        base::test_support::{TestUser, seed_users, setup_db},
    };

    fn named_scope(
        expected: &'static str,
    ) -> impl Fn(Relation<TestUser>) -> Relation<TestUser> + Send + Sync + 'static {
        move |relation| relation.r#where(HashMap::from([("name".to_owned(), json!(expected))]))
    }

    #[tokio::test]
    async fn apply_returns_none_for_unknown_scope() {
        let registry = ScopeRegistry::<TestUser>::new();

        assert!(registry.apply("missing", Relation::new()).is_none());
    }

    #[tokio::test]
    async fn apply_runs_registered_scope() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("named_bob", |relation| {
            relation.r#where(HashMap::from([("name".to_owned(), json!("Bob"))]))
        });

        let relation = registry
            .apply("named_bob", Relation::new())
            .expect("scope should exist");
        let users = relation
            .load(&db)
            .await
            .expect("scoped query should succeed");

        assert_eq!(users.len(), 1);
        assert_eq!(users[0].name, "Bob");
    }

    #[tokio::test]
    async fn scope_can_modify_relation_with_limit() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("first_two", |relation| relation.limit(2));

        let relation = registry
            .apply("first_two", Relation::new())
            .expect("scope should exist");
        let users = relation
            .load(&db)
            .await
            .expect("limited query should succeed");

        assert_eq!(users.len(), 2);
    }

    #[tokio::test]
    async fn add_replaces_existing_scope_name() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("window", |relation| relation.limit(1));
        registry.add("window", |relation| relation.limit(2));

        let relation = registry
            .apply("window", Relation::new())
            .expect("scope should exist");
        let users = relation.load(&db).await.expect("query should succeed");

        assert_eq!(users.len(), 2);
    }

    #[test]
    fn names_returns_registered_scope_names() {
        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("recent", |relation| relation.limit(1));
        registry.add("alphabetical", |relation| relation);

        let mut names = registry
            .names()
            .into_iter()
            .map(|name| name.as_str())
            .collect::<Vec<_>>();
        names.sort_unstable();

        assert_eq!(names, vec!["alphabetical", "recent"]);
    }

    #[test]
    fn default_registry_starts_without_names() {
        let registry = ScopeRegistry::<TestUser>::default();

        assert!(registry.names().is_empty());
    }

    #[tokio::test]
    async fn scope_name_with_spaces_is_applied() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("named bob", named_scope("Bob"));

        let users = registry
            .apply("named bob", Relation::new())
            .expect("scope should exist")
            .load(&db)
            .await
            .expect("scoped query should succeed");

        assert_eq!(users.len(), 1);
        assert_eq!(users[0].name, "Bob");
    }

    #[tokio::test]
    async fn scope_can_capture_external_value() {
        let db = setup_db().await;
        seed_users(&db).await;

        let expected = "Carol".to_owned();
        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("captured_name", move |relation| {
            relation.r#where(HashMap::from([(
                "name".to_owned(),
                json!(expected.clone()),
            )]))
        });

        let users = registry
            .apply("captured_name", Relation::new())
            .expect("scope should exist")
            .load(&db)
            .await
            .expect("captured query should succeed");

        assert_eq!(users.len(), 1);
        assert_eq!(users[0].email, "carol@example.com");
    }

    #[tokio::test]
    async fn scope_factory_with_argument_filters_expected_row() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("named_alice", named_scope("Alice"));

        let user = registry
            .apply("named_alice", Relation::new())
            .expect("scope should exist")
            .first(&db)
            .await
            .expect("query should succeed")
            .expect("alice should exist");

        assert_eq!(user.email, "alice@example.com");
    }

    #[tokio::test]
    async fn scope_chaining_applies_multiple_registered_scopes() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("without_alice", |relation| {
            relation.not(HashMap::from([("name".to_owned(), json!("Alice"))]))
        });
        registry.add("descending", |relation| {
            relation.order("name", OrderDirection::Desc)
        });

        let relation = registry
            .apply("without_alice", Relation::new())
            .expect("first scope should exist");
        let relation = registry
            .apply("descending", relation)
            .expect("second scope should exist");
        let users = relation
            .load(&db)
            .await
            .expect("chained scope should succeed");

        let names = users.into_iter().map(|user| user.name).collect::<Vec<_>>();
        assert_eq!(names, vec!["Carol", "Bob"]);
    }

    #[tokio::test]
    async fn scope_can_extend_existing_relation_filters() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("first_match", |relation| relation.limit(1));

        let base = Relation::new().r#where(HashMap::from([("name".to_owned(), json!("Carol"))]));
        let users = registry
            .apply("first_match", base)
            .expect("scope should exist")
            .load(&db)
            .await
            .expect("merged query should succeed");

        assert_eq!(users.len(), 1);
        assert_eq!(users[0].name, "Carol");
    }

    #[tokio::test]
    async fn scope_can_order_results_descending() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("desc_by_name", |relation| {
            relation.order("name", OrderDirection::Desc)
        });

        let first = registry
            .apply("desc_by_name", Relation::new())
            .expect("scope should exist")
            .first(&db)
            .await
            .expect("ordered query should succeed")
            .expect("a row should exist");

        assert_eq!(first.name, "Carol");
    }

    #[tokio::test]
    async fn scope_can_skip_rows_with_offset() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("skip_first", |relation| {
            relation.order("id", OrderDirection::Asc).offset(1)
        });

        let users = registry
            .apply("skip_first", Relation::new())
            .expect("scope should exist")
            .load(&db)
            .await
            .expect("offset query should succeed");

        let names = users.into_iter().map(|user| user.name).collect::<Vec<_>>();
        assert_eq!(names, vec!["Bob", "Carol"]);
    }

    #[tokio::test]
    async fn scope_can_add_negated_filters() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("without_bob", |relation| {
            relation.not(HashMap::from([("name".to_owned(), json!("Bob"))]))
        });

        let users = registry
            .apply("without_bob", Relation::new())
            .expect("scope should exist")
            .load(&db)
            .await
            .expect("negated query should succeed");

        let names = users.into_iter().map(|user| user.name).collect::<Vec<_>>();
        assert_eq!(names, vec!["Alice", "Carol"]);
    }

    #[tokio::test]
    async fn scope_merge_like_composition_preserves_all_constraints() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("only_carol", named_scope("Carol"));
        registry.add("take_one", |relation| relation.limit(1));

        let relation = registry
            .apply(
                "only_carol",
                Relation::new().order("id", OrderDirection::Desc),
            )
            .expect("first scope should exist");
        let exists = registry
            .apply("take_one", relation)
            .expect("second scope should exist")
            .exists(&db)
            .await
            .expect("exists query should succeed");

        assert!(exists);
    }

    #[test]
    fn replacing_scope_keeps_single_registered_name() {
        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("window", |relation| relation.limit(1));
        registry.add("window", |relation| relation.limit(2));

        let mut names = registry
            .names()
            .into_iter()
            .map(|name| name.as_str())
            .collect::<Vec<_>>();
        names.sort_unstable();

        assert_eq!(names, vec!["window"]);
    }

    #[tokio::test]
    async fn scope_application_is_repeatable_without_state_leakage() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("without_alice", |relation| {
            relation.not(HashMap::from([("name".to_owned(), json!("Alice"))]))
        });

        let first = registry
            .apply("without_alice", Relation::new())
            .expect("scope should exist")
            .load(&db)
            .await
            .expect("first scoped query should succeed");
        let second = registry
            .apply("without_alice", Relation::new())
            .expect("scope should exist")
            .load(&db)
            .await
            .expect("second scoped query should succeed");

        let first_names = first.into_iter().map(|user| user.name).collect::<Vec<_>>();
        let second_names = second.into_iter().map(|user| user.name).collect::<Vec<_>>();

        assert_eq!(first_names, vec!["Bob", "Carol"]);
        assert_eq!(second_names, vec!["Bob", "Carol"]);
    }

    #[tokio::test]
    async fn scope_preserves_existing_order_when_it_only_adds_filters() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut registry = ScopeRegistry::<TestUser>::new();
        registry.add("without_carol", |relation| {
            relation.not(HashMap::from([("name".to_owned(), json!("Carol"))]))
        });

        let users = registry
            .apply(
                "without_carol",
                Relation::new().order("name", OrderDirection::Desc),
            )
            .expect("scope should exist")
            .load(&db)
            .await
            .expect("ordered scoped query should succeed");

        let names = users.into_iter().map(|user| user.name).collect::<Vec<_>>();
        assert_eq!(names, vec!["Bob", "Alice"]);
    }
}