tauri-plugin-persistence 0.2.0

A wrapper plugin for several persistence backends, focused on managing complex project folders with less boilerplate.
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
use std::{borrow::Borrow, collections::HashMap, marker::PhantomData, ops::Deref, path::PathBuf, str::FromStr, sync::Arc};

use bson::Document;
use polodb_core::{options::UpdateOptions, results::{DeleteResult, InsertManyResult, InsertOneResult, UpdateResult}, CollectionT, IndexModel};
use serde::{de::DeserializeOwned, Serialize};
use tauri::{AppHandle, Manager, Runtime};
use tokio::{fs::{File, OpenOptions}, sync::Mutex};

use super::{state::{ContextDB, ContextFileHandle, ContextState, FileHandleMode, PluginState}, types::{PathInformation, PathMetadata}};

pub struct Context<R: Runtime> {
    handle: Arc<AppHandle<R>>,
    name: String,
    path: String,
}

impl<R: Runtime> Clone for Context<R> {
    fn clone(&self) -> Self {
        Self {
            handle: self.handle.clone(),
            name: self.name.clone(),
            path: self.path.clone(),
        }
    }
}

impl<R: Runtime> Context<R> {
    pub(crate) fn create(handle: AppHandle<R>, name: String, path: String) -> Self {
        Self {
            handle: Arc::new(handle),
            name,
            path,
        }
    }

    pub fn name(&self) -> String {
        self.name.clone()
    }

    pub fn path(&self) -> String {
        self.path.clone()
    }

    pub(crate) fn handle(&self) -> AppHandle<R> {
        self.handle.clone().deref().clone()
    }

    pub fn base_path(&self) -> PathBuf {
        PathBuf::from_str(&self.path()).unwrap()
    }

    pub fn get_path(&self, path: impl AsRef<str>) -> crate::Result<PathBuf> {
        let resolved = PathBuf::from_str(path.as_ref()).unwrap();
        if resolved.is_absolute() {
            return Err(crate::Error::no_absolute_path(path.as_ref()));
        }
        let joined = self
            .base_path()
            .canonicalize().or(Err(crate::Error::invalid_path(path.as_ref())))?
            .join(&resolved);

        if !joined.starts_with(self.base_path_canonicalized()?) {
            return Err(crate::Error::path_escapes_context(path.as_ref()));
        }

        Ok(joined)
    }

    pub fn base_path_canonicalized(&self) -> crate::Result<PathBuf> {
        PathBuf::from_str(&self.path()).unwrap().canonicalize().or_else(|_| Err(crate::Error::invalid_path(self.path())))
    }

    pub async fn create_directory(&self, path: impl AsRef<str>, parents: bool) -> crate::Result<()> {
        let resolved = self.get_path(path)?;
        let create_result = if parents {tokio::fs::create_dir_all(&resolved).await} else {tokio::fs::create_dir(&resolved).await};
        if let Err(error) = create_result {
            return Err(crate::Error::filesystem("CREATE_DIRECTORY", error.to_string()));
        }

        Ok(())
    }

    pub async fn remove_directory(&self, path: impl AsRef<str>) -> crate::Result<()> {
        let resolved = self.get_path(path)?;
        if !resolved.is_dir() {
            return Err(crate::Error::filesystem("REMOVE_DIRECTORY", "Specified path is not a directory or does not exist."));
        }
        tokio::fs::remove_dir_all(resolved).await.or_else(|error| Err(crate::Error::filesystem("REMOVE_DIRECTORY", error.to_string())))?;
        Ok(())
    }

    pub async fn remove_file(&self, path: impl AsRef<str>) -> crate::Result<()> {
        let resolved = self.get_path(path)?;
        if !resolved.is_file() {
            return Err(crate::Error::filesystem("REMOVE_FILE", "Specified path is not a file or does not exist."));
        }
        tokio::fs::remove_file(resolved).await.or_else(|error| Err(crate::Error::filesystem("REMOVE_FILE", error.to_string())))?;
        Ok(())
    }

