bytecon_data_store 0.1.0

A library for storing ByteConverter implementations conveniently.
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
use std::{error::Error, fs::File, io::{Read, Write}, path::{Path, PathBuf}, sync::{Arc, Mutex}};
use crate::DataStore;
use bytecon::ByteConverter;
use futures::future::join_all;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use rusqlite::{named_params, Connection};

pub struct DirectoryDataStore {
    sqlite_file_path: PathBuf,
    storage_directory_path: PathBuf,
    random: Arc<Mutex<ChaCha8Rng>>,
    cache_filename_length: usize,
}

impl DirectoryDataStore {
    pub fn new(sqlite_file_path: PathBuf, cache_filename_length: usize) -> Result<Self, DirectoryDataStoreError> {

        let storage_directory_path = {
            sqlite_file_path.parent()
                .ok_or_else(|| {
                    DirectoryDataStoreError::UnableToConstructStorageDirectoryPath {
                        sqlite_file_path: sqlite_file_path.clone(),
                    }
                })?
                .append("cache")
        };

        Ok(Self {
            sqlite_file_path,
            storage_directory_path,
            random: Arc::new(Mutex::new(ChaCha8Rng::from_entropy())),
            cache_filename_length,
        })
    }
    fn generate_random_filename(&self) -> Result<String, Box<dyn Error>> {
        let locked_random_result = self.random.lock();
        let mut locked_random = locked_random_result
            .map_err(|_| {
                DirectoryDataStoreError::FailedToLockMutex
            })?;
        Ok(locked_random.gen_filename(self.cache_filename_length))
    }
    fn generate_random_value<T>(&self) -> Result<T, DirectoryDataStoreError>
    where rand::distributions::Standard: rand::prelude::Distribution<T>
    {
        let locked_random_result = self.random.lock();
        let mut locked_random = locked_random_result
            .map_err(|_| {
                DirectoryDataStoreError::FailedToLockMutex
            })?;
        Ok(locked_random.gen())
    }
}

impl DataStore for DirectoryDataStore {
    type Item = Vec<u8>;
    type Key = i64;

