tideorm 0.9.3

A developer-friendly ORM for Rust with clean, expressive syntax
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
//! File Attachments System
//!
//! This module provides file attachment functionality for TideORM models.
//!
//! ## Overview
//!
//! File attachments allow you to associate files with your models using a JSONB column.
//! Files can be attached as:
//! - **HasOne**: Single file attachment (e.g., `thumbnail`, `avatar`)
//! - **HasMany**: Multiple file attachments (e.g., `images`, `documents`)
//!
//! ## Setup
//!
//! Add a `files` JSONB column to your table and use the `#[tideorm(has_one_file)]` or
//! `#[tideorm(has_many_files)]` attributes:
//!
//! ```rust,ignore
//! #[tideorm::model(table = "products")]
//! #[tideorm(has_one_file = "thumbnail")]
//! #[tideorm(has_many_files = "images,documents")]
//! pub struct Product {
//!     #[tideorm(primary_key, auto_increment)]
//!     pub id: i64,
//!     pub name: String,
//!     pub files: Option<Json>,  // JSONB column storing attachments
//! }
//! ```
//!
//! ## Usage
//!
//! ### Attaching Files
//!
//! ```rust,ignore
//! // Attach a single file (hasOne)
//! product.attach("thumbnail", "uploads/thumb.jpg")?;
//!
//! // Attach multiple files (hasMany)
//! product.attach("images", "uploads/img1.jpg")?;
//! product.attach("images", "uploads/img2.jpg")?;
//!
//! // Or attach multiple at once
//! product.attach_many("images", vec!["uploads/img3.jpg", "uploads/img4.jpg"])?;
//!
//! // Save the model to persist changes
//! product.update().await?;
//! ```
//!
//! ### Detaching Files
//!
//! ```rust,ignore
//! // Detach a specific file
//! product.detach("images", Some("uploads/img1.jpg"))?;
//!
//! // Detach all files from a relation
//! product.detach("images", None)?;
//!
//! product.update().await?;
//! ```
//!
//! ### Syncing Files (Replace All)
//!
//! ```rust,ignore
//! // Replace all images with new ones
//! product.sync("images", vec!["uploads/new1.jpg", "uploads/new2.jpg"])?;
//!
//! // Clear all images
//! product.sync("images", vec![])?;
//!
//! product.update().await?;
//! ```
//!
//! ## File Metadata
//!
//! Each attachment stores metadata:
//! - `key`: The file path/key
//! - `filename`: Extracted filename
//! - `created_at`: Timestamp when attached
//! - Additional fields can be added via `attach_with_metadata`

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// File attachment metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileAttachment {
    /// The file key/path (e.g., "uploads/2024/01/image.jpg")
    pub key: String,

    /// The filename (extracted from key)
    pub filename: String,

    /// When the file was attached
    pub created_at: String,

    /// Original filename (if different from key)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub original_filename: Option<String>,

    /// File size in bytes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<u64>,

    /// MIME type
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,

    /// Custom metadata
    #[serde(flatten, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, serde_json::Value>,
}

impl FileAttachment {
    /// Create a new file attachment from a key
    pub fn new(key: &str) -> Self {
        let filename = key.split('/').next_back().unwrap_or(key).to_string();
        Self {
            key: key.to_string(),
            filename,
            created_at: chrono::Utc::now().to_rfc3339(),
            original_filename: None,
            size: None,
            mime_type: None,
            metadata: HashMap::new(),
        }
    }

    /// Create with additional metadata
    pub fn with_metadata(
        key: &str,
        original_filename: Option<&str>,
        size: Option<u64>,
        mime_type: Option<&str>,
    ) -> Self {
        let mut attachment = Self::new(key);
        attachment.original_filename = original_filename.map(|s| s.to_string());
        attachment.size = size;
        attachment.mime_type = mime_type.map(|s| s.to_string());
        attachment
    }

    /// Add custom metadata
    pub fn add_metadata(mut self, key: &str, value: impl Into<serde_json::Value>) -> Self {
        self.metadata.insert(key.to_string(), value.into());
        self
    }

    /// Get the full URL for this file attachment using the global URL generator
    ///
    /// This uses the global file URL generator configured via `TideConfig`.
    /// For model-specific URL generation, use the model's `generate_file_url` method.
    ///
    /// # Arguments
    /// * `field_name` - The name of the attachment field (e.g., "thumbnail", "avatar")
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let attachment = FileAttachment::new("uploads/2024/image.jpg");
    /// let url = attachment.url("thumbnail");
    /// // Returns: "https://cdn.example.com/uploads/2024/image.jpg"
    /// ```
    #[inline]
    pub fn url(&self, field_name: &str) -> String {
        crate::config::Config::generate_file_url(field_name, self)
    }