    pub async fn file_metadata(&self, path: impl AsRef<str>) -> crate::Result<PathMetadata> {
        let resolved = self.get_path(path)?;
        match tokio::fs::metadata(resolved).await {
            Ok(meta) => Ok(PathMetadata::from(meta)),
            Err(e) => Err(crate::Error::filesystem("FILE_METADATA", e.to_string()))
        }
    }

    pub async fn list_directory(&self, path: impl AsRef<str>) -> crate::Result<Vec<PathInformation>> {
        let resolved = self.get_path(path)?;
        if !resolved.is_dir() {
            return Err(crate::Error::filesystem("LIST_DIRECTORY", "Specified path is not a directory or does not exist."));
        }

        match tokio::fs::read_dir(resolved).await {
            Ok(mut results) => {
                let mut infos: Vec<PathInformation> = Vec::new();
                while let Ok(Some(info)) = results.next_entry().await {
                    infos.push(PathInformation::from(info));
                }

                Ok(infos)
            },
            Err(e) => Err(crate::Error::filesystem("LIST_DIRECTORY", e.to_string()))
        }
    }

    pub(crate) async fn state(&self) -> ContextState {
        self.handle()
            .state::<PluginState>()
            .lock()
            .await
            .get(&self.name())
            .expect("Context not initialized.")
            .clone()
    }

    pub(crate) async fn databases(&self) -> Arc<Mutex<HashMap<String, ContextDB>>> {
        self.state().await.databases.clone()
    }

    pub(crate) async fn files(&self) -> Arc<Mutex<HashMap<bson::Uuid, ContextFileHandle>>> {
        self.state().await.files.clone()
    }

    pub async fn open_database(
        &self,
        name: impl AsRef<str>,
        path: impl AsRef<str>,
    ) -> crate::Result<Database<R>> {
        let _dbs = self.databases().await;
        let mut dbs = _dbs.lock().await;
        let resolved_path = self.get_path(path.as_ref())?;
        if let Some(db) = dbs.get(&name.as_ref().to_string()) {
            if db.path == path.as_ref().to_string() {
                Ok(Database::<R>::create(
                    self.clone(),
                    name.as_ref().to_string(),
                    path.as_ref().to_string(),
                ))
            } else {
                Err(crate::Error::open_database(
                    name.as_ref(),
                    self.name(),
                    path.as_ref(),
                    "Database is already open at another path.",
                ))
            }
        } else {
            if resolved_path.exists() {
                if resolved_path.is_file() {
                    let database =
                        polodb_core::Database::open_path(resolved_path).or_else(|e| {
                            Err(crate::Error::open_database(
                                name.as_ref(),
                                self.name(),
                                path.as_ref(),
                                e.to_string(),
                            ))
                        })?;
                    let _ = dbs.insert(
                        name.as_ref().to_string(),
                        ContextDB {
                            name: name.as_ref().to_string(),
                            path: path.as_ref().to_string(),
                            database: Arc::new(Mutex::new(database)),
                            transactions: Arc::new(Mutex::new(HashMap::new())),
                        },
                    );
                    Ok(Database::<R>::create(
                        self.clone(),
                        name.as_ref().to_string(),
                        path.as_ref().to_string(),
                    ))
                } else {
                    Err(crate::Error::open_database(
                        name.as_ref(),
                        self.name(),
                        path.as_ref(),
                        "Specified path is not a file.",
                    ))
                }
            } else {
                let database = polodb_core::Database::open_path(resolved_path).or_else(|e| {
                    Err(crate::Error::open_database(
                        name.as_ref(),
                        self.name(),
                        path.as_ref(),
                        e.to_string(),
                    ))
                })?;
                let _ = dbs.insert(
                    name.as_ref().to_string(),
                    ContextDB {
                        name: name.as_ref().to_string(),
                        path: path.as_ref().to_string(),
                        database: Arc::new(Mutex::new(database)),
                        transactions: Arc::new(Mutex::new(HashMap::new())),
                    },
                );
                Ok(Database::<R>::create(
                    self.clone(),
                    name.as_ref().to_string(),
                    path.as_ref().to_string(),
                ))
            }
        }
    }

