indexed-db 0.4.2

Bindings to IndexedDB that default the transactions to aborting and can work multi-threaded
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
use crate::{
    transaction::transaction_request,
    utils::{
        array_to_vec, make_key_range, map_add_err, map_clear_err, map_count_err, map_count_res,
        map_delete_err, map_get_err, none_if_undefined, str_slice_to_array,
    },
    CursorBuilder, Index,
};
use futures_util::future::{Either, FutureExt};
use std::{future::Future, marker::PhantomData, ops::RangeBounds};
use web_sys::{js_sys::JsString, wasm_bindgen::JsValue, IdbIndexParameters, IdbObjectStore};

#[cfg(doc)]
use crate::Cursor;

/// Wrapper for [`IDBObjectStore`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore),
/// for use in transactions
#[derive(Debug)]
pub struct ObjectStore<Err> {
    sys: IdbObjectStore,
    _phantom: PhantomData<Err>,
}

impl<Err> ObjectStore<Err> {
    pub(crate) fn from_sys(sys: IdbObjectStore) -> ObjectStore<Err> {
        ObjectStore {
            sys,
            _phantom: PhantomData,
        }
    }

    /// Build an index over this object store
    ///
    /// Note that this method can only be called from within an `on_upgrade_needed` callback. It returns
    /// a builder, and calling the `create` method on this builder will perform the actual creation.
    ///
    /// If you want to make an index that searches multiple columns, please use [`ObjectStore::build_compound_index`].
    ///
    /// Internally, this uses [`IDBObjectStore::createIndex`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex).
    pub fn build_index<'a>(&self, name: &'a str, key_path: &str) -> IndexBuilder<'a, Err> {
        IndexBuilder {
            store: self.sys.clone(),
            name,
            key_path: JsString::from(key_path).into(),
            options: IdbIndexParameters::new(),
            _phantom: PhantomData,
        }
    }

    /// Build a compound index over this object store
    ///
    /// Note that this method can only be called from within an `on_upgrade_needed` callback. It returns
    /// a builder, and calling the `create` method on this builder will perform the actual creation.
    ///
    /// Interesting points about indices:
    /// - It is not possible to index `bool` in IndexedDB.
    /// - If your index uses a column that does not exist, then the object will not be recorded in the index.
    ///   This is useful for unique compound indices, usually when you would have conditionally indexed a `bool` column otherwise.
    /// - You cannot build a compound multi-entry index, it needs to be a regular index.
    ///
    /// Internally, this uses [`IDBObjectStore::createIndex`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex).
    pub fn build_compound_index<'a>(
        &self,
        name: &'a str,
        key_paths: &[&str],
    ) -> IndexBuilder<'a, Err> {
        IndexBuilder {
            store: self.sys.clone(),
            name,
            key_path: str_slice_to_array(key_paths).into(),
            options: IdbIndexParameters::new(),
            _phantom: PhantomData,
        }
    }

    /// Delete an index from this object store
    ///
    /// Note that this method can only be called from within an `on_upgrade_needed` callback.
    ///
    /// Internally, this uses [`IDBObjectStore::deleteIndex`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/deleteIndex).
    pub fn delete_index(&self, name: &str) -> crate::Result<(), Err> {
        self.sys
            .delete_index(name)
            .map_err(|err| match error_name!(&err) {
                Some("InvalidStateError") => crate::Error::ObjectStoreWasRemoved,
                Some("NotFoundError") => crate::Error::DoesNotExist,
                _ => crate::Error::from_js_value(err),
            })
    }

    /// Add the value `value` to this object store, and return its auto-computed key
    ///
    /// This will error if the key already existed.
    ///
    /// Internally, this uses [`IDBObjectStore::add`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add).
    pub fn add(&self, value: &JsValue) -> impl Future<Output = crate::Result<JsValue, Err>> {
        match self.sys.add(value) {
            Ok(add_req) => {
                Either::Left(transaction_request(add_req).map(|res| res.map_err(map_add_err)))
            }
            Err(e) => Either::Right(std::future::ready(Err(map_add_err(e)))),
        }
    }

    /// Add the value `value` to this object store, with key `key`
    ///
    /// This will error if the key already existed.
    ///
    /// Internally, this uses [`IDBObjectStore::add`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add).
    pub fn add_kv(
        &self,
        key: &JsValue,
        value: &JsValue,
    ) -> impl Future<Output = crate::Result<(), Err>> {
        match self.sys.add_with_key(value, key) {
            Ok(add_req) => Either::Left(
                transaction_request(add_req).map(|res| res.map_err(map_add_err).map(|_| ())),
            ),
            Err(e) => Either::Right(std::future::ready(Err(map_add_err(e)))),
        }
    }

    /// Add the value `value` to this object store, and return its auto-computed key
    ///
    /// This will overwrite the previous value if the key already existed.
    ///
    /// Internally, this uses [`IDBObjectStore::add`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add).
    pub fn put(&self, value: &JsValue) -> impl Future<Output = crate::Result<JsValue, Err>> {
        match self.sys.put(value) {
            Ok(add_req) => {
                Either::Left(transaction_request(add_req).map(|res| res.map_err(map_add_err)))
            }
            Err(e) => Either::Right(std::future::ready(Err(map_add_err(e)))),
        }
    }

    /// Add the value `value` to this object store, with key `key`
    ///
    /// This will overwrite the previous value if the key already existed.
    ///
    /// Internally, this uses [`IDBObjectStore::add`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add).
    pub fn put_kv(
        &self,
        key: &JsValue,
        value: &JsValue,
    ) -> impl Future<Output = crate::Result<(), Err>> {
        match self.sys.put_with_key(value, key) {
            Ok(add_req) => Either::Left(
                transaction_request(add_req).map(|res| res.map_err(map_add_err).map(|_| ())),
            ),
            Err(e) => Either::Right(std::future::ready(Err(map_add_err(e)))),
        }
    }

    /// Clear this object store
    ///
    /// Internally, this uses [`IDBObjectStore::clear`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/clear).
    pub fn clear(&self) -> impl Future<Output = crate::Result<(), Err>> {
        match self.sys.clear() {
            Ok(clear_req) => Either::Left(
                transaction_request(clear_req).map(|res| res.map_err(map_clear_err).map(|_| ())),
            ),
            Err(err) => Either::Right(std::future::ready(Err(map_clear_err(err)))),
        }
    }

    /// Count the number of objects in this store
    ///
    /// Internally, this uses [`IDBObjectStore::count`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/count).
    pub fn count(&self) -> impl Future<Output = crate::Result<usize, Err>> {
        match self.sys.count() {
            Ok(count_req) => Either::Left(
                transaction_request(count_req)
                    .map(|res| res.map_err(map_count_err).map(map_count_res)),
            ),
            Err(e) => Either::Right(std::future::ready(Err(map_count_err(e)))),
        }
    }

    /// Checks whether the provided key exists in this object store
    ///
    /// Internally, this uses [`IDBObjectStore::count`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/count).
    pub fn contains(&self, key: &JsValue) -> impl Future<Output = crate::Result<bool, Err>> {
        match self.sys.count_with_key(key) {
            Ok(count_req) => Either::Left(
                transaction_request(count_req)
                    .map(|res| res.map_err(map_count_err).map(|n| map_count_res(n) != 0)),
            ),
            Err(e) => Either::Right(std::future::ready(Err(map_count_err(e)))),
        }
    }

    /// Counts the number of objects with a key in `range`
    ///
    /// Note that the unbounded range is not a valid range for IndexedDB.
    ///
    /// Internally, this uses [`IDBObjectStore::count`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/count).
    pub fn count_in(
        &self,
        range: impl RangeBounds<JsValue>,
    ) -> impl Future<Output = crate::Result<usize, Err>> {
        let range = match make_key_range(range) {
            Ok(range) => range,
            Err(e) => return Either::Left(std::future::ready(Err(e))),
        };
        match self.sys.count_with_key(&range) {
            Ok(count_req) => Either::Right(
                transaction_request(count_req)
                    .map(|res| res.map_err(map_count_err).map(map_count_res)),
            ),
            Err(e) => Either::Left(std::future::ready(Err(map_count_err(e)))),
        }
    }

    /// Delete the object with key `key`
    ///
    /// Unfortunately, the IndexedDb API does not indicate whether an object was actually deleted.
    ///
    /// Internally, this uses [`IDBObjectStore::delete`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete).
    pub fn delete(&self, key: &JsValue) -> impl Future<Output = crate::Result<(), Err>> {
        match self.sys.delete(key) {
            Ok(delete_req) => Either::Left(
                transaction_request(delete_req).map(|res| res.map_err(map_delete_err).map(|_| ())),
            ),
            Err(e) => Either::Right(std::future::ready(Err(map_delete_err(e)))),
        }
    }

    /// Delete all the objects with a key in `range`
    ///
    /// Note that the unbounded range is not a valid range for IndexedDB.
    /// Unfortunately, the IndexedDb API does not indicate whether an object was actually deleted.
    ///
    /// Internally, this uses [`IDBObjectStore::delete`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete).
    pub fn delete_range(
        &self,
        range: impl RangeBounds<JsValue>,
    ) -> impl Future<Output = crate::Result<(), Err>> {
        let range = match make_key_range(range) {
            Ok(range) => range,
            Err(e) => return Either::Left(std::future::ready(Err(e))),
        };
        match self.sys.delete(&range) {
            Ok(delete_req) => Either::Right(
                transaction_request(delete_req).map(|res| res.map_err(map_delete_err).map(|_| ())),
            ),
            Err(e) => Either::Left(std::future::ready(Err(map_delete_err(e)))),
        }
    }

    /// Get the object with key `key`
    ///
    /// Internally, this uses [`IDBObjectStore::get`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get).
    pub fn get(&self, key: &JsValue) -> impl Future<Output = crate::Result<Option<JsValue>, Err>> {
        match self.sys.get(key) {
            Ok(get_req) => Either::Right(
                transaction_request(get_req)
                    .map(|res| res.map_err(map_get_err).map(none_if_undefined)),
            ),
            Err(err) => Either::Left(std::future::ready(Err(map_get_err(err)))),
        }
    }

    /// Get the first value with a key in `range`, ordered by key
    ///
    /// Note that the unbounded range is not a valid range for IndexedDB.
    ///
    /// Internally, this uses [`IDBObjectStore::get`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get).
    pub fn get_first_in(
        &self,
        range: impl RangeBounds<JsValue>,
    ) -> impl Future<Output = crate::Result<Option<JsValue>, Err>> {
        let range = match make_key_range(range) {
            Ok(range) => range,
            Err(e) => return Either::Left(std::future::ready(Err(e))),
        };
        match self.sys.get(&range) {
            Ok(get_req) => Either::Right(
                transaction_request(get_req)
                    .map(|res| res.map_err(map_get_err).map(none_if_undefined)),
            ),
            Err(e) => Either::Left(std::future::ready(Err(map_get_err(e)))),
        }
    }

    /// Get all the objects in the store, with a maximum number of results of `limit`
    ///
    /// Internally, this uses [`IDBObjectStore::getAll`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll).
    pub fn get_all(
        &self,
        limit: Option<u32>,
    ) -> impl Future<Output = crate::Result<Vec<JsValue>, Err>> {
        let get_req = match limit {
            None => self.sys.get_all(),
            Some(limit) => self
                .sys
                .get_all_with_key_and_limit(&JsValue::UNDEFINED, limit),
        };
        match get_req {
            Ok(get_req) => Either::Right(
                transaction_request(get_req).map(|res| res.map_err(map_get_err).map(array_to_vec)),
            ),
            Err(err) => Either::Left(std::future::ready(Err(map_get_err(err)))),
        }
    }

    /// Get all the objects with a key in the provided range, with a maximum number of results of `limit`
    ///
    /// Internally, this uses [`IDBObjectStore::getAll`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll).
    pub fn get_all_in(
        &self,
        range: impl RangeBounds<JsValue>,
        limit: Option<u32>,
    ) -> impl Future<Output = crate::Result<Vec<JsValue>, Err>> {
        let range = match make_key_range(range) {
            Ok(range) => range,
            Err(e) => return Either::Left(std::future::ready(Err(e))),
        };
        let get_req = match limit {
            None => self.sys.get_all_with_key(&range),
            Some(limit) => self.sys.get_all_with_key_and_limit(&range, limit),
        };
        match get_req {
            Ok(get_req) => Either::Right(
                transaction_request(get_req).map(|res| res.map_err(map_get_err).map(array_to_vec)),
            ),
            Err(err) => Either::Left(std::future::ready(Err(map_get_err(err)))),
        }
    }

    /// Get the first existing key in the provided range
    ///
    /// Internally, this uses [`IDBObjectStore::getKey`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getKey).
    pub fn get_first_key_in(
        &self,
        range: impl RangeBounds<JsValue>,
    ) -> impl Future<Output = crate::Result<Option<JsValue>, Err>> {
        let range = match make_key_range(range) {
            Ok(range) => range,
            Err(e) => return Either::Left(std::future::ready(Err(e))),
        };
        match self.sys.get_key(&range) {
            Ok(get_req) => Either::Right(
                transaction_request(get_req)
                    .map(|res| res.map_err(map_get_err).map(none_if_undefined)),
            ),
            Err(err) => Either::Left(std::future::ready(Err(map_get_err(err)))),
        }
    }

    /// List all the keys in the object store, with a maximum number of results of `limit`
    ///
    /// Internally, this uses [`IDBObjectStore::getAllKeys`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys).
    pub fn get_all_keys(
        &self,
        limit: Option<u32>,
    ) -> impl Future<Output = crate::Result<Vec<JsValue>, Err>> {
        let get_req = match limit {
            None => self.sys.get_all_keys(),
            Some(limit) => self
                .sys
                .get_all_keys_with_key_and_limit(&JsValue::UNDEFINED, limit),
        };
        match get_req {
            Ok(get_req) => Either::Right(
                transaction_request(get_req).map(|res| res.map_err(map_get_err).map(array_to_vec)),
            ),
            Err(err) => Either::Left(std::future::ready(Err(map_get_err(err)))),
        }
    }

    /// List all the keys in the provided range, with a maximum number of results of `limit`
    ///
    /// Internally, this uses [`IDBObjectStore::getAllKeys`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys).
    pub fn get_all_keys_in(
        &self,
        range: impl RangeBounds<JsValue>,
        limit: Option<u32>,
    ) -> impl Future<Output = crate::Result<Vec<JsValue>, Err>> {
        let range = match make_key_range(range) {
            Ok(range) => range,
            Err(e) => return Either::Left(std::future::ready(Err(e))),
        };
        let get_req = match limit {
            None => self.sys.get_all_keys_with_key(&range),
            Some(limit) => self.sys.get_all_keys_with_key_and_limit(&range, limit),
        };
        match get_req {
            Ok(get_req) => Either::Right(
                transaction_request(get_req).map(|res| res.map_err(map_get_err).map(array_to_vec)),
            ),
            Err(err) => Either::Left(std::future::ready(Err(map_get_err(err)))),
        }
    }

    /// Get the [`Index`] with the provided name
    ///
    /// Internally, this uses [`IDBObjectStore::index`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/index).
    pub fn index(&self, name: &str) -> crate::Result<Index<Err>, Err> {
        Ok(Index::from_sys(self.sys.index(name).map_err(
            |err| match error_name!(&err) {
                Some("InvalidStateError") => crate::Error::ObjectStoreWasRemoved,
                Some("NotFoundError") => crate::Error::DoesNotExist,
                _ => crate::Error::from_js_value(err),
            },
        )?))
    }

    /// Open a [`Cursor`] on this object store
    pub fn cursor(&self) -> CursorBuilder<Err> {
        CursorBuilder::from_store(self.sys.clone())
    }
}