    async fn initialize(&mut self) -> Result<(), Box<dyn Error>> {
        let connection = Connection::open(&self.sqlite_file_path)
            .map_err(|error| {
                DirectoryDataStoreError::UnableToConnectToSqlitePath {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        connection.execute("
            CREATE TABLE IF NOT EXISTS file_record
            (
                file_record_id INTEGER PRIMARY KEY AUTOINCREMENT
                , file_path TEXT
                , bytes_length INTEGER
            );
        ", [])
            .map_err(|error| {
                DirectoryDataStoreError::UnableToCreateTablesWhenConstructingFreshStart {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        connection.close()
            .map_err(|(_, error)| {
                DirectoryDataStoreError::FailedToCloseSqliteConnection {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;
        
        if !self.storage_directory_path.exists() {
            std::fs::create_dir_all(&self.storage_directory_path)
                .map_err(|error| {
                    DirectoryDataStoreError::FailedToCreateCacheDirectory {
                        cache_directory_path: self.storage_directory_path.clone(),
                        error,
                    }
                })?;
        }

        Ok(())
    }
    async fn insert(&mut self, item: Self::Item) -> Result<Self::Key, Box<dyn Error>> {
        let random_file_name = self.generate_random_filename()?;
        let random_file_path = self.storage_directory_path.append(random_file_name);

        if random_file_path.exists() {
            return Err(Box::new(DirectoryDataStoreError::RandomFilePathAlreadyExists {
                random_file_path: random_file_path.clone(),
                sqlite_file_path: self.sqlite_file_path.clone(),
            }));
        }
        
        let mut random_file = File::create(random_file_path.clone())
            .map_err(|error| {
                DirectoryDataStoreError::FailedToCreateRandomFile {
                    random_file_path: random_file_path.clone(),
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        let connection = Connection::open(&self.sqlite_file_path)
            .map_err(|error| {
                DirectoryDataStoreError::UnableToConnectToSqlitePath {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        connection.execute("
            INSERT INTO file_record
            (
                file_path
                , bytes_length
            )
            VALUES
            (
                :file_path
                , :bytes_length
            );
        ", named_params! {
            ":file_path": random_file_path.as_os_str().to_str(),
            ":bytes_length": item.len(),
        })
            .map_err(|error| {
                DirectoryDataStoreError::FailedToInsertFileRecord {
                    random_file_path: random_file_path.clone(),
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        let file_record_id = connection.last_insert_rowid();

        connection.close()
            .map_err(|(_, error)| {
                DirectoryDataStoreError::FailedToCloseSqliteConnection {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        random_file.write_all(&item)
            .map_err(|error| {
                DirectoryDataStoreError::FailedToWriteBytesToFile {
                    bytes_length: item.len(),
                    random_file_path: random_file_path.clone(),
                    error,
                }
            })?;

        Ok(file_record_id)
    }
    async fn get(&self, id: &Self::Key) -> Result<Self::Item, Box<dyn Error>> {
        
        let connection = Connection::open(&self.sqlite_file_path)
            .map_err(|error| {
                DirectoryDataStoreError::UnableToConnectToSqlitePath {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        let mut statement = connection.prepare("
            SELECT
                file_path
                , bytes_length
            FROM file_record
            WHERE
                file_record_id = :file_record_id;
        ")
            .map_err(|error| {
                DirectoryDataStoreError::FailedToConstructStatement {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        let (file_path, bytes_length) = statement.query_row(named_params! {
            ":file_record_id": *id,
        }, |row| {
            let file_path: String = row.get(0)?;
            let bytes_length: usize = row.get(1)?;
            Ok((
                file_path,
                bytes_length,
            ))
        })
            .map_err(|error| {
                DirectoryDataStoreError::FailedToPullBackFileRecord {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    id: *id,
                    error,
                }
            })?;
        
        let bytes = {
            let mut bytes: Vec<u8> = Vec::with_capacity(bytes_length);
            let mut file = File::open(&file_path)
                .map_err(|error| {
                    DirectoryDataStoreError::FailedToOpenCachedFileRecord {
                        cached_file_path: file_path.clone(),
                        error,
                    }
                })?;
            file.read_to_end(&mut bytes)
                .map_err(|error| {
                    DirectoryDataStoreError::FailedToReadFromCachedFile {
                        cached_file_path: file_path.clone(),
                        error,
                    }
                })?;
            bytes
        };

        Ok(bytes)
    }
    async fn delete(&self, id: &Self::Key) -> Result<(), Box<dyn Error>> {
        
        let mut connection = Connection::open(&self.sqlite_file_path)
            .map_err(|error| {
                DirectoryDataStoreError::UnableToConnectToSqlitePath {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        let transaction = connection.transaction()
            .map_err(|error| {
                DirectoryDataStoreError::UnableToCreateTransaction {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        let mut statement = transaction.prepare("
            SELECT
                file_path
            FROM file_record
            WHERE
                file_record_id = :file_record_id;
        ")
            .map_err(|error| {
                DirectoryDataStoreError::FailedToConstructStatement {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        let file_path = statement.query_row(named_params! {
            ":file_record_id": *id,
        }, |row| {
            let file_path: String = row.get(0)?;
            Ok(file_path)
        })
            .map_err(|error| {
                DirectoryDataStoreError::FailedToPullBackFileRecord {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    id: *id,
                    error,
                }
            })?;
        
        let path = Path::new(&file_path);
        if path.exists() {
            std::fs::remove_file(path)
                .map_err(|error| {
                    DirectoryDataStoreError::FailedToDeleteFileAtPath {
                        file_path: file_path.into(),
                        error,
                    }
                })?;
        }

        transaction.execute("
            DELETE FROM file_record
            WHERE
                file_record_id = :file_record_id;
        ", named_params! {
            ":file_record_id": *id,
        })
            .map_err(|error| {
                DirectoryDataStoreError::FailedToDeleteFileRecord {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    id: *id,
                    error,
                }
            })?;

        Ok(())
    }
    async fn list(&self, page_index: u64, page_size: u64, row_offset: u64) -> Result<Vec<Self::Key>, Box<dyn Error>> {
        
        let connection = Connection::open(&self.sqlite_file_path)
            .map_err(|error| {
                DirectoryDataStoreError::UnableToConnectToSqlitePath {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        let mut statement = connection.prepare("
            SELECT
                file_record_id
            FROM file_record
            ORDER BY
                file_record_id
            LIMIT :limit
            OFFSET :offset;
        ")
            .map_err(|error| {
                DirectoryDataStoreError::FailedToConstructStatement {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;

        let offset = page_index * page_size + row_offset;
        let file_record_id_results: Vec<Result<i64, rusqlite::Error>> = statement.query_map(named_params! {
            ":limit": page_size,
            ":offset": offset,
        }, |row| {
            let file_record_id: i64 = row.get(0)?;
            Ok(file_record_id)
        })
            .map_err(|error| {
                DirectoryDataStoreError::FailedToPullBackFileRecordList {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    page_size,
                    page_index,
                    row_offset,
                    error,
                }
            })?
            .collect();

        let mut file_record_ids = Vec::with_capacity(file_record_id_results.len());
        for file_record_id_result in file_record_id_results {
            let file_record_id = file_record_id_result?;
            file_record_ids.push(file_record_id);
        }
        
        Ok(file_record_ids)
    }
    async fn bulk_insert(&mut self, items: Vec<Self::Item>) -> Result<Vec<Self::Key>, Box<dyn Error>> {
        let mut file_paths = Vec::with_capacity(items.len());
        for _ in 0..items.len() {
            let random_file_name = self.generate_random_filename()?;
            let random_file_path = self.storage_directory_path.append(random_file_name);

            if random_file_path.exists() {
                return Err(Box::new(DirectoryDataStoreError::RandomFilePathAlreadyExists {
                    random_file_path: random_file_path.clone(),
                    sqlite_file_path: self.sqlite_file_path.clone(),
                }));
            }

            file_paths.push(random_file_path);
        }

        let mut files = Vec::with_capacity(file_paths.len());
        for file_path in file_paths.iter() {
            let random_file = File::create(file_path.clone())
                .map_err(|error| {
                    DirectoryDataStoreError::FailedToCreateRandomFile {
                        random_file_path: file_path.clone(),
                        sqlite_file_path: self.sqlite_file_path.clone(),
                        error,
                    }
                })?;
            files.push(random_file);
        }

        let mut connection = Connection::open(&self.sqlite_file_path)
            .map_err(|error| {
                DirectoryDataStoreError::UnableToConnectToSqlitePath {
                    sqlite_file_path: self.sqlite_file_path.clone(),
                    error,
                }
            })?;
        let transaction = connection.transaction()?;

        let file_record_ids = {
            let mut statement = transaction.prepare("
                INSERT INTO file_record
                (
                    file_path
                    , bytes_length
                )
                VALUES
                (
                    :file_path
                    , :bytes_length
                );
            ")?;

            let mut file_record_ids = Vec::with_capacity(file_paths.len());
            for (file_path, item_length) in file_paths.iter().zip(items.iter().map(|item| item.len())) {
                statement.execute(named_params! {
                    ":file_path": file_path.as_os_str().to_str(),
                    ":bytes_length": item_length,
                })
                    .map_err(|error| {
                        DirectoryDataStoreError::FailedToInsertFileRecord {
                            random_file_path: file_path.clone(),
                            sqlite_file_path: self.sqlite_file_path.clone(),
                            error,
                        }
                    })?;

                let file_record_id = transaction.last_insert_rowid();
                file_record_ids.push(file_record_id);
            }
            file_record_ids
        };

        transaction.commit()?;

        for (mut file, (file_path, item)) in files.into_iter().zip(file_paths.into_iter().zip(items.into_iter())) {
            file.write_all(&item)
                .map_err(|error| {
                    DirectoryDataStoreError::FailedToWriteBytesToFile {
                        bytes_length: item.len(),
                        random_file_path: file_path.clone(),
                        error,
                    }
                })?;
        }

        Ok(file_record_ids)
    }
    async fn bulk_get(&self, ids: &Vec<Self::Key>) -> Result<Vec<Self::Item>, Box<dyn Error>> {
        if ids.is_empty() {
            return Ok(Vec::new());
        }

        // perform database interactions
        let items = {
            let mut connection = Connection::open(&self.sqlite_file_path)
                .map_err(|error| {
                    DirectoryDataStoreError::UnableToConnectToSqlitePath {
                        sqlite_file_path: self.sqlite_file_path.clone(),
                        error,
                    }
                })?;

            let transaction = connection.transaction()?;

            // create temp table
            let temp_table_name = {
                let temp_table_name = {
                    let random_number: u128 = self.generate_random_value()?;
                    String::from(format!("temp_ids_{}", random_number))
                };
                transaction.execute(&format!("
                    CREATE TEMP TABLE {}
                    (
                        id INTEGER PRIMARY KEY AUTOINCREMENT
                        , file_record_id INTEGER
                    );
                ", temp_table_name), [])?;
                temp_table_name
            };

            // insert ids into temp table
            {
                let mut statement = transaction.prepare(&format!("
                    INSERT INTO {}
                    (
                        file_record_id
                    )
                    VALUES
                    (
                        :file_record_id
                    );
                ", temp_table_name))?;
                for id in ids {
                    statement.execute(named_params! {
                        ":file_record_id": id,
                    })?;
                }
            }

            // select from primary table
            let items = {
                let mut statement = transaction.prepare(&format!("
                    SELECT
                        file_path
                        , bytes_length
                    FROM file_record fr
                    JOIN {} ti
                    ON
                        ti.file_record_id = fr.file_record_id
                    ORDER BY
                        ti.id;
                ", temp_table_name))?;
                let items = statement.query_map([], |row| {
                    let file_path: String = row.get(0)?;
                    let bytes_length: usize = row.get(1)?;
                    Ok((
                        file_path,
                        bytes_length,
                    ))
                })?
                .collect::<Result<Vec<_>, _>>()?;
                items
            };

            // drop the temp table
            {
                transaction.execute(&format!("
                    DROP TABLE {};
                ", temp_table_name), [])?;
            }

            items
        };

        // read the bytes from the files
        let bytes_collections: Vec<Vec<u8>> = {
            let futures = items.into_iter().enumerate()
                .map(|(index, (file_path, bytes_length))| {
                    async move {
                        let mut bytes: Vec<u8> = Vec::with_capacity(bytes_length);
                        let mut file = File::open(&file_path)
                            .map_err(|error| {
                                DirectoryDataStoreError::FailedToOpenCachedFileRecord {
                                    cached_file_path: file_path.clone(),
                                    error,
                                }
                            })?;
                        file.read_to_end(&mut bytes)
                            .map_err(|error| {
                                DirectoryDataStoreError::FailedToReadFromCachedFile {
                                    cached_file_path: file_path.clone(),
                                    error,
                                }
                            })?;
                        Ok((index, bytes))
                    }
                })
                .collect::<Vec<_>>();

            let joined_futures: Vec<Result<(usize, Vec<u8>), DirectoryDataStoreError>> = join_all(futures)
                .await;
            let mut bytes_collections = Vec::with_capacity(joined_futures.len());
            for joined_future in joined_futures {
                let bytes = joined_future?;
                bytes_collections.push(bytes);
            }
            bytes_collections.sort_by_key(|(index, _)| *index);
            bytes_collections.into_iter()
                .map(|(_, bytes)| {
                    bytes
                })
                .collect()
        };

        Ok(bytes_collections)
    }
}

impl ByteConverter for DirectoryDataStore {
    fn append_to_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), Box<dyn Error>> {
        self.sqlite_file_path.append_to_bytes(bytes)?;
        self.storage_directory_path.append_to_bytes(bytes)?;
        self.random.lock()
            .map_err(|_| {
                DirectoryDataStoreError::FailedToLockMutex
            })?
            .append_to_bytes(bytes)?;
        self.cache_filename_length.append_to_bytes(bytes)?;
        Ok(())
    }
    fn extract_from_bytes(bytes: &Vec<u8>, index: &mut usize) -> Result<Self, Box<dyn Error>> where Self: Sized {
        Ok(Self {
            sqlite_file_path: PathBuf::extract_from_bytes(bytes, index)?,
            storage_directory_path: PathBuf::extract_from_bytes(bytes, index)?,
            random: Arc::new(Mutex::new(ChaCha8Rng::extract_from_bytes(bytes, index)?)),
            cache_filename_length: usize::extract_from_bytes(bytes, index)?,
        })
    }
}

trait Appendable<T: AsRef<Path>> {
    fn append(&self, appended: T) -> PathBuf;
}

impl<T: AsRef<Path>> Appendable<T> for &std::path::Path {
    fn append(&self, appended: T) -> PathBuf {
        self.join(appended)
    }
}

impl<T: AsRef<Path>> Appendable<T> for PathBuf {
    fn append(&self, appended: T) -> PathBuf {
        self.join(appended)
    }
}

impl<T: AsRef<Path>> Appendable<T> for &PathBuf {
    fn append(&self, appended: T) -> PathBuf {
        self.join(appended)
    }
}

trait RandomFilenameGenerator {
    fn gen_filename(&mut self, length: usize) -> String;
}

impl RandomFilenameGenerator for rand::rngs::StdRng {
    fn gen_filename(&mut self, length: usize) -> String {
        self.sample_iter(&rand::distributions::Alphanumeric)
            .take(length)
            .map(char::from)
            .collect()
    }
}

impl RandomFilenameGenerator for ChaCha8Rng {
    fn gen_filename(&mut self, length: usize) -> String {
        self.sample_iter(&rand::distributions::Alphanumeric)
            .take(length)
            .map(char::from)
            .collect()
    }
}

#[derive(thiserror::Error, Debug)]
pub enum DirectoryDataStoreError {
    #[error("Unable to create connection to Sqlite path at {sqlite_file_path} with error {error}.")]
    UnableToConnectToSqlitePath {
        sqlite_file_path: PathBuf,
        error: rusqlite::Error,
    },
    #[error("Unable to create tables when constructing fresh start at {sqlite_file_path} with error {error}.")]
    UnableToCreateTablesWhenConstructingFreshStart {
        sqlite_file_path: PathBuf,
        error: rusqlite::Error,
    },
    #[error("Unable to construct storage directory path from Sqlite path {sqlite_file_path}.")]
    UnableToConstructStorageDirectoryPath {
        sqlite_file_path: PathBuf,
    },
    #[error("Random file path already exists at {random_file_path} with Sqlite path at {sqlite_file_path}.")]
    RandomFilePathAlreadyExists {
        random_file_path: PathBuf,
        sqlite_file_path: PathBuf,
    },
    #[error("Failed to create random file at {random_file_path} with Sqlite path at {sqlite_file_path} with error {error}.")]
    FailedToCreateRandomFile {
        random_file_path: PathBuf,
        sqlite_file_path: PathBuf,
        error: std::io::Error,
    },
    #[error("Failed to insert file record at {random_file_path} with Sqlite path at {sqlite_file_path} with error {error}.")]
    FailedToInsertFileRecord {
        random_file_path: PathBuf,
        sqlite_file_path: PathBuf,
        error: rusqlite::Error,
    },
    #[error("Failed to close Sqlite connection to {sqlite_file_path} with error {error}")]
    FailedToCloseSqliteConnection {
        sqlite_file_path: PathBuf,
        error: rusqlite::Error,
    },
    #[error("Failed to write {bytes_length} bytes to file {random_file_path}.")]
    FailedToWriteBytesToFile {
        bytes_length: usize,
        random_file_path: PathBuf,
        error: std::io::Error,
    },
    #[error("Failed to construct rusqlite Statement instance for {sqlite_file_path} with error {error}.")]
    FailedToConstructStatement {
        sqlite_file_path: PathBuf,
        error: rusqlite::Error,
    },
    #[error("Failed to pull back file_record row from Statement for {sqlite_file_path} for ID {id} with error {error}.")]
    FailedToPullBackFileRecord {
        sqlite_file_path: PathBuf,
        id: i64,
        error: rusqlite::Error,
    },
    #[error("Failed to open cached file at {cached_file_path} with error {error}.")]
    FailedToOpenCachedFileRecord {
        cached_file_path: String,
        error: std::io::Error,
    },
    #[error("Failed to read from cached file at {cached_file_path} with error {error}.")]
    FailedToReadFromCachedFile {
        cached_file_path: String,
        error: std::io::Error,
    },
    #[error("Failed to create cache directory at {cache_directory_path} with error {error}.")]
    FailedToCreateCacheDirectory {
        cache_directory_path: PathBuf,
        error: std::io::Error,
    },
    #[error("Failed to delete file_record row for {sqlite_file_path} with ID {id} with error {error}.")]
    FailedToDeleteFileRecord {
        sqlite_file_path: PathBuf,
        id: i64,
        error: rusqlite::Error,
    },
    #[error("Unable to create transaction from Sqlite connection for {sqlite_file_path} with error {error}.")]
    UnableToCreateTransaction {
        sqlite_file_path: PathBuf,
        error: rusqlite::Error,
    },
    #[error("Failed to delete file based on file_record path {file_path} with error {error}.")]
    FailedToDeleteFileAtPath {
        file_path: PathBuf,
        error: std::io::Error,
    },
    #[error("Failed to pull back file_record rows from list Statement for {sqlite_file_path} for page size {page_size}, page index {page_index}, and row offset {row_offset} with error {error}.")]
    FailedToPullBackFileRecordList {
        sqlite_file_path: PathBuf,
        page_size: u64,
        page_index: u64,
        row_offset: u64,
        error: rusqlite::Error,
    },
    #[error("Failed to lock mutex.")]
    FailedToLockMutex,
}