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
#![cfg_attr(not(feature = "global"), allow(unused_imports, unused_variables))]

use crate::{Database, DatabaseRc, WeakDatabaseRc};
use std::sync::Mutex;

#[cfg(feature = "global")]
lazy_static::lazy_static! {
    static ref DATABASE: Mutex<Option<DatabaseRc>> = Mutex::new(None);
    static ref WITH_LOCK: Mutex<()> = Mutex::new(());
}

/// Executes the given function with the provided database as the new, global
/// database, destroying the database once the function completes; locks
/// execution of this function, only allowing one call to `with_db` at a time
pub fn with_db_from_rc<F: FnMut() -> R, R>(database: DatabaseRc, mut f: F) -> R {
    #[cfg(feature = "global")]
    let _lock = WITH_LOCK.lock().unwrap();

    set_db_from_rc(database);
    let result = f();
    destroy_db();
    result
}

/// Executes the given function with the provided database as the new, global
/// database, destroying the database once the function completes; locks
/// execution of this function, only allowing one call to `with_db` at a time
#[inline]
pub fn with_db_from_box<F: FnMut() -> R, R>(database: Box<dyn Database>, f: F) -> R {
    with_db_from_rc(DatabaseRc::new(database), f)
}

/// Executes the given function with the provided database as the new, global
/// database, destroying the database once the function completes; locks
/// execution of this function, only allowing one call to `with_db` at a time
#[inline]
pub fn with_db<D: Database + 'static, F: FnMut() -> R, R>(database: D, f: F) -> R {
    with_db_from_box(Box::new(database), f)
}

/// Returns a weak reference to the global database if it is set, otherwise
/// will return a weak reference that will resolve to None when upgrading
#[inline]
pub fn db() -> WeakDatabaseRc {
    #[cfg(feature = "global")]
    let x = match DATABASE.lock().unwrap().as_ref() {
        Some(x) => DatabaseRc::downgrade(x),
        None => WeakDatabaseRc::new(),
    };

    #[cfg(not(feature = "global"))]
    let x = WeakDatabaseRc::new();

    x
}

/// Sets the global database to the specific database implementation
#[inline]
pub fn set_db<D: Database + 'static>(database: D) -> WeakDatabaseRc {
    set_db_from_box(Box::new(database))
}

/// Sets the global database to the database trait object
#[inline]
pub fn set_db_from_box(database: Box<dyn Database>) -> WeakDatabaseRc {
    set_db_from_rc(DatabaseRc::new(database))
}

/// Sets the global database to the strong reference and returns a weak
/// reference to the same database
#[inline]
pub fn set_db_from_rc(database_rc: DatabaseRc) -> WeakDatabaseRc {
    #[cfg(feature = "global")]
    DATABASE.lock().unwrap().replace(database_rc);
    db()
}

/// Returns true if the global database has been assigned
#[inline]
pub fn has_db() -> bool {
    #[cfg(feature = "global")]
    let x = DATABASE.lock().unwrap().is_some();

    #[cfg(not(feature = "global"))]
    let x = false;

    x
}

/// Removes the global database reference
#[inline]
pub fn destroy_db() {
    #[cfg(feature = "global")]
    DATABASE.lock().unwrap().take();
}

#[cfg(all(test, feature = "global"))]
mod tests {
    use super::*;
    use crate::{DatabaseResult, Ent, Id, Query};

    /// Resets database to starting state
    fn reset_db_state() {
        DATABASE.lock().unwrap().take();
    }

