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
use js_sys::Array;
use num_traits::ToPrimitive;
use wasm_bindgen::{prelude::Closure, JsCast, JsValue};
use web_sys::{Event, EventTarget, IdbDatabase};

use crate::{
    utils::dom_string_list_to_vec, Error, ObjectStore, ObjectStoreParams, Transaction,
    TransactionMode,
};

/// [`Database`] provides a connection to a database; you can use an [`Database`] object to open a transaction on your
/// database then create, manipulate, and delete objects (data) in that database. The object provides the only way to
/// get and manage versions of the database.
#[derive(Debug)]
pub struct Database {
    inner: IdbDatabase,
    abort_callback: Option<Closure<dyn FnMut(Event)>>,
    close_callback: Option<Closure<dyn FnMut(Event)>>,
    error_callback: Option<Closure<dyn FnMut(Event)>>,
    version_change_callback: Option<Closure<dyn FnMut(Event)>>,
}

impl Database {
    /// Returns the name of the database.
    pub fn name(&self) -> String {
        self.inner.name()
    }

    /// Returns the version of the database.
    pub fn version(&self) -> Result<u32, Error> {
        self.inner
            .version()
            .to_u32()
            .ok_or(Error::NumberConversionError)
    }

    /// Returns a list of the names of [`ObjectStore`]s in the database.
    pub fn store_names(&self) -> Vec<String> {
        dom_string_list_to_vec(&self.inner.object_store_names())
    }

    /// Returns a new transaction with the given scope (which can be a single object store name or an array of names),
    /// mode ([`TransactionMode::ReadOnly`] or [`TransactionMode::ReadWrite`]).
    pub fn transaction<T>(
        &self,
        store_names: &[T],
        mode: TransactionMode,
    ) -> Result<Transaction, Error>
    where
        T: AsRef<str>,
    {
        let store_names: Array = store_names
            .iter()
            .map(|s| JsValue::from(s.as_ref()))
            .collect();

        self.inner
            .transaction_with_str_sequence_and_mode(&store_names, mode.into())
            .map(Into::into)
            .map_err(Error::TransactionOpenFailed)
    }

    /// Closes the connection once all running transactions have finished.
    pub fn close(&self) {
        self.inner.close()
    }

    /// Creates a new object store with the given name and options and returns a new [`ObjectStore`]. Returns an
    /// [`Error`] if not called within an upgrade transaction.
    pub fn create_object_store(
        &self,
        name: &str,
        params: ObjectStoreParams,
    ) -> Result<ObjectStore, Error> {
        self.inner
            .create_object_store_with_optional_parameters(name, &params.into())
            .map(Into::into)
            .map_err(Error::ObjectStoreCreateFailed)
    }

    /// Deletes the object store with the given name. Returns an [`Error`] if not called within an upgrade transaction.
    pub fn delete_object_store(&self, name: &str) -> Result<(), Error> {
        self.inner
            .delete_object_store(name)
            .map_err(Error::ObjectStoreDeleteFailed)
    }

    /// Adds an event handler for `abort` event.
    pub fn on_abort<F>(&mut self, callback: F)
    where
        F: FnOnce(Event) + 'static,
    {
        let closure = Closure::once(callback);
        self.inner
            .set_onabort(Some(closure.as_ref().unchecked_ref()));
        self.abort_callback = Some(closure);
    }

    /// Adds an event handler for `close` event.
    pub fn on_close<F>(&mut self, callback: F)
    where
        F: FnOnce(Event) + 'static,
    {
        let closure = Closure::once(callback);
        self.inner
            .set_onclose(Some(closure.as_ref().unchecked_ref()));
        self.close_callback = Some(closure);
    }

    /// Adds an event handler for `error` event.
    pub fn on_error<F>(&mut self, callback: F)
    where
        F: FnOnce(Event) + 'static,
    {
        let closure = Closure::once(callback);
        self.inner
            .set_onerror(Some(closure.as_ref().unchecked_ref()));
        self.error_callback = Some(closure);
    }

    /// Adds an event handler for `versionchange` event.
    pub fn on_version_change<F>(&mut self, callback: F)
    where
        F: FnOnce(Event) + 'static,
    {
        let closure = Closure::once(callback);
        self.inner
            .set_onversionchange(Some(closure.as_ref().unchecked_ref()));
        self.version_change_callback = Some(closure);
    }
}

impl TryFrom<EventTarget> for Database {
    type Error = Error;

    fn try_from(target: EventTarget) -> Result<Self, Self::Error> {
        let target: JsValue = target.into();
        target
            .dyn_into::<IdbDatabase>()
            .map(Into::into)
            .map_err(|value| Error::UnexpectedJsType("IdbDatabase", value))
    }
}

impl From<IdbDatabase> for Database {
    fn from(inner: IdbDatabase) -> Self {
        Self {
            inner,
            abort_callback: None,
            close_callback: None,
            error_callback: None,
            version_change_callback: None,
        }
    }
}

impl From<Database> for IdbDatabase {
    fn from(database: Database) -> Self {
        database.inner
    }
}

impl TryFrom<JsValue> for Database {
    type Error = Error;

    fn try_from(value: JsValue) -> Result<Self, Self::Error> {
        value
            .dyn_into::<IdbDatabase>()
            .map(Into::into)
            .map_err(|value| Error::UnexpectedJsType("IdbDatabase", value))
    }
}

impl From<Database> for JsValue {
    fn from(value: Database) -> Self {
        value.inner.into()
    }
}