docbox-database 0.11.1

Docbox database structures, logic, and migrations
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
use chrono::{DateTime, Utc};
use serde::Serialize;
use sqlx::{postgres::PgQueryResult, prelude::FromRow};
use utoipa::ToSchema;
use uuid::Uuid;

use super::{
    document_box::DocumentBoxScopeRaw,
    folder::FolderId,
    user::{User, UserId},
};
use crate::{
    DbExecutor, DbResult,
    models::{
        document_box::DocumentBoxScopeRawRef,
        shared::{
            CountResult, DocboxInputPair, FolderPathSegment, TotalSizeResult, WithFullPath,
            WithFullPathScope,
        },
    },
};

pub type FileId = Uuid;

#[derive(Debug, Clone, FromRow, Serialize, sqlx::Type, ToSchema)]
#[sqlx(type_name = "docbox_file")]
pub struct File {
    /// Unique identifier for the file
    #[schema(value_type = Uuid)]
    pub id: FileId,
    /// Name of the file
    pub name: String,
    /// Mime type of the file content
    pub mime: String,
    /// Parent folder ID
    #[schema(value_type = Uuid)]
    pub folder_id: FolderId,
    /// Optional parent file ID if the file is a child of
    /// some other file (i.e attachment for an email file)
    #[schema(value_type = Option<Uuid>)]
    pub parent_id: Option<FileId>,
    /// Hash of the file bytes stored in S3
    pub hash: String,
    /// Size of the file in bytes
    pub size: i32,
    /// Whether the file was determined to be encrypted when processing
    pub encrypted: bool,
    /// Whether the file is marked as pinned
    pub pinned: bool,
    /// S3 key pointing to the file
    #[serde(skip)]
    pub file_key: String,
    /// When the file was created
    pub created_at: DateTime<Utc>,
    /// User who created the file
    #[serde(skip)]
    pub created_by: Option<UserId>,
}

impl Eq for File {}

impl PartialEq for File {
    fn eq(&self, other: &Self) -> bool {
        self.id.eq(&other.id)
            && self.name.eq(&other.name)
            && self.mime.eq(&other.mime)
            && self.folder_id.eq(&other.folder_id)
            && self.parent_id.eq(&other.parent_id)
            && self.hash.eq(&other.hash)
            && self.size.eq(&other.size)
            && self.encrypted.eq(&other.encrypted)
            && self.pinned.eq(&other.pinned)
            && self.file_key.eq(&other.file_key)
            && self.created_by.eq(&self.created_by)
            // Reduce precision when checking creation timestamp
            // (Database does not store the full precision)
            && self
                .created_at
                .timestamp_millis()
                .eq(&other.created_at.timestamp_millis())
    }
}

#[derive(Debug, FromRow, Serialize)]
pub struct FileWithScope {
    #[sqlx(flatten)]
    pub file: File,
    pub scope: String,
}

/// File with the resolved creator and last modified data
#[derive(Debug, Clone, FromRow, Serialize, ToSchema)]
pub struct FileWithExtra {
    #[serde(flatten)]
    pub file: File,
    #[schema(nullable, value_type = User)]
    pub created_by: Option<User>,
    #[schema(nullable, value_type = User)]
    pub last_modified_by: Option<User>,
    /// Last time the file was modified
    pub last_modified_at: Option<DateTime<Utc>>,
}

/// File with extra with an additional resolved full path
#[derive(Debug, FromRow, Serialize, ToSchema)]
pub struct ResolvedFileWithExtra {
    #[serde(flatten)]
    #[sqlx(flatten)]
    pub file: FileWithExtra,
    pub full_path: Vec<FolderPathSegment>,
}

#[derive(Debug, Default, Clone)]
pub struct CreateFile {
    /// ID for the file to use
    pub id: FileId,

    /// Optional parent file if the file was created
    /// as the result of another file (i.e. email attachments)
    pub parent_id: Option<FileId>,