    /// Get the full URL for this file attachment using a specific URL generator
    ///
    /// # Arguments
    /// * `field_name` - The name of the attachment field (e.g., "thumbnail", "avatar")
    /// * `generator` - Custom URL generator function
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let attachment = FileAttachment::with_metadata(
    ///     "uploads/2024/image.jpg",
    ///     None,
    ///     Some(1024),
    ///     Some("image/jpeg"),
    /// );
    /// let url = attachment.url_with_generator("thumbnail", |field_name, file| {
    ///     // Generate different URLs based on field name and mime type
    ///     match field_name {
    ///         "thumbnail" => format!("https://images-cdn.example.com/thumb/{}", file.key),
    ///         _ => format!("https://cdn.example.com/{}", file.key),
    ///     }
    /// });
    /// ```
    #[inline]
    pub fn url_with_generator(
        &self,
        field_name: &str,
        generator: crate::config::FileUrlGenerator,
    ) -> String {
        generator(field_name, self)
    }

    /// Convert to JSON value
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::to_value(self).unwrap_or(serde_json::json!({}))
    }
}

/// Trait for models with file attachments
///
/// This trait is automatically implemented for models with file attachment configuration.
/// You can also implement it manually for custom behavior.
pub trait HasAttachments {
    /// Get the list of hasOne file relations
    fn has_one_files() -> Vec<&'static str>;

    /// Get the list of hasMany file relations
    fn has_many_files() -> Vec<&'static str>;