    pub async fn database(&self, name: impl AsRef<str>) -> crate::Result<Database<R>> {
        if let Some(db) = self
            .databases()
            .await
            .lock()
            .await
            .get(&name.as_ref().to_string())
        {
            Ok(Database::<R>::create(
                self.clone(),
                name.as_ref().to_string(),
                db.path.clone(),
            ))
        } else {
            Err(crate::Error::unknown_database(name.as_ref()))
        }
    }

    pub(crate) async fn close_database(&self, name: impl AsRef<str>) -> crate::Result<()> {
        if let Some(_) = self
            .databases()
            .await
            .lock()
            .await
            .remove(&name.as_ref().to_string())
        {
            Ok(())
        } else {
            Err(crate::Error::unknown_database(name.as_ref()))
        }
    }

    pub async fn open_file_handle(
        &self,
        path: impl AsRef<str>,
        mode: FileHandleMode,
    ) -> crate::Result<FileHandle<R>> {
        let resolved = self.get_path(path.as_ref())?;
        if mode.create() && !resolved.exists() && resolved.clone().parent().is_some() {
            tokio::fs::create_dir_all(resolved.clone().parent().unwrap())
                .await
                .or_else(|e| {
                    Err(crate::Error::open_file_handle(
                        path.as_ref(),
                        self.name(),
                        e.to_string(),
                    ))
                })?;
        }

        let options: OpenOptions = mode.clone().into();
        let file = options.open(resolved.clone()).await.or_else(|e| {
            Err(crate::Error::open_file_handle(
                path.as_ref(),
                self.name(),
                e.to_string(),
            ))
        })?;
        let handle = ContextFileHandle {
            id: bson::Uuid::new(),
            path: path.as_ref().to_string(),
            handle: async_dup::Arc::new(async_dup::Mutex::new(file)),
            mode: mode.clone(),
        };
        let id = handle.id.clone();

        let _files = self.files().await;
        let mut files = _files.lock().await;
        let _ = files.insert(id.clone(), handle);
        Ok(FileHandle::<R>::create(
            self.clone(),
            id.clone(),
            path.as_ref().to_string(),
        ))
    }

    pub async fn file_handle(&self, id: bson::Uuid) -> crate::Result<FileHandle<R>> {
        if let Some(handle) = self.files().await.lock().await.get(&id) {
            Ok(FileHandle::<R>::create(
                self.clone(),
                id.clone(),
                handle.path.clone(),
            ))
        } else {
            Err(crate::Error::unknown_file_handle(id.to_string()))
        }
    }

    pub(crate) async fn close_file_handle(&self, id: bson::Uuid) -> crate::Result<()> {
        if let Some(_) = self.files().await.lock().await.remove(&id) {
            Ok(())
        } else {
            Err(crate::Error::unknown_file_handle(id.to_string()))
        }
    }

    pub(crate) async fn file_ids(&self) -> Vec<bson::Uuid> {
        let files = self.files().await;
        let handles = files.lock().await;
        let mut result: Vec<bson::Uuid> = Vec::new();
        for id in handles.keys() {
            result.push(id.clone());
        }

        result
    }

    pub(crate) async fn db_ids(&self) -> Vec<String> {
        let dbs = self.databases().await;
        let bases = dbs.lock().await;
        let mut result: Vec<String> = Vec::new();
        for id in bases.keys() {
            result.push(id.clone());
        }

        result
    }
    