    pub name: String,
    pub mime: String,
    pub folder_id: FolderId,
    pub hash: String,
    pub size: i32,
    pub file_key: String,
    pub created_by: Option<UserId>,
    pub created_at: DateTime<Utc>,
    pub encrypted: bool,
}

impl File {
    pub async fn create(
        db: impl DbExecutor<'_>,
        CreateFile {
            id,
            parent_id,
            name,
            mime,
            folder_id,
            hash,
            size,
            file_key,
            created_by,
            created_at,
            encrypted,
        }: CreateFile,
    ) -> DbResult<File> {
        sqlx::query(
            r#"INSERT INTO "docbox_files" (
                    "id", "name", "mime", "folder_id", "hash", "size",
                    "encrypted", "file_key", "created_by", "created_at",
                    "parent_id"
                )
                VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
                "#,
        )
        .bind(id)
        .bind(name.as_str())
        .bind(mime.as_str())
        .bind(folder_id)
        .bind(hash.as_str())
        .bind(size)
        .bind(encrypted)
        .bind(file_key.as_str())
        .bind(created_by.as_ref())
        .bind(created_at)
        .bind(parent_id)
        .execute(db)
        .await?;

        Ok(File {
            id,
            name,
            mime,
            folder_id,
            hash,
            size,
            encrypted,
            file_key,
            created_by,
            created_at,
            parent_id,
            pinned: false,
        })
    }

    pub async fn all(
        db: impl DbExecutor<'_>,
        offset: u64,
        page_size: u64,
    ) -> DbResult<Vec<FileWithScope>> {
        sqlx::query_as(
            r#"
            SELECT
            "file".*,
            "folder"."document_box" AS "scope"
            FROM "docbox_files" "file"
            INNER JOIN "docbox_folders" "folder" ON "file"."folder_id" = "folder"."id"
            ORDER BY "created_at" ASC
            OFFSET $1
            LIMIT $2
        "#,
        )
        .bind(offset as i64)
        .bind(page_size as i64)
        .fetch_all(db)
        .await
    }

    pub async fn move_to_folder(
        mut self,
        db: impl DbExecutor<'_>,
        folder_id: FolderId,
    ) -> DbResult<File> {
        sqlx::query(r#"UPDATE "docbox_files" SET "folder_id" = $1 WHERE "id" = $2"#)
            .bind(folder_id)
            .bind(self.id)
            .execute(db)
            .await?;

        self.folder_id = folder_id;

        Ok(self)
    }

    pub async fn rename(mut self, db: impl DbExecutor<'_>, name: String) -> DbResult<File> {
        sqlx::query(r#"UPDATE "docbox_files" SET "name" = $1 WHERE "id" = $2"#)
            .bind(name.as_str())
            .bind(self.id)
            .execute(db)
            .await?;

        self.name = name;

        Ok(self)
    }

    /// Updates the pinned state of the file
    pub async fn set_pinned(mut self, db: impl DbExecutor<'_>, pinned: bool) -> DbResult<File> {
        sqlx::query(r#"UPDATE "docbox_files" SET "pinned" = $1 WHERE "id" = $2"#)
            .bind(pinned)
            .bind(self.id)
            .execute(db)
            .await?;

        self.pinned = pinned;

        Ok(self)
    }

    /// Updates the encryption state of the file
    pub async fn set_encrypted(
        mut self,
        db: impl DbExecutor<'_>,
        encrypted: bool,
    ) -> DbResult<File> {
        sqlx::query(r#"UPDATE "docbox_files" SET "encrypted" = $1 WHERE "id" = $2"#)
            .bind(encrypted)
            .bind(self.id)
            .execute(db)
            .await?;

        self.encrypted = encrypted;

        Ok(self)
    }

    /// Updates the mime type of a file
    pub async fn set_mime(mut self, db: impl DbExecutor<'_>, mime: String) -> DbResult<File> {
        sqlx::query(r#"UPDATE "docbox_files" SET "mime" = $1 WHERE "id" = $2"#)
            .bind(&mime)
            .bind(self.id)
            .execute(db)
            .await?;

        self.mime = mime;

        Ok(self)
    }

    pub async fn all_by_mime(
        db: impl DbExecutor<'_>,
        mime: &str,
        offset: u64,
        page_size: u64,
    ) -> DbResult<Vec<FileWithScope>> {
        sqlx::query_as(
            r#"
            SELECT
            "file".*,
            "folder"."document_box" AS "scope"
            FROM "docbox_files" "file"
            INNER JOIN "docbox_folders" "folder" ON "file"."folder_id" = "folder"."id"
            WHERE "file"."mime" = $1
            ORDER BY "created_at" ASC
            OFFSET $2
            LIMIT $3
        "#,
        )
        .bind(mime)
        .bind(offset as i64)
        .bind(page_size as i64)
        .fetch_all(db)
        .await
    }

    pub async fn all_by_mimes(
        db: impl DbExecutor<'_>,
        mimes: &[&str],
        offset: u64,
        page_size: u64,
    ) -> DbResult<Vec<FileWithScope>> {
        sqlx::query_as(
            r#"
            SELECT
                "file".*,
                "folder"."document_box" AS "scope"
            FROM "docbox_files" AS "file"
            INNER JOIN "docbox_folders" "folder" ON "file"."folder_id" = "folder"."id"
            WHERE "mime" = ANY($1) AND "file"."encrypted" = FALSE
            ORDER BY "file"."created_at" ASC
            OFFSET $2
            LIMIT $3
        "#,
        )
        .bind(mimes)
        .bind(offset as i64)
        .bind(page_size as i64)
        .fetch_all(db)
        .await
    }

    /// Finds a specific file using its full path scope -> folder -> file
    pub async fn find(
        db: impl DbExecutor<'_>,
        scope: &DocumentBoxScopeRaw,
        file_id: FileId,
    ) -> DbResult<Option<File>> {
        sqlx::query_as(
            r#"
            SELECT "file".*
            FROM "docbox_files" AS "file"
            INNER JOIN "docbox_folders" "folder" ON "file"."folder_id" = "folder"."id"
            WHERE "file"."id" = $1 AND "folder"."document_box" = $2
        "#,
        )
        .bind(file_id)
        .bind(scope)
        .fetch_optional(db)
        .await
    }

    /// Collects the IDs and names of all parent folders of the
    /// provided folder
    pub async fn resolve_path(
        db: impl DbExecutor<'_>,
        file_id: FileId,
    ) -> DbResult<Vec<FolderPathSegment>> {
        sqlx::query_as(r#"SELECT "id", "name" FROM resolve_file_path($1)"#)
            .bind(file_id)
            .fetch_all(db)
            .await
    }

    pub async fn find_by_parent(
        db: impl DbExecutor<'_>,
        parent_id: FolderId,
    ) -> DbResult<Vec<File>> {
        sqlx::query_as(r#"SELECT * FROM "docbox_files" WHERE "folder_id" = $1"#)
            .bind(parent_id)
            .fetch_all(db)
            .await
    }

    /// Deletes the file
    pub async fn delete(&self, db: impl DbExecutor<'_>) -> DbResult<PgQueryResult> {
        sqlx::query(r#"DELETE FROM "docbox_files" WHERE "id" = $1"#)
            .bind(self.id)
            .execute(db)
            .await
    }

    /// Finds a collection of files that are all within the same document box, resolves
    /// both the files themselves and the folder path to traverse to get to each file
    pub async fn resolve_with_extra(
        db: impl DbExecutor<'_>,
        scope: &DocumentBoxScopeRaw,
        file_ids: Vec<Uuid>,
    ) -> DbResult<Vec<WithFullPath<FileWithExtra>>> {
        if file_ids.is_empty() {
            return Ok(Vec::new());
        }

        sqlx::query_as(r#"SELECT * FROM resolve_files_with_extra($1, $2)"#)
            .bind(scope)
            .bind(file_ids)
            .fetch_all(db)
            .await
    }

    /// Finds a collection of files that are within various document box scopes, resolves
    /// both the files themselves and the folder path to traverse to get to each file
    pub async fn resolve_with_extra_mixed_scopes(
        db: impl DbExecutor<'_>,
        files_scope_with_id: Vec<DocboxInputPair<'_>>,
    ) -> DbResult<Vec<WithFullPathScope<FileWithExtra>>> {
        if files_scope_with_id.is_empty() {
            return Ok(Vec::new());
        }

        sqlx::query_as(
            r#"SELECT * FROM resolve_files_with_extra_mixed_scopes($1::docbox_input_pair[])"#,
        )
        .bind(files_scope_with_id)
        .fetch_all(db)
        .await
    }

    /// Finds a specific file using its full path scope -> folder -> file
    /// fetching the additional details about the file like the creator and
    /// last modified
    pub async fn find_with_extra(
        db: impl DbExecutor<'_>,
        scope: &DocumentBoxScopeRaw,
        file_id: FileId,
    ) -> DbResult<Option<FileWithExtra>> {
        sqlx::query_as(r#"SELECT * FROM resolve_file_by_id_with_extra($1, $2)"#)
            .bind(scope)
            .bind(file_id)
            .fetch_optional(db)
            .await
    }

    pub async fn find_by_parent_folder_with_extra(
        db: impl DbExecutor<'_>,
        parent_id: FolderId,
    ) -> DbResult<Vec<FileWithExtra>> {
        sqlx::query_as(r#"SELECT * FROM resolve_files_by_parent_folder_with_extra($1)"#)
            .bind(parent_id)
            .fetch_all(db)
            .await
    }

    pub async fn find_by_parent_file_with_extra(
        db: impl DbExecutor<'_>,
        parent_id: FileId,
    ) -> DbResult<Vec<FileWithExtra>> {
        sqlx::query_as(r#"SELECT * FROM resolve_files_by_parent_file_with_extra($1)"#)
            .bind(parent_id)
            .fetch_all(db)
            .await
    }

    /// Get the total number of files in the tenant
    pub async fn total_count(db: impl DbExecutor<'_>) -> DbResult<i64> {
        let count_result: CountResult =
            sqlx::query_as(r#"SELECT COUNT(*) AS "count" FROM "docbox_files""#)
                .fetch_one(db)
                .await?;

        Ok(count_result.count)
    }

    /// Get the total "size" of files within the current tenant, this does not include
    /// the size of generated files
    pub async fn total_size(db: impl DbExecutor<'_>) -> DbResult<i64> {
        let size_result: TotalSizeResult = sqlx::query_as(
            r#"
            SELECT COALESCE(SUM("file"."size"), 0) AS "total_size"
            FROM "docbox_files" "file";
        "#,
        )
        .fetch_one(db)
        .await?;

        Ok(size_result.total_size)
    }

    /// Get the total "size" of files within a specific scope, this does not include
    /// the size of generated files
    pub async fn total_size_within_scope(
        db: impl DbExecutor<'_>,
        scope: DocumentBoxScopeRawRef<'_>,
    ) -> DbResult<i64> {
        let size_result: TotalSizeResult = sqlx::query_as(
            r#"
            SELECT COALESCE(SUM("file"."size"), 0) AS "total_size"
            FROM "docbox_files" "file"
            INNER JOIN "docbox_folders" "folder" ON "file"."folder_id" = "folder"."id"
            WHERE "folder"."document_box" = $1;
        "#,
        )
        .bind(scope)
        .fetch_one(db)
        .await?;

        Ok(size_result.total_size)
    }
}