    /// NOTE: We have to run all tests that impact the global database in a
    ///       singular test to avoid race conditions in modifying and checking
    ///       global database state from parallel tests. This is to avoid the
    ///       need to run the entire test infra in a single thread, which is
    ///       much slower.
    #[test]
    fn test_runner() {
        fn db_should_return_empty_weak_ref_if_database_not_set() {
            reset_db_state();

            assert!(
                WeakDatabaseRc::ptr_eq(&db(), &WeakDatabaseRc::new()),
                "Returned weak reference unexpectedly pointing to database"
            );
        }
        db_should_return_empty_weak_ref_if_database_not_set();

        fn db_should_return_weak_ref_for_active_database_if_set() {
            reset_db_state();

            set_db(TestDatabase);
            assert!(
                !WeakDatabaseRc::ptr_eq(&db(), &WeakDatabaseRc::new()),
                "Returned weak reference not pointing to database"
            );
        }
        db_should_return_weak_ref_for_active_database_if_set();

        fn set_db_should_update_the_global_database_with_the_given_instance() {
            reset_db_state();

            assert!(
                !WeakDatabaseRc::ptr_eq(&set_db(TestDatabase), &WeakDatabaseRc::new()),
                "Returned weak reference not pointing to database"
            );

            assert!(DATABASE.lock().unwrap().is_some());
        }
        set_db_should_update_the_global_database_with_the_given_instance();

        fn set_db_from_box_should_update_the_global_database_with_the_given_instance() {
            reset_db_state();

            assert!(
                !WeakDatabaseRc::ptr_eq(
                    &set_db_from_box(Box::new(TestDatabase)),
                    &WeakDatabaseRc::new()
                ),
                "Returned weak reference not pointing to database"
            );

            assert!(DATABASE.lock().unwrap().is_some());
        }
        set_db_from_box_should_update_the_global_database_with_the_given_instance();

        fn set_db_from_rc_should_update_the_global_database_with_the_given_instance() {
            reset_db_state();

            assert!(
                !WeakDatabaseRc::ptr_eq(
                    &set_db_from_rc(DatabaseRc::new(Box::new(TestDatabase))),
                    &WeakDatabaseRc::new()
                ),
                "Returned weak reference not pointing to database"
            );

            assert!(DATABASE.lock().unwrap().is_some());
        }
        set_db_from_rc_should_update_the_global_database_with_the_given_instance();

        fn has_db_should_return_false_if_database_not_set() {
            reset_db_state();

            assert!(!has_db(), "Unexpectedly reported having database");
        }
        has_db_should_return_false_if_database_not_set();

        fn has_db_should_return_false_if_database_destroyed() {
            reset_db_state();

            DATABASE
                .lock()
                .unwrap()
                .replace(DatabaseRc::new(Box::new(TestDatabase)));
            destroy_db();

            assert!(!has_db(), "Unexpectedly reported having database");
        }
        has_db_should_return_false_if_database_destroyed();

        fn has_db_should_return_true_if_database_set() {
            reset_db_state();

            set_db(TestDatabase);
            assert!(has_db(), "Unexpectedly reported NOT having database");
        }
        has_db_should_return_true_if_database_set();

        fn destroy_db_should_remove_global_database_if_set() {
            reset_db_state();

            DATABASE
                .lock()
                .unwrap()
                .replace(DatabaseRc::new(Box::new(TestDatabase)));

            destroy_db();
            assert!(
                DATABASE.lock().unwrap().is_none(),
                "Database was not destroyed"
            );
        }
        destroy_db_should_remove_global_database_if_set();

        fn destroy_db_should_do_nothing_if_global_database_is_not_set() {
            reset_db_state();

            destroy_db();
            assert!(
                DATABASE.lock().unwrap().is_none(),
                "Database was not destroyed"
            );
        }
        destroy_db_should_do_nothing_if_global_database_is_not_set();
    }

    /// Represents a test database so we can run the above tests regardless
    /// of whether the inmemory, sled, or other database feature is active
    struct TestDatabase;

    impl Database for TestDatabase {
        fn get(&self, _id: Id) -> DatabaseResult<Option<Box<dyn Ent>>> {
            unimplemented!()
        }

        fn remove(&self, _id: Id) -> DatabaseResult<bool> {
            unimplemented!()
        }

        fn insert(&self, _ent: Box<dyn Ent>) -> DatabaseResult<Id> {
            unimplemented!()
        }

        fn get_all(&self, _ids: Vec<Id>) -> DatabaseResult<Vec<Box<dyn Ent>>> {
            unimplemented!()
        }

        fn find_all(&self, _query: Query) -> DatabaseResult<Vec<Box<dyn Ent>>> {
            unimplemented!()
        }
    }
}