    /// Get all file relation names
    fn all_file_relations() -> Vec<&'static str> {
        let mut relations = Self::has_one_files();
        relations.extend(Self::has_many_files());
        relations
    }

    /// Check if a relation is hasOne
    fn is_has_one_relation(relation: &str) -> bool {
        Self::has_one_files().contains(&relation)
    }

    /// Check if a relation is hasMany
    fn is_has_many_relation(relation: &str) -> bool {
        Self::has_many_files().contains(&relation)
    }

    /// Get the current files data from the model
    fn get_files_data(&self) -> Result<FilesData, AttachmentError>;

    /// Set the files data on the model
    fn set_files_data(&mut self, data: FilesData) -> Result<(), AttachmentError>;

    // =========================================================================
    // ATTACH METHODS
    // =========================================================================

    /// Attach a file to a relation
    ///
    /// For hasOne relations, this replaces any existing attachment.
    /// For hasMany relations, this adds to the existing attachments.
    ///
    /// # Example
    /// ```rust,ignore
    /// // Attach a thumbnail (hasOne)
    /// product.attach("thumbnail", "uploads/thumb.jpg")?;
    ///
    /// // Attach an image (hasMany)
    /// product.attach("images", "uploads/img1.jpg")?;
    /// ```
    fn attach(&mut self, relation: &str, file_key: &str) -> Result<(), AttachmentError> {
        self.attach_with_metadata(relation, FileAttachment::new(file_key))
    }

    /// Attach a file with custom metadata
    ///
    /// # Example
    /// ```rust,ignore
    /// let attachment = FileAttachment::with_metadata(
    ///     "uploads/document.pdf",
    ///     Some("My Document.pdf"),
    ///     Some(1024 * 1024), // 1MB
    ///     Some("application/pdf"),
    /// );
    /// product.attach_with_metadata("documents", attachment)?;
    /// ```
    fn attach_with_metadata(
        &mut self,
        relation: &str,
        attachment: FileAttachment,
    ) -> Result<(), AttachmentError> {
        self.validate_relation(relation)?;

        let mut files = self.get_files_data()?;

        if Self::is_has_one_relation(relation) {
            files.set_one(relation, attachment);
        } else {
            files.add_many(relation, attachment);
        }

        self.set_files_data(files)
    }

    /// Attach multiple files at once (hasMany only)
    ///
    /// # Example
    /// ```rust,ignore
    /// product.attach_many("images", vec!["img1.jpg", "img2.jpg", "img3.jpg"])?;
    /// ```
    fn attach_many(&mut self, relation: &str, file_keys: Vec<&str>) -> Result<(), AttachmentError> {
        if !Self::is_has_many_relation(relation) {
            return Err(AttachmentError::InvalidRelation(format!(
                "'{}' is not a hasMany relation, use attach() instead",
                relation
            )));
        }

        let mut files = self.get_files_data()?;

        for key in file_keys {
            files.add_many(relation, FileAttachment::new(key));
        }

        self.set_files_data(files)
    }

    // =========================================================================
    // DETACH METHODS
    // =========================================================================

    /// Detach a file from a relation
    ///
    /// For hasOne, pass `None` as `file_key` to remove the attachment.
    /// For hasMany, pass `Some(key)` to remove a specific file, or `None` to remove all.
    ///
    /// # Example
    /// ```rust,ignore
    /// // Remove thumbnail (hasOne)
    /// product.detach("thumbnail", None)?;
    ///
    /// // Remove specific image (hasMany)
    /// product.detach("images", Some("uploads/img1.jpg"))?;
    ///
    /// // Remove all images (hasMany)
    /// product.detach("images", None)?;
    /// ```
    fn detach(&mut self, relation: &str, file_key: Option<&str>) -> Result<(), AttachmentError> {
        self.validate_relation(relation)?;

        let mut files = self.get_files_data()?;

        if Self::is_has_one_relation(relation) {
            files.remove_one(relation);
        } else if let Some(key) = file_key {
            files.remove_from_many(relation, key);
        } else {
            files.clear_many(relation);
        }

        self.set_files_data(files)
    }

    /// Detach multiple files at once (hasMany only)
    ///
    /// # Example
    /// ```rust,ignore
    /// product.detach_many("images", vec!["img1.jpg", "img2.jpg"])?;
    /// ```
    fn detach_many(&mut self, relation: &str, file_keys: Vec<&str>) -> Result<(), AttachmentError> {
        if !Self::is_has_many_relation(relation) {
            return Err(AttachmentError::InvalidRelation(format!(
                "'{}' is not a hasMany relation",
                relation
            )));
        }

        let mut files = self.get_files_data()?;

        for key in file_keys {
            files.remove_from_many(relation, key);
        }

        self.set_files_data(files)
    }

    // =========================================================================
    // SYNC METHODS
    // =========================================================================

    /// Sync files for a relation (replace all existing with new ones)
    ///
    /// This is useful when you have a form with file inputs and want to
    /// replace the entire collection.
    ///
    /// # Example
    /// ```rust,ignore
    /// // Replace all images with new ones
    /// product.sync("images", vec!["new1.jpg", "new2.jpg"])?;
    ///
    /// // Clear all images
    /// product.sync("images", vec![])?;
    ///
    /// // Replace thumbnail
    /// product.sync("thumbnail", vec!["new-thumb.jpg"])?;
    /// ```
    fn sync(&mut self, relation: &str, file_keys: Vec<&str>) -> Result<(), AttachmentError> {
        self.validate_relation(relation)?;

        let mut files = self.get_files_data()?;

        if Self::is_has_one_relation(relation) {
            if file_keys.is_empty() {
                files.remove_one(relation);
            } else {
                files.set_one(relation, FileAttachment::new(file_keys[0]));
            }
        } else {
            // Clear and add new ones
            files.clear_many(relation);
            for key in file_keys {
                files.add_many(relation, FileAttachment::new(key));
            }
        }

        self.set_files_data(files)
    }

    /// Sync files with custom metadata
    ///
    /// # Example
    /// ```rust,ignore
    /// let attachments = vec![
    ///     FileAttachment::with_metadata("img1.jpg", Some("Photo 1"), Some(1024), Some("image/jpeg")),
    ///     FileAttachment::with_metadata("img2.jpg", Some("Photo 2"), Some(2048), Some("image/jpeg")),
    /// ];
    /// product.sync_with_metadata("images", attachments)?;
    /// ```
    fn sync_with_metadata(
        &mut self,
        relation: &str,
        attachments: Vec<FileAttachment>,
    ) -> Result<(), AttachmentError> {
        self.validate_relation(relation)?;

        let mut files = self.get_files_data()?;

        if Self::is_has_one_relation(relation) {
            if attachments.is_empty() {
                files.remove_one(relation);
            } else if let Some(first) = attachments.into_iter().next() {
                files.set_one(relation, first);
            }
        } else {
            files.clear_many(relation);
            for attachment in attachments {
                files.add_many(relation, attachment);
            }
        }

        self.set_files_data(files)
    }

    // =========================================================================
    // GETTER METHODS
    // =========================================================================

    /// Get a single file attachment (hasOne)
    ///
    /// # Example
    /// ```rust,ignore
    /// if let Some(thumb) = product.get_file("thumbnail")? {
    ///     println!("Thumbnail: {}", thumb.key);
    /// }
    /// ```
    fn get_file(&self, relation: &str) -> Result<Option<FileAttachment>, AttachmentError> {
        let files = self.get_files_data()?;
        Ok(files.get_one(relation))
    }

    /// Get multiple file attachments (hasMany)
    ///
    /// # Example
    /// ```rust,ignore
    /// let images = product.get_files("images")?;
    /// for img in images {
    ///     println!("Image: {}", img.key);
    /// }
    /// ```
    fn get_files(&self, relation: &str) -> Result<Vec<FileAttachment>, AttachmentError> {
        let files = self.get_files_data()?;
        Ok(files.get_many(relation))
    }

    /// Check if a relation has any files
    fn has_files(&self, relation: &str) -> Result<bool, AttachmentError> {
        let files = self.get_files_data()?;
        Ok(files.has_files(relation))
    }

    /// Count files in a relation
    fn count_files(&self, relation: &str) -> Result<usize, AttachmentError> {
        let files = self.get_files_data()?;
        Ok(files.count_files(relation))
    }

    // =========================================================================
    // HELPER METHODS
    // =========================================================================

    /// Validate that a relation exists
    fn validate_relation(&self, relation: &str) -> Result<(), AttachmentError> {
        if !Self::all_file_relations().contains(&relation) {
            return Err(AttachmentError::InvalidRelation(format!(
                "Unknown file relation: '{}'. Available: {:?}",
                relation,
                Self::all_file_relations()
            )));
        }
        Ok(())
    }
}

