rustrails-storage 0.1.2

File storage (ActiveStorage 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
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
//! Attachment associations between records and blobs.

use chrono::{DateTime, Utc};
use rustrails_support::runtime;
use thiserror::Error;
use uuid::Uuid;

use crate::{
    blob::Blob,
    service::{StorageError, StorageService},
};

/// Errors returned by attachment operations.
#[derive(Debug, Error)]
pub enum AttachmentError {
    /// The attachment name was empty.
    #[error("attachment name must not be empty")]
    EmptyName,
    /// A storage backend failed while purging the blob.
    #[error(transparent)]
    Storage(#[from] StorageError),
}

/// Links a blob to a record instance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attachment {
    id: Uuid,
    record_type: String,
    record_id: String,
    name: String,
    blob: Blob,
    created_at: DateTime<Utc>,
}

impl Attachment {
    /// Creates a new attachment.
    ///
    /// # Errors
    ///
    /// Returns an error when the attachment name is empty.
    pub fn new(
        record_type: impl Into<String>,
        record_id: impl Into<String>,
        name: impl Into<String>,
        blob: Blob,
    ) -> Result<Self, AttachmentError> {
        let name = name.into();
        if name.trim().is_empty() {
            return Err(AttachmentError::EmptyName);
        }
        Ok(Self {
            id: Uuid::now_v7(),
            record_type: record_type.into(),
            record_id: record_id.into(),
            name,
            blob,
            created_at: Utc::now(),
        })
    }

    /// Returns the attachment identifier.
    #[must_use]
    pub fn id(&self) -> Uuid {
        self.id
    }

    /// Returns the owning record type.
    #[must_use]
    pub fn record_type(&self) -> &str {
        &self.record_type
    }

    /// Returns the owning record identifier.
    #[must_use]
    pub fn record_id(&self) -> &str {
        &self.record_id
    }

    /// Returns the attachment name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the referenced blob.
    #[must_use]
    pub fn blob(&self) -> &Blob {
        &self.blob
    }

    /// Returns the blob identifier.
    #[must_use]
    pub fn blob_id(&self) -> Uuid {
        self.blob.id()
    }

    /// Returns the creation timestamp.
    #[must_use]
    pub fn created_at(&self) -> DateTime<Utc> {
        self.created_at
    }

    /// Deletes the attached blob from storage.
    ///
    /// # Errors
    ///
    /// Returns an error when the storage service delete fails.
    pub async fn purge<S: StorageService + ?Sized>(
        &self,
        service: &S,
    ) -> Result<(), AttachmentError> {
        service.delete(self.blob.key()).await?;
        Ok(())
    }

    /// Deletes the attached blob from storage using the thread-local runtime.
    ///
    /// # Errors
    ///
    /// Returns an error when the storage service delete fails.
    pub fn purge_sync<S: StorageService + ?Sized>(
        &self,
        service: &S,
    ) -> Result<(), AttachmentError> {
        runtime::block_on(self.purge(service))
    }
}

/// Metadata describing a `has_one_attached` declaration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HasOneAttached {
    /// Attachment name on the owning record.
    pub name: String,
}

impl HasOneAttached {
    /// Creates `has_one_attached` metadata.
    ///
    /// # Errors
    ///
    /// Returns an error when the attachment name is empty.
    pub fn new(name: impl Into<String>) -> Result<Self, AttachmentError> {
        Ok(Self {
            name: validated_name(name.into())?,
        })
    }

    /// Binds this metadata to a specific record instance.
    #[must_use]
    pub fn bind(
        &self,
        record_type: impl Into<String>,
        record_id: impl Into<String>,
    ) -> OneAttachment {
        OneAttachment::new(record_type, record_id, self.name.clone())
    }
}

/// Creates metadata for a `has_one_attached` declaration.
///
/// # Errors
///
/// Returns an error when the attachment name is empty.
pub fn has_one_attached(name: impl Into<String>) -> Result<HasOneAttached, AttachmentError> {
    HasOneAttached::new(name)
}

/// Metadata describing a `has_many_attached` declaration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HasManyAttached {
    /// Attachment collection name on the owning record.
    pub name: String,
}

impl HasManyAttached {
    /// Creates `has_many_attached` metadata.
    ///
    /// # Errors
    ///
    /// Returns an error when the attachment name is empty.
    pub fn new(name: impl Into<String>) -> Result<Self, AttachmentError> {
        Ok(Self {
            name: validated_name(name.into())?,
        })
    }