    pub async fn close(self) -> crate::Result<()> {
        for handle_id in self.file_ids().await {
            self.close_file_handle(handle_id).await?;
        }

        for db_id in self.db_ids().await {
            self.close_database(db_id).await?;
        }

        Ok(())
    }
}

pub struct Database<R: Runtime> {
    context: Context<R>,
    name: String,
    path: String,
}

impl<R: Runtime> Clone for Database<R> {
    fn clone(&self) -> Self {
        Self {
            context: self.context.clone(),
            name: self.name.clone(),
            path: self.path.clone()
        }
    }
}

impl<R: Runtime> Database<R> {
    pub(crate) fn create(context: Context<R>, name: String, path: String) -> Self {
        Self {
            context,
            name,
            path,
        }
    }

    pub fn name(&self) -> String {
        self.name.clone()
    }

    pub fn path(&self) -> String {
        self.path.clone()
    }

    pub fn absolute_path(&self) -> crate::Result<PathBuf> {
        self.context.get_path(self.path())
    }

    pub(crate) async fn db_context(&self) -> crate::Result<ContextDB> {
        if let Some(db) = self.context.databases().await.lock().await.get(&self.name) {
            Ok(db.clone())
        } else {
            Err(crate::Error::unknown_database(self.name()))
        }
    }

    pub(crate) async fn db(&self) -> crate::Result<Arc<Mutex<polodb_core::Database>>> {
        Ok(self.db_context().await?.database.clone())
    }

    pub async fn close(self) -> crate::Result<()> {
        self.context.close_database(self.name()).await
    }

    pub async fn collections(&self) -> crate::Result<Vec<String>> {
        let db = self.db().await?;
        let database = db.lock().await;
        Ok(database.list_collection_names().or_else(|e| Err(crate::Error::from(e)))?)
    }

    pub async fn collection<T: Serialize + DeserializeOwned + Send + Sync>(&self, name: impl AsRef<str>) -> Collection<T, R> {
        Collection::<T, R>::create(self.clone(), name.as_ref().to_string(), None)
    }

    pub async fn start_transaction(&self) -> crate::Result<Transaction<R>> {
        let context = self.db_context().await?;
        let db = context.database.lock().await;
        let mut transactions = context.transactions.lock().await;
        let new_id = bson::Uuid::new();
        transactions.insert(new_id.clone(), Arc::new(Mutex::new(db.start_transaction().or_else(|e| Err(crate::Error::from(e)))?)));
        Ok(Transaction::<R>::create(self.clone(), new_id))
    }

    pub async fn get_transaction(&self, id: bson::Uuid) -> crate::Result<Transaction<R>> {
        let context = self.db_context().await?;
        let transactions = context.transactions.lock().await;
        if let Some(_) = transactions.get(&id) {
            Ok(Transaction::<R>::create(self.clone(), id.clone()))
        } else {
            Err(crate::Error::unknown_transaction(id.to_string()))
        }
    }

    pub async fn commit_transaction(&self, id: bson::Uuid) -> crate::Result<()> {
        if let Some(mutex) = self.db_context().await?.transactions.lock().await.remove(&id) {
            let transaction = mutex.lock().await;
            transaction.commit().or_else(|e| Err(crate::Error::from(e)))
        } else {
            Err(crate::Error::unknown_transaction(id.to_string()))
        }
    }

    pub async fn rollback_transaction(&self, id: bson::Uuid) -> crate::Result<()> {
        if let Some(mutex) = self.db_context().await?.transactions.lock().await.remove(&id) {
            let transaction = mutex.lock().await;
            transaction.rollback().or_else(|e| Err(crate::Error::from(e)))
        } else {
            Err(crate::Error::unknown_transaction(id.to_string()))
        }
    }
}

pub struct Transaction<R: Runtime> {
    database: Database<R>,
    id: bson::Uuid
}

impl<R: Runtime> Clone for Transaction<R> {
    fn clone(&self) -> Self {
        Self {
            database: self.database.clone(),
            id: self.id.clone()
        }
    }
}