/// Helper to build indexes over an [`ObjectStore`]
pub struct IndexBuilder<'a, Err> {
    store: IdbObjectStore,
    name: &'a str,
    key_path: JsValue,
    options: IdbIndexParameters,
    _phantom: PhantomData<Err>,
}

impl<'a, Err> IndexBuilder<'a, Err> {
    /// Create the index
    ///
    /// Internally, this uses [`IDBObjectStore::createIndex`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex).
    pub fn create(self) -> crate::Result<(), Err> {
        self.store
            .create_index_with_str_sequence_and_optional_parameters(
                self.name,
                &self.key_path,
                &self.options,
            )
            .map_err(|err| match error_name!(&err) {
                Some("ConstraintError") => crate::Error::AlreadyExists,
                Some("InvalidAccessError") => crate::Error::InvalidArgument,
                Some("InvalidStateError") => crate::Error::ObjectStoreWasRemoved,
                Some("SyntaxError") => crate::Error::InvalidKey,
                _ => crate::Error::from_js_value(err),
            })
            .map(|_| ())
    }

    /// Mark this index as unique
    ///
    /// Internally, this sets [this property](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex#unique).
    pub fn unique(self) -> Self {
        self.options.set_unique(true);
        self
    }

    /// Mark this index as multi-entry
    ///
    /// Internally, this sets [this property](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex#multientry).
    pub fn multi_entry(self) -> Self {
        self.options.set_multi_entry(true);
        self
    }
}