    /// Binds this metadata to a specific record instance.
    #[must_use]
    pub fn bind(
        &self,
        record_type: impl Into<String>,
        record_id: impl Into<String>,
    ) -> ManyAttachments {
        ManyAttachments::new(record_type, record_id, self.name.clone())
    }
}

/// Creates metadata for a `has_many_attached` declaration.
///
/// # Errors
///
/// Returns an error when the attachment name is empty.
pub fn has_many_attached(name: impl Into<String>) -> Result<HasManyAttached, AttachmentError> {
    HasManyAttached::new(name)
}

/// Represents a `has_one_attached` relation.
#[derive(Debug, Clone)]
pub struct OneAttachment {
    record_type: String,
    record_id: String,
    name: String,
    attachment: Option<Attachment>,
}

impl OneAttachment {
    /// Creates an empty one-to-one attachment relation.
    #[must_use]
    pub fn new(
        record_type: impl Into<String>,
        record_id: impl Into<String>,
        name: impl Into<String>,
    ) -> Self {
        Self {
            record_type: record_type.into(),
            record_id: record_id.into(),
            name: name.into(),
            attachment: None,
        }
    }

    /// Attaches a blob, replacing any existing attachment.
    ///
    /// # Errors
    ///
    /// Returns an error when the attachment cannot be built.
    pub fn attach(&mut self, blob: Blob) -> Result<&Attachment, AttachmentError> {
        if self
            .attachment
            .as_ref()
            .is_some_and(|current| current.blob_id() == blob.id())
        {
            return self.attachment.as_ref().ok_or(AttachmentError::EmptyName);
        }
        self.attachment = Some(Attachment::new(
            self.record_type.clone(),
            self.record_id.clone(),
            self.name.clone(),
            blob,
        )?);
        self.attachment.as_ref().ok_or(AttachmentError::EmptyName)
    }

    /// Returns whether a blob is currently attached.
    #[must_use]
    pub fn is_attached(&self) -> bool {
        self.attachment.is_some()
    }

    /// Returns the current attachment, if any.
    #[must_use]
    pub fn attachment(&self) -> Option<&Attachment> {
        self.attachment.as_ref()
    }

    /// Removes the current attachment and returns it.
    pub fn detach(&mut self) -> Option<Attachment> {
        self.attachment.take()
    }

    /// Purges the current attachment from storage and detaches it.
    ///
    /// # Errors
    ///
    /// Returns an error when the storage service delete fails.
    pub async fn purge<S: StorageService + ?Sized>(
        &mut self,
        service: &S,
    ) -> Result<Option<Attachment>, AttachmentError> {
        if let Some(attachment) = &self.attachment {
            attachment.purge(service).await?;
        }
        Ok(self.detach())
    }

    /// Purges the current attachment from storage and detaches it using the thread-local runtime.
    ///
    /// # Errors
    ///
    /// Returns an error when the storage service delete fails.
    pub fn purge_sync<S: StorageService + ?Sized>(
        &mut self,
        service: &S,
    ) -> Result<Option<Attachment>, AttachmentError> {
        runtime::block_on(self.purge(service))
    }
}

/// Represents a `has_many_attached` relation.
#[derive(Debug, Clone)]
pub struct ManyAttachments {
    record_type: String,
    record_id: String,
    name: String,
    attachments: Vec<Attachment>,
}

impl ManyAttachments {
    /// Creates an empty collection attachment relation.
    #[must_use]
    pub fn new(
        record_type: impl Into<String>,
        record_id: impl Into<String>,
        name: impl Into<String>,
    ) -> Self {
        Self {
            record_type: record_type.into(),
            record_id: record_id.into(),
            name: name.into(),
            attachments: Vec::new(),
        }
    }

    /// Appends a blob to the collection.
    ///
    /// # Errors
    ///
    /// Returns an error when the attachment cannot be built.
    pub fn attach(&mut self, blob: Blob) -> Result<&Attachment, AttachmentError> {
        let attachment = Attachment::new(
            self.record_type.clone(),
            self.record_id.clone(),
            self.name.clone(),
            blob,
        )?;
        self.attachments.push(attachment);
        self.attachments.last().ok_or(AttachmentError::EmptyName)
    }

    /// Appends several blobs to the collection.
    ///
    /// # Errors
    ///
    /// Returns an error when any attachment cannot be built.
    pub fn attach_many<I>(&mut self, blobs: I) -> Result<(), AttachmentError>
    where
        I: IntoIterator<Item = Blob>,
    {
        for blob in blobs {
            let _ = self.attach(blob)?;
        }
        Ok(())
    }

    /// Returns whether at least one blob is attached.
    #[must_use]
    pub fn is_attached(&self) -> bool {
        !self.attachments.is_empty()
    }

    /// Returns the attachment count.
    #[must_use]
    pub fn len(&self) -> usize {
        self.attachments.len()
    }

    /// Returns whether the collection is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.attachments.is_empty()
    }

    /// Returns all attachments in insertion order.
    #[must_use]
    pub fn attachments(&self) -> &[Attachment] {
        &self.attachments
    }

    /// Returns an iterator over the attached blobs.
    pub fn blobs(&self) -> impl Iterator<Item = &Blob> {
        self.attachments.iter().map(Attachment::blob)
    }

    /// Removes an attachment by blob id.
    pub fn detach_blob(&mut self, blob_id: Uuid) -> Option<Attachment> {
        self.attachments
            .iter()
            .position(|attachment| attachment.blob_id() == blob_id)
            .map(|index| self.attachments.remove(index))
    }

    /// Purges all attached blobs from storage and clears the collection.
    ///
    /// # Errors
    ///
    /// Returns an error when any storage delete fails.
    pub async fn purge_all<S: StorageService + ?Sized>(
        &mut self,
        service: &S,
    ) -> Result<Vec<Attachment>, AttachmentError> {
        for attachment in &self.attachments {
            attachment.purge(service).await?;
        }
        Ok(std::mem::take(&mut self.attachments))
    }

    /// Purges all attached blobs from storage and clears the collection using the thread-local runtime.
    ///
    /// # Errors
    ///
    /// Returns an error when any storage delete fails.
    pub fn purge_all_sync<S: StorageService + ?Sized>(
        &mut self,
        service: &S,
    ) -> Result<Vec<Attachment>, AttachmentError> {
        runtime::block_on(self.purge_all(service))
    }
}

fn validated_name(name: String) -> Result<String, AttachmentError> {
    if name.trim().is_empty() {
        Err(AttachmentError::EmptyName)
    } else {
        Ok(name)
    }
}

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

    use bytes::Bytes;
    use rustrails_support::runtime;

    use super::*;
    use crate::{blob::Blob, service::memory::MemoryService, test_support::run_sync_test};

    fn blob(filename: &str) -> Blob {
        Blob::create(
            Bytes::from(filename.as_bytes().to_vec()),
            filename.to_owned(),
            None,
            BTreeMap::new(),
            "memory",
        )
        .expect("blob should build")
    }

    #[test]
    fn test_attachment_new_captures_record_information() {
        let attachment = Attachment::new("User", "1", "avatar", blob("avatar.png"))
            .expect("attachment should build");
        assert_eq!(attachment.record_type(), "User");
        assert_eq!(attachment.record_id(), "1");
        assert_eq!(attachment.name(), "avatar");
    }

    #[test]
    fn test_attachment_rejects_empty_name() {
        let error = Attachment::new("User", "1", "", blob("avatar.png"))
            .expect_err("attachment should fail");
        assert!(matches!(error, AttachmentError::EmptyName));
    }

    #[test]
    fn test_one_attachment_attach_sets_current_attachment() {
        let mut one = OneAttachment::new("User", "1", "avatar");
        let attachment = one
            .attach(blob("avatar.png"))
            .expect("attach should succeed");
        assert_eq!(attachment.name(), "avatar");
        assert!(one.is_attached());
    }

    #[test]
    fn test_one_attachment_replace_swaps_blob() {
        let mut one = OneAttachment::new("User", "1", "avatar");
        let _ = one.attach(blob("old.png")).expect("attach should succeed");
        let attachment = one.attach(blob("new.png")).expect("attach should succeed");
        assert_eq!(attachment.blob().filename(), "new.png");
    }

    #[test]
    fn test_one_attachment_attaching_same_blob_keeps_attachment() {
        let mut one = OneAttachment::new("User", "1", "avatar");
        let avatar = blob("avatar.png");
        let first_id = one
            .attach(avatar.clone())
            .expect("attach should succeed")
            .id();
        let second_id = one.attach(avatar).expect("attach should succeed").id();
        assert_eq!(first_id, second_id);
    }

    #[test]
    fn test_one_attachment_detach_returns_previous_attachment() {
        let mut one = OneAttachment::new("User", "1", "avatar");
        let _ = one
            .attach(blob("avatar.png"))
            .expect("attach should succeed");
        let detached = one.detach().expect("attachment should exist");
        assert_eq!(detached.blob().filename(), "avatar.png");
        assert!(!one.is_attached());
    }

    #[tokio::test]
    async fn test_one_attachment_purge_deletes_backing_blob() {
        let service = MemoryService::new("memory").expect("service should build");
        let blob = blob("avatar.png");
        service
            .upload(blob.key(), Bytes::from_static(b"avatar"))
            .await
            .expect("upload should succeed");
        let mut one = OneAttachment::new("User", "1", "avatar");
        let _ = one.attach(blob.clone()).expect("attach should succeed");
        let purged = one.purge(&service).await.expect("purge should succeed");
        assert_eq!(
            purged.expect("attachment should be returned").blob_id(),
            blob.id()
        );
        assert!(
            !service
                .exists(blob.key())
                .await
                .expect("exists should succeed")
        );
    }

    #[test]
    fn test_attachment_purge_sync_deletes_backing_blob() {
        run_sync_test(|| {
            let service = MemoryService::new("memory").expect("service should build");
            let blob = blob("avatar.png");
            runtime::block_on(service.upload(blob.key(), Bytes::from_static(b"avatar")))
                .expect("upload should succeed");
            let attachment = Attachment::new("User", "1", "avatar", blob.clone())
                .expect("attachment should build");

            attachment
                .purge_sync(&service)
                .expect("purge_sync should succeed");

            assert!(!runtime::block_on(service.exists(blob.key())).expect("exists should succeed"));
        });
    }

    #[test]
    fn test_one_attachment_purge_sync_deletes_backing_blob() {
        run_sync_test(|| {
            let service = MemoryService::new("memory").expect("service should build");
            let blob = blob("avatar.png");
            runtime::block_on(service.upload(blob.key(), Bytes::from_static(b"avatar")))
                .expect("upload should succeed");
            let mut one = OneAttachment::new("User", "1", "avatar");
            let _ = one.attach(blob.clone()).expect("attach should succeed");

            let purged = one.purge_sync(&service).expect("purge_sync should succeed");

            assert_eq!(
                purged.expect("attachment should be returned").blob_id(),
                blob.id()
            );
            assert!(!runtime::block_on(service.exists(blob.key())).expect("exists should succeed"));
        });
    }

    #[test]
    fn test_many_attachments_attach_preserves_order() {
        let mut many = ManyAttachments::new("User", "1", "photos");
        let _ = many.attach(blob("one.png")).expect("attach should succeed");
        let _ = many.attach(blob("two.png")).expect("attach should succeed");
        assert_eq!(many.attachments()[0].blob().filename(), "one.png");
        assert_eq!(many.attachments()[1].blob().filename(), "two.png");
    }

    #[test]
    fn test_many_attachments_attach_many_adds_all_blobs() {
        let mut many = ManyAttachments::new("User", "1", "photos");
        many.attach_many([blob("one.png"), blob("two.png")])
            .expect("attach should succeed");
        assert_eq!(many.len(), 2);
    }

    #[test]
    fn test_many_attachments_reports_empty_state() {
        let many = ManyAttachments::new("User", "1", "photos");
        assert!(many.is_empty());
        assert!(!many.is_attached());
    }

    #[test]
    fn test_many_attachments_blobs_iterator_exposes_blob_names() {
        let mut many = ManyAttachments::new("User", "1", "photos");
        many.attach_many([blob("one.png"), blob("two.png")])
            .expect("attach should succeed");
        let names: Vec<_> = many
            .blobs()
            .map(|blob| blob.filename().to_owned())
            .collect();
        assert_eq!(names, ["one.png", "two.png"]);
    }

    #[test]
    fn test_many_attachments_detach_blob_removes_only_matching_blob() {
        let mut many = ManyAttachments::new("User", "1", "photos");
        let first = blob("one.png");
        let first_id = first.id();
        many.attach_many([first, blob("two.png")])
            .expect("attach should succeed");
        let detached = many.detach_blob(first_id).expect("attachment should exist");
        assert_eq!(detached.blob().filename(), "one.png");
        assert_eq!(many.len(), 1);
        assert_eq!(many.attachments()[0].blob().filename(), "two.png");
    }

    #[test]
    fn test_many_attachments_detach_blob_returns_none_for_missing_blob() {
        let mut many = ManyAttachments::new("User", "1", "photos");
        many.attach(blob("one.png")).expect("attach should succeed");
        assert!(many.detach_blob(Uuid::now_v7()).is_none());
    }

    #[tokio::test]
    async fn test_many_attachments_purge_all_deletes_backing_blobs() {
        let service = MemoryService::new("memory").expect("service should build");
        let first = blob("one.png");
        let second = blob("two.png");
        service
            .upload(first.key(), Bytes::from_static(b"one"))
            .await
            .expect("upload should succeed");
        service
            .upload(second.key(), Bytes::from_static(b"two"))
            .await
            .expect("upload should succeed");
        let mut many = ManyAttachments::new("User", "1", "photos");
        many.attach_many([first.clone(), second.clone()])
            .expect("attach should succeed");
        let purged = many
            .purge_all(&service)
            .await
            .expect("purge should succeed");
        assert_eq!(purged.len(), 2);
        assert!(
            !service
                .exists(first.key())
                .await
                .expect("exists should succeed")
        );
        assert!(
            !service
                .exists(second.key())
                .await
                .expect("exists should succeed")
        );
        assert!(many.is_empty());
    }

    #[test]
    fn test_many_attachments_purge_all_sync_deletes_backing_blobs() {
        run_sync_test(|| {
            let service = MemoryService::new("memory").expect("service should build");
            let first = blob("one.png");
            let second = blob("two.png");
            runtime::block_on(service.upload(first.key(), Bytes::from_static(b"one")))
                .expect("upload should succeed");
            runtime::block_on(service.upload(second.key(), Bytes::from_static(b"two")))
                .expect("upload should succeed");
            let mut many = ManyAttachments::new("User", "1", "photos");
            many.attach_many([first.clone(), second.clone()])
                .expect("attach should succeed");

            let purged = many
                .purge_all_sync(&service)
                .expect("purge_all_sync should succeed");

            assert_eq!(purged.len(), 2);
            assert!(
                !runtime::block_on(service.exists(first.key())).expect("exists should succeed")
            );
            assert!(
                !runtime::block_on(service.exists(second.key())).expect("exists should succeed")
            );
            assert!(many.is_empty());
        });
    }

    #[test]
    fn test_many_attachments_can_attach_duplicate_filenames() {
        let mut many = ManyAttachments::new("User", "1", "photos");
        many.attach_many([blob("same.png"), blob("same.png")])
            .expect("attach should succeed");
        assert_eq!(many.len(), 2);
        assert_ne!(
            many.attachments()[0].blob_id(),
            many.attachments()[1].blob_id()
        );
    }

    #[test]
    fn test_attachment_created_at_is_recent() {
        let attachment = Attachment::new("User", "1", "avatar", blob("avatar.png"))
            .expect("attachment should build");
        assert!(attachment.created_at() <= Utc::now());
    }

    #[test]
    fn test_one_attachment_empty_relation_has_no_attachment() {
        let one = OneAttachment::new("User", "1", "avatar");
        assert!(one.attachment().is_none());
    }

    #[test]
    fn test_many_attachments_share_name_for_each_attachment() {
        let mut many = ManyAttachments::new("User", "1", "photos");
        many.attach_many([blob("one.png"), blob("two.png")])
            .expect("attach should succeed");
        assert!(
            many.attachments()
                .iter()
                .all(|attachment| attachment.name() == "photos")
        );
    }

    #[test]
    fn test_has_one_attached_metadata_binds_to_record() {
        let metadata = has_one_attached("avatar").expect("metadata should build");
        let relation = metadata.bind("User", "1");
        assert!(!relation.is_attached());
        assert_eq!(metadata.name, "avatar");
    }

    #[test]
    fn test_has_many_attached_metadata_binds_to_record() {
        let metadata = has_many_attached("photos").expect("metadata should build");
        let relation = metadata.bind("User", "1");
        assert!(relation.is_empty());
        assert_eq!(metadata.name, "photos");
    }

    #[test]
    fn test_attachment_metadata_rejects_blank_name() {
        assert!(matches!(
            has_one_attached("   "),
            Err(AttachmentError::EmptyName)
        ));
        assert!(matches!(
            has_many_attached(""),
            Err(AttachmentError::EmptyName)
        ));
    }
}