impl<R: Runtime> Transaction<R> {
    pub(crate) fn create(database: Database<R>, id: bson::Uuid) -> Self {
        Self {
            database, id
        }
    }

    pub fn id(&self) -> bson::Uuid {
        self.id.clone()
    }

    pub fn collection<T: Serialize + DeserializeOwned + Send + Sync>(&self, name: impl AsRef<str>) -> Collection<T, R> {
        Collection::create(self.database.clone(), name.as_ref().to_string(), Some(self.id.clone()))
    }

    pub async fn commit(self) -> crate::Result<()> {
        self.database.commit_transaction(self.id()).await
    }

    pub async fn rollback(self) -> crate::Result<()> {
        self.database.rollback_transaction(self.id()).await
    }
}

pub struct FileHandle<R: Runtime> {
    context: Context<R>,
    id: bson::Uuid,
    path: String,
}

impl<R: Runtime> Clone for FileHandle<R> {
    fn clone(&self) -> Self {
        Self {
            context: self.context.clone(),
            id: self.id.clone(),
            path: self.path.clone()
        }
    }
}

impl<R: Runtime> FileHandle<R> {
    pub(crate) fn create(context: Context<R>, id: bson::Uuid, path: String) -> Self {
        Self { context, id, path }
    }

    pub fn id(&self) -> bson::Uuid {
        self.id.clone()
    }

    pub fn path(&self) -> String {
        self.path.clone()
    }

    pub fn absolute_path(&self) -> crate::Result<PathBuf> {
        self.context.get_path(self.path())
    }

    pub async fn close(self) -> crate::Result<()> {
        self.context.close_file_handle(self.id()).await
    }

    async fn metadata(&self) -> ContextFileHandle {
        self.context.files().await.lock().await.get(&self.id()).expect("File handle has been closed.").clone()
    }

    pub async fn mode(&self) -> FileHandleMode {
        self.metadata().await.mode
    }

    pub async fn handle(&self) -> async_dup::Arc<async_dup::Mutex<File>> {
        self.metadata().await.handle.clone()
    }
}

pub(crate) enum CollectionType {
    Standalone(polodb_core::Collection<Document>),
    Transaction(polodb_core::TransactionalCollection<Document>)
}

impl CollectionT<Document> for CollectionType {
    fn name(&self) -> &str {
        match self {
            Self::Standalone(c) => c.name(),
            Self::Transaction(c) => c.name()
        }
    }

    fn count_documents(&self) -> polodb_core::Result<u64> {
        match self {
            Self::Standalone(c) => c.count_documents(),
            Self::Transaction(c) => c.count_documents()
        }
    }

    fn update_one(&self, query: Document, update: Document) -> polodb_core::Result<polodb_core::results::UpdateResult> {
        match self {
            Self::Standalone(c) => c.update_one(query, update),
            Self::Transaction(c) => c.update_one(query, update)
        }
    }

    fn update_one_with_options(&self, query: Document, update: Document, options: polodb_core::options::UpdateOptions) -> polodb_core::Result<polodb_core::results::UpdateResult> {
        match self {
            Self::Standalone(c) => c.update_one_with_options(query, update, options),
            Self::Transaction(c) => c.update_one_with_options(query, update, options)
        }
    }

    fn update_many(&self, query: Document, update: Document) -> polodb_core::Result<polodb_core::results::UpdateResult> {
        match self {
            Self::Standalone(c) => c.update_many(query, update),
            Self::Transaction(c) => c.update_many(query, update)
        }
    }

    fn update_many_with_options(&self, query: Document, update: Document, options: polodb_core::options::UpdateOptions) -> polodb_core::Result<polodb_core::results::UpdateResult> {
        match self {
            Self::Standalone(c) => c.update_many_with_options(query, update, options),
            Self::Transaction(c) => c.update_many_with_options(query, update, options)
        }
    }