/// Container for all file attachments on a model
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FilesData {
    /// Map of relation name to file data
    #[serde(flatten)]
    data: HashMap<String, serde_json::Value>,
}

impl FilesData {
    /// Create empty files data
    pub fn new() -> Self {
        Self {
            data: HashMap::new(),
        }
    }

    /// Create from JSON value
    pub fn from_json(value: &serde_json::Value) -> Self {
        match value {
            serde_json::Value::Object(map) => {
                let data: HashMap<String, serde_json::Value> =
                    map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
                Self { data }
            }
            _ => Self::new(),
        }
    }

    /// Convert to JSON value
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::to_value(&self.data).unwrap_or(serde_json::json!({}))
    }

    /// Set a single file (hasOne)
    pub fn set_one(&mut self, relation: &str, attachment: FileAttachment) {
        self.data.insert(relation.to_string(), attachment.to_json());
    }

    /// Remove a single file (hasOne)
    pub fn remove_one(&mut self, relation: &str) {
        self.data
            .insert(relation.to_string(), serde_json::Value::Null);
    }

    /// Get a single file (hasOne)
    pub fn get_one(&self, relation: &str) -> Option<FileAttachment> {
        self.data
            .get(relation)
            .filter(|v| !v.is_null())
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    /// Add to file array (hasMany)
    pub fn add_many(&mut self, relation: &str, attachment: FileAttachment) {
        let mut array = self.get_many_raw(relation);
        array.push(attachment.to_json());
        self.data
            .insert(relation.to_string(), serde_json::Value::Array(array));
    }

    /// Remove from file array (hasMany)
    pub fn remove_from_many(&mut self, relation: &str, file_key: &str) {
        let array: Vec<serde_json::Value> = self
            .get_many_raw(relation)
            .into_iter()
            .filter(|item| item.get("key").and_then(|k| k.as_str()) != Some(file_key))
            .collect();
        self.data
            .insert(relation.to_string(), serde_json::Value::Array(array));
    }

    /// Clear all files from array (hasMany)
    pub fn clear_many(&mut self, relation: &str) {
        self.data
            .insert(relation.to_string(), serde_json::Value::Array(vec![]));
    }

    /// Get all files from array (hasMany)
    pub fn get_many(&self, relation: &str) -> Vec<FileAttachment> {
        self.get_many_raw(relation)
            .into_iter()
            .filter_map(|v| serde_json::from_value(v).ok())
            .collect()
    }

    fn get_many_raw(&self, relation: &str) -> Vec<serde_json::Value> {
        self.data
            .get(relation)
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default()
    }

    /// Check if relation has files
    pub fn has_files(&self, relation: &str) -> bool {
        match self.data.get(relation) {
            Some(serde_json::Value::Null) => false,
            Some(serde_json::Value::Array(arr)) => !arr.is_empty(),
            Some(serde_json::Value::Object(_)) => true,
            _ => false,
        }
    }

    /// Count files in relation
    pub fn count_files(&self, relation: &str) -> usize {
        match self.data.get(relation) {
            Some(serde_json::Value::Null) => 0,
            Some(serde_json::Value::Array(arr)) => arr.len(),
            Some(serde_json::Value::Object(_)) => 1,
            _ => 0,
        }
    }
}

/// Errors that can occur during attachment operations
#[derive(Debug, Clone)]
pub enum AttachmentError {
    /// Invalid or unknown relation name
    InvalidRelation(String),
    /// Failed to parse files data
    ParseError(String),
    /// Model doesn't support file attachments
    NotSupported,
}

impl std::fmt::Display for AttachmentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AttachmentError::InvalidRelation(msg) => write!(f, "Invalid relation: {}", msg),
            AttachmentError::ParseError(msg) => write!(f, "Parse error: {}", msg),
            AttachmentError::NotSupported => write!(f, "Model does not support file attachments"),
        }
    }
}

impl std::error::Error for AttachmentError {}

impl From<AttachmentError> for crate::Error {
    fn from(err: AttachmentError) -> Self {
        crate::Error::query(err.to_string())
    }
}

#[cfg(test)]
#[path = "testing/attachments_tests.rs"]
mod tests;