    fn delete_one(&self, query: Document) -> polodb_core::Result<polodb_core::results::DeleteResult> {
        match self {
            Self::Standalone(c) => c.delete_one(query),
            Self::Transaction(c) => c.delete_one(query)
        }
    }

    fn delete_many(&self, query: Document) -> polodb_core::Result<polodb_core::results::DeleteResult> {
        match self {
            Self::Standalone(c) => c.delete_many(query),
            Self::Transaction(c) => c.delete_many(query)
        }
    }

    fn create_index(&self, index: polodb_core::IndexModel) -> polodb_core::Result<()> {
        match self {
            Self::Standalone(c) => c.create_index(index),
            Self::Transaction(c) => c.create_index(index)
        }
    }

    fn drop_index(&self, name: impl AsRef<str>) -> polodb_core::Result<()> {
        match self {
            Self::Standalone(c) => c.drop_index(name),
            Self::Transaction(c) => c.drop_index(name)
        }
    }

    fn drop(&self) -> polodb_core::Result<()> {
        match self {
            Self::Standalone(c) => c.drop(),
            Self::Transaction(c) => c.drop()
        }
    }

    fn insert_one(&self, doc: impl std::borrow::Borrow<Document>) -> polodb_core::Result<polodb_core::results::InsertOneResult>
    where Document: Serialize {
        match self {
            Self::Standalone(c) => c.insert_one(doc),
            Self::Transaction(c) => c.insert_one(doc)
        }
    }

    fn insert_many(&self, docs: impl IntoIterator<Item = impl std::borrow::Borrow<Document>>) -> polodb_core::Result<polodb_core::results::InsertManyResult>
    where Document: Serialize {
        match self {
            Self::Standalone(c) => c.insert_many(docs),
            Self::Transaction(c) => c.insert_many(docs)
        }
    }

    fn find(&self, filter: Document) -> polodb_core::action::Find<'_, '_, Document>
    where Document: DeserializeOwned + Send + Sync {
        match self {
            Self::Standalone(c) => c.find(filter),
            Self::Transaction(c) => c.find(filter)
        }
    }

    fn find_one(&self, filter: Document) -> polodb_core::Result<Option<Document>>
    where Document: DeserializeOwned + Send + Sync {
        match self {
            Self::Standalone(c) => c.find_one(filter),
            Self::Transaction(c) => c.find_one(filter)
        }
    }

    fn aggregate(&self, pipeline: impl IntoIterator<Item = Document>) -> polodb_core::action::Aggregate<'_, '_> {
        match self {
            Self::Standalone(c) => c.aggregate(pipeline),
            Self::Transaction(c) => c.aggregate(pipeline)
        }
    }
}

pub struct Collection<T: Serialize + DeserializeOwned + Send + Sync, R: Runtime> {
    database: Database<R>,
    name: String,
    transaction_id: Option<bson::Uuid>,
    _doctype: PhantomData<T>
}

impl<T: Serialize + DeserializeOwned + Send + Sync, R: Runtime> Clone for Collection<T, R> {
    fn clone(&self) -> Self {
        Self {
            database: self.database.clone(),
            name: self.name.clone(),
            transaction_id: self.transaction_id.clone(),
            _doctype: PhantomData
        }
    }
}

impl<T: Serialize + DeserializeOwned + Send + Sync, R: Runtime> Collection<T, R> {
    pub(crate) fn create(db: Database<R>, name: String, transaction_id: Option<bson::Uuid>) -> Self {
        Self {
            database: db.clone(),
            name,
            transaction_id,
            _doctype: PhantomData
        }
    }

    pub fn name(&self) -> String {
        self.name.clone()
    }

    pub(crate) async fn collection(&self) -> crate::Result<CollectionType> {
        let db = self.database.db().await?;
        if let Some(id) = self.transaction_id {
            let dbcon = self.database.db_context().await?;
            let transactions = dbcon.transactions.lock().await;
            if let Some(transaction) = transactions.get(&id) {
                Ok(CollectionType::Transaction(transaction.lock().await.collection::<Document>(&self.name())))
            } else {
                Err(crate::Error::unknown_transaction(id.to_string()))
            }
        } else {
            Ok(CollectionType::Standalone(db.lock().await.collection::<Document>(&self.name())))
        }
    }

    pub async fn count_documents(&self) -> crate::Result<u64> {
        self.collection().await?.count_documents().or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn update_one(&self, query: Document, update: Document) -> crate::Result<UpdateResult> {
        self.collection().await?.update_one(query, update).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn update_one_with_options(
        &self,
        query: Document,
        update: Document,
        options: UpdateOptions,
    ) -> crate::Result<UpdateResult> {
        self.collection().await?.update_one_with_options(query, update, options).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn update_many(&self, query: Document, update: Document) -> crate::Result<UpdateResult> {
        self.collection().await?.update_many(query, update).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn update_many_with_options(
        &self,
        query: Document,
        update: Document,
        options: UpdateOptions,
    ) -> crate::Result<UpdateResult> {
        self.collection().await?.update_many_with_options(query, update, options).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn delete_one(&self, query: Document) -> crate::Result<DeleteResult> {
        self.collection().await?.delete_one(query).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn delete_many(&self, query: Document) -> crate::Result<DeleteResult> {
        self.collection().await?.delete_many(query).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn create_index(&self, index: IndexModel) -> crate::Result<()> {
        self.collection().await?.create_index(index).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn drop_index(&self, name: impl AsRef<str>) -> crate::Result<()> {
        self.collection().await?.drop_index(name).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn drop(&self) -> crate::Result<()> {
        self.collection().await?.drop().or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn insert_one(&self, doc: impl Borrow<T>) -> crate::Result<InsertOneResult> {
        self.collection().await?.insert_one(bson::to_document(doc.borrow()).or_else(|e| Err(crate::Error::from(e)))?).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn insert_many(
        &self,
        docs: impl IntoIterator<Item = impl Borrow<T>>,
    ) -> crate::Result<InsertManyResult> {
        let mut serialized: Vec<Document> = Vec::new();
        for doc in docs {
            serialized.push(bson::to_document(doc.borrow()).or_else(|e| Err(crate::Error::from(e)))?);
        }

        self.collection().await?.insert_many(serialized).or_else(|e| Err(crate::Error::from(e)))
    }

    pub async fn find(&self, filter: Document, skip: Option<u64>, limit: Option<u64>, sort: Option<Document>) -> crate::Result<Vec<T>> {
        let mut results: Vec<T> = Vec::new();
        let collection = self.collection().await?;
        let mut find = collection.find(filter);
        if let Some(_skip) = skip {
            find = find.skip(_skip);
        }

        if let Some(_limit) = limit {
            find = find.limit(_limit);
        }

        if let Some(_sort) = sort {
            find = find.sort(_sort);
        }

        let docs: Vec<Result<Document, polodb_core::Error>> = find.run().or_else(|e| Err(crate::Error::from(e)))?.collect();
        for dresult in docs {
            results.push(match dresult {
                Ok(doc) => bson::from_document::<T>(doc).or_else(|e| Err(crate::Error::from(e))),
                Err(e) => Err(crate::Error::from(e))
            }?);
        }

        Ok(results)
    }

    pub async fn find_one(&self, filter: Document) -> crate::Result<Option<T>> {
        let raw = self.collection().await?.find_one(filter).or_else(|e| Err(crate::Error::from(e)))?;
        if let Some(doc) = raw {
            Ok(Some(bson::from_document::<T>(doc).or_else(|e| Err(crate::Error::from(e)))?))
        } else {
            Ok(None)
        }
    }
}