Skip to main content

script/dom/indexeddb/
idbobjectstore.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4use std::cell::Cell;
5use std::collections::HashMap;
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use js::conversions::ToJSValConvertible;
10use js::gc::MutableHandleValue;
11use js::jsval::NullValue;
12use js::rust::HandleValue;
13use script_bindings::cell::DomRefCell;
14use script_bindings::codegen::GenericBindings::IDBObjectStoreBinding::IDBIndexParameters;
15use script_bindings::codegen::GenericUnionTypes::StringOrStringSequence;
16use script_bindings::error::ErrorResult;
17use script_bindings::reflector::{Reflector, reflect_dom_object_with_cx};
18use servo_base::generic_channel::{GenericSend, GenericSender};
19use storage_traits::indexeddb::{
20    self, AsyncOperation, AsyncReadOnlyOperation, AsyncReadWriteOperation, IndexedDBKeyType,
21    IndexedDBThreadMsg, SyncOperation,
22};
23
24use crate::dom::bindings::codegen::Bindings::IDBCursorBinding::IDBCursorDirection;
25use crate::dom::bindings::codegen::Bindings::IDBDatabaseBinding::IDBObjectStoreParameters;
26use crate::dom::bindings::codegen::Bindings::IDBObjectStoreBinding::IDBObjectStoreMethods;
27use crate::dom::bindings::codegen::Bindings::IDBTransactionBinding::{
28    IDBTransactionMethods, IDBTransactionMode,
29};
30// We need to alias this name, otherwise test-tidy complains at &String reference.
31use crate::dom::bindings::codegen::UnionTypes::StringOrStringSequence as StrOrStringSequence;
32use crate::dom::bindings::error::{Error, Fallible};
33use crate::dom::bindings::refcounted::Trusted;
34use crate::dom::bindings::reflector::DomGlobal;
35use crate::dom::bindings::root::{Dom, DomRoot};
36use crate::dom::bindings::str::DOMString;
37use crate::dom::bindings::structuredclone;
38use crate::dom::domstringlist::DOMStringList;
39use crate::dom::globalscope::GlobalScope;
40use crate::dom::indexeddb::idbcursor::{IDBCursor, IterationParam, ObjectStoreOrIndex};
41use crate::dom::indexeddb::idbcursorwithvalue::IDBCursorWithValue;
42use crate::dom::indexeddb::idbindex::IDBIndex;
43use crate::dom::indexeddb::idbrequest::IDBRequest;
44use crate::dom::indexeddb::idbtransaction::IDBTransaction;
45use crate::indexeddb::{
46    ExtractionResult, can_inject_key_into_value, convert_value_to_key, convert_value_to_key_range,
47    extract_key, inject_key_into_value, is_valid_key_path,
48};
49
50#[derive(Clone, JSTraceable, MallocSizeOf)]
51pub enum KeyPath {
52    String(DOMString),
53    StringSequence(Vec<DOMString>),
54}
55
56impl From<StringOrStringSequence> for KeyPath {
57    fn from(value: StringOrStringSequence) -> Self {
58        match value {
59            StringOrStringSequence::String(s) => KeyPath::String(s),
60            StringOrStringSequence::StringSequence(ss) => KeyPath::StringSequence(ss),
61        }
62    }
63}
64
65impl From<indexeddb::KeyPath> for KeyPath {
66    fn from(value: indexeddb::KeyPath) -> Self {
67        match value {
68            indexeddb::KeyPath::String(string) => KeyPath::String(string.into()),
69            indexeddb::KeyPath::Sequence(ss) => {
70                KeyPath::StringSequence(ss.into_iter().map(Into::into).collect())
71            },
72        }
73    }
74}
75
76impl From<KeyPath> for indexeddb::KeyPath {
77    fn from(item: KeyPath) -> Self {
78        match item {
79            KeyPath::String(s) => Self::String(String::from(s)),
80            KeyPath::StringSequence(ss) => {
81                Self::Sequence(ss.into_iter().map(String::from).collect())
82            },
83        }
84    }
85}
86
87#[derive(Clone, JSTraceable, MallocSizeOf)]
88struct IDBObjectStoreRollbackState {
89    newly_created_during_transaction: bool,
90    rollback_name: Option<DOMString>,
91    #[no_trace]
92    rollback_indexes: Vec<indexeddb::IndexedDBIndex>,
93    key_generator_current_number: Option<i64>,
94}
95
96#[dom_struct]
97pub struct IDBObjectStore {
98    reflector_: Reflector,
99    name: DomRefCell<DOMString>,
100    key_path: Option<KeyPath>,
101    index_set: DomRefCell<HashMap<DOMString, Dom<IDBIndex>>>,
102    abort_state_on_abort: DomRefCell<Option<IDBObjectStoreRollbackState>>,
103    transaction: Dom<IDBTransaction>,
104    has_key_generator: bool,
105    key_generator_current_number: Cell<Option<i64>>,
106
107    // We store the db name in the object store to address backend operations
108    // that are keyed by (origin, database name, object store name).
109    db_name: DOMString,
110}
111
112pub(crate) struct IDBObjectStoreAbortState {
113    pub(crate) newly_created_during_transaction: bool,
114    pub(crate) rollback_indexes_on_abort: Vec<indexeddb::IndexedDBIndex>,
115    pub(crate) key_generator_current_number: Option<i64>,
116}
117
118impl IDBObjectStore {
119    pub fn new_inherited(
120        db_name: DOMString,
121        name: DOMString,
122        options: Option<&IDBObjectStoreParameters>,
123        abort_state: IDBObjectStoreAbortState,
124        transaction: &IDBTransaction,
125    ) -> IDBObjectStore {
126        let key_path: Option<KeyPath> = match options {
127            Some(options) => options.keyPath.as_ref().map(|path| match path {
128                StrOrStringSequence::String(inner) => KeyPath::String(inner.clone()),
129                StrOrStringSequence::StringSequence(inner) => {
130                    KeyPath::StringSequence(inner.clone())
131                },
132            }),
133            None => None,
134        };
135        let has_key_generator = options.is_some_and(|options| options.autoIncrement);
136        let IDBObjectStoreAbortState {
137            newly_created_during_transaction,
138            rollback_indexes_on_abort,
139            key_generator_current_number,
140        } = abort_state;
141        let key_generator_current_number = if has_key_generator {
142            Some(key_generator_current_number.unwrap_or(1))
143        } else {
144            None
145        };
146
147        IDBObjectStore {
148            reflector_: Reflector::new(),
149            name: DomRefCell::new(name),
150            key_path,
151            index_set: DomRefCell::new(HashMap::new()),
152            abort_state_on_abort: DomRefCell::new(Some(IDBObjectStoreRollbackState {
153                newly_created_during_transaction,
154                rollback_name: None,
155                rollback_indexes: rollback_indexes_on_abort,
156                key_generator_current_number,
157            })),
158            transaction: Dom::from_ref(transaction),
159            has_key_generator,
160            key_generator_current_number: Cell::new(key_generator_current_number),
161            db_name,
162        }
163    }
164
165    pub fn new(
166        cx: &mut JSContext,
167        global: &GlobalScope,
168        db_name: DOMString,
169        name: DOMString,
170        options: Option<&IDBObjectStoreParameters>,
171        abort_state: IDBObjectStoreAbortState,
172        transaction: &IDBTransaction,
173    ) -> DomRoot<IDBObjectStore> {
174        reflect_dom_object_with_cx(
175            Box::new(IDBObjectStore::new_inherited(
176                db_name,
177                name,
178                options,
179                abort_state,
180                transaction,
181            )),
182            global,
183            cx,
184        )
185    }
186
187    pub fn get_name(&self) -> DOMString {
188        self.name.borrow().clone()
189    }
190
191    /// <https://w3c.github.io/IndexedDB/#abort-an-upgrade-transaction>
192    pub(crate) fn restore_metadata_after_abort(&self, cx: &mut JSContext) {
193        let Some(abort_state) = self.abort_state_on_abort.borrow().as_ref().cloned() else {
194            return;
195        };
196
197        // Step 5.1. If handle’s object store was not newly created during transaction,
198        // set handle’s name to its object store’s name.
199        if !abort_state.newly_created_during_transaction &&
200            let Some(name) = abort_state.rollback_name
201        {
202            *self.name.borrow_mut() = name;
203        }
204
205        // Step 5.2. Set handle’s index set to the set of indexes that reference
206        // its object store.
207        self.index_set.borrow_mut().clear();
208        for index in abort_state.rollback_indexes {
209            self.add_index(
210                cx,
211                index.name.clone().into(),
212                &IDBIndexParameters {
213                    multiEntry: index.multi_entry,
214                    unique: index.unique,
215                },
216                index.key_path.clone().into(),
217            );
218        }
219
220        // Restore key generator state for existing object store handles.
221        if self.has_key_generator && !abort_state.newly_created_during_transaction {
222            self.key_generator_current_number
223                .set(abort_state.key_generator_current_number);
224        }
225    }
226
227    pub(crate) fn transaction(&self) -> DomRoot<IDBTransaction> {
228        self.transaction.as_rooted()
229    }
230
231    fn get_idb_thread(&self) -> GenericSender<IndexedDBThreadMsg> {
232        self.global().storage_threads().sender()
233    }
234
235    /// <https://www.w3.org/TR/IndexedDB-3/#clone>
236    fn clone_value_in_target_realm(
237        &self,
238        cx: &mut JSContext,
239        value: HandleValue,
240        clone: MutableHandleValue<'_>,
241    ) -> Fallible<()> {
242        // Step 1. Assert: transaction's state is active.
243        debug_assert!(self.transaction.is_active());
244
245        // Step 2. Set transaction's state to inactive.
246        //
247        // NOTE: The transaction is made inactive so that getters or other side
248        // effects triggered by the cloning operation are unable to make
249        // additional requests against the transaction.
250        self.transaction.set_active_flag(false);
251
252        let result = (|| {
253            // Step 3. Let serialized be ? StructuredSerializeForStorage(value).
254            let serialized = structuredclone::write(cx, value, None)?;
255
256            // Step 4. Let clone be ? StructuredDeserialize(serialized, targetRealm).
257            let _ = structuredclone::read(cx, &self.global(), serialized, clone)?;
258            Ok(())
259        })();
260
261        // Step 5. Set transaction's state to active.
262        self.transaction.set_active_flag(true);
263
264        // Step 6. Return clone.
265        result
266    }
267
268    fn has_key_generator(&self) -> bool {
269        self.has_key_generator
270    }
271
272    /// <https://w3c.github.io/IndexedDB/#generate-a-key>
273    fn generate_key_for_put(&self) -> Fallible<(IndexedDBKeyType, i64)> {
274        // Step 1. Let generator be store's key generator.
275        let Some(current_number) = self.key_generator_current_number.get() else {
276            return Err(Error::Data(None));
277        };
278        // Step 2. Let key be generator's current number.
279        let key = current_number as f64;
280        // Step 3. If key is greater than 2^53 (9007199254740992), then return failure.
281        if key > 9_007_199_254_740_992.0 {
282            return Err(Error::Constraint(None));
283        }
284        // Step 4. Increase generator's current number by 1.
285        let next_current_number = current_number
286            .checked_add(1)
287            .ok_or(Error::Constraint(None))?;
288        // Step 5. Return key.
289        Ok((IndexedDBKeyType::Number(key), next_current_number))
290    }
291
292    /// <https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator>
293    fn possibly_update_the_key_generator(&self, key: &IndexedDBKeyType) -> Option<i64> {
294        // Step 1. If the type of key is not number, abort these steps.
295        let IndexedDBKeyType::Number(number) = key else {
296            return None;
297        };
298
299        // Step 2. Let value be the value of key.
300        let mut value = *number;
301        // Step 3. Set value to the minimum of value and 2^53 (9007199254740992).
302        value = value.min(9_007_199_254_740_992.0);
303        // Step 4. Set value to the largest integer not greater than value.
304        value = value.floor();
305        // Step 5. Let generator be store's key generator.
306        let current_number = self.key_generator_current_number.get()?;
307        // Step 6. If value is greater than or equal to generator's current number,
308        // then set generator's current number to value + 1.
309        if value < current_number as f64 {
310            return None;
311        }
312
313        let next = value + 1.0;
314        if next > i64::MAX as f64 {
315            return Some(i64::MAX);
316        }
317        Some(next as i64)
318    }
319
320    /// <https://www.w3.org/TR/IndexedDB-3/#object-store-in-line-keys>
321    fn uses_inline_keys(&self) -> bool {
322        self.key_path.is_some()
323    }
324
325    fn verify_not_deleted(&self) -> ErrorResult {
326        let db = self.transaction.Db();
327        if !db.object_store_exists(&self.name.borrow()) {
328            return Err(Error::InvalidState(None));
329        }
330        Ok(())
331    }
332
333    /// Checks if the transaction is active, throwing a "TransactionInactiveError" DOMException if not.
334    fn check_transaction_active(&self) -> Fallible<()> {
335        // Let transaction be this object store handle's transaction.
336        let transaction = &self.transaction;
337
338        // If transaction is not active, throw a "TransactionInactiveError" DOMException.
339        // https://w3c.github.io/IndexedDB/#transaction-inactive
340        // A transaction is in this state after control returns to the event loop after its creation, and when events are not being dispatched.
341        // No requests can be made against the transaction when it is in this state.
342        if !transaction.is_active() || !transaction.is_usable() {
343            return Err(Error::TransactionInactive(None));
344        }
345
346        Ok(())
347    }
348
349    /// Checks if the transaction is active, throwing a "TransactionInactiveError" DOMException if not.
350    /// it then checks if the transaction is a read-only transaction, throwing a "ReadOnlyError" DOMException if so.
351    fn check_readwrite_transaction_active(&self) -> Fallible<()> {
352        // Let transaction be this object store handle's transaction.
353        let transaction = &self.transaction;
354
355        // If transaction is not active, throw a "TransactionInactiveError" DOMException.
356        self.check_transaction_active()?;
357
358        if let IDBTransactionMode::Readonly = transaction.get_mode() {
359            return Err(Error::ReadOnly(None));
360        }
361        Ok(())
362    }
363
364    /// <https://www.w3.org/TR/IndexedDB-3/#add-or-put>
365    fn put(
366        &self,
367        cx: &mut JSContext,
368        value: HandleValue,
369        key: HandleValue,
370        no_overwrite: bool,
371    ) -> Fallible<DomRoot<IDBRequest>> {
372        // Step 1. Let transaction be handle’s transaction.
373        // Step 2. Let store be handle’s object store.
374        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
375        self.verify_not_deleted()?;
376
377        // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
378        // Step 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.
379        self.check_readwrite_transaction_active()?;
380
381        // Step 6. If store uses in-line keys and key was given, throw a "DataError"
382        // DOMException.
383        if !key.is_undefined() && self.uses_inline_keys() {
384            return Err(Error::Data(None));
385        }
386
387        // Step 7. If store uses out-of-line keys and has no key generator and key
388        // was not given, throw a "DataError" DOMException.
389        if !self.uses_inline_keys() && !self.has_key_generator() && key.is_undefined() {
390            return Err(Error::Data(None));
391        }
392
393        // Step 8. If key was given, then:
394        let mut serialized_key = None;
395        let mut key_generator_current_number_for_put = None;
396
397        if !key.is_undefined() {
398            // Step 8.1. Let r be the result of converting a value to a key with key.
399            // Rethrow any exceptions.
400            let key = convert_value_to_key(cx, key, None)?.into_result()?;
401            // Step 8.2. If r is "invalid value" or "invalid type", throw a
402            // "DataError" DOMException.
403            // Handled by `into_result()` above.
404            // Step 8.3. Let key be r.
405            key_generator_current_number_for_put = self.possibly_update_the_key_generator(&key);
406            serialized_key = Some(key);
407        }
408
409        // Step 9. Let targetRealm be a user-agent defined Realm.
410        // Step 10. Let clone be a clone of value in targetRealm during transaction.
411        // Rethrow any exceptions.
412        rooted!(&in(cx) let mut cloned_js_value = NullValue());
413        self.clone_value_in_target_realm(cx, value, cloned_js_value.handle_mut())?;
414
415        // Step 11. If store uses in-line keys, then:
416        let cloned_value = match self.key_path.as_ref() {
417            Some(key_path) => {
418                // Step 11.1. Let kpk be the result of extracting a key from a value using a key
419                // path with clone and store’s key path. Rethrow any exceptions.
420                match extract_key(cx, cloned_js_value.handle(), key_path, None)? {
421                    // Step 11.2. If kpk is invalid, throw a "DataError" DOMException.
422                    ExtractionResult::Invalid => return Err(Error::Data(None)),
423                    // Step 11.3. If kpk is not failure, let key be kpk.
424                    ExtractionResult::Key(kpk) => {
425                        key_generator_current_number_for_put =
426                            self.possibly_update_the_key_generator(&kpk);
427                        serialized_key = Some(kpk);
428                    },
429                    // Step 11.4. Otherwise (kpk is failure):
430                    ExtractionResult::Failure => {
431                        // Step 11.4.1. If store does not have a key generator, throw a
432                        // "DataError" DOMException.
433                        if !self.has_key_generator() {
434                            return Err(Error::Data(None));
435                        }
436                        let KeyPath::String(key_path) = key_path else {
437                            return Err(Error::Data(None));
438                        };
439                        // Step 11.4.2. If check that a key could be injected into a value with
440                        // clone and store’s key path return false, throw a "DataError"
441                        // DOMException.
442                        if !can_inject_key_into_value(cx, cloned_js_value.handle(), key_path)? {
443                            return Err(Error::Data(None));
444                        }
445
446                        // Prepares the generated key and injected clone here so Step 12 can
447                        // pass the final key/value pair to the storage backend.
448                        let (generated_key, next_current_number) = self.generate_key_for_put()?;
449                        if !inject_key_into_value(
450                            cx,
451                            cloned_js_value.handle(),
452                            &generated_key,
453                            key_path,
454                        )? {
455                            return Err(Error::Data(None));
456                        }
457                        serialized_key = Some(generated_key);
458                        key_generator_current_number_for_put = Some(next_current_number);
459                    },
460                }
461
462                structuredclone::write(cx, cloned_js_value.handle(), None)?
463            },
464            None => structuredclone::write(cx, cloned_js_value.handle(), None)?,
465        };
466        let Ok(serialized_value) = postcard::to_stdvec(&cloned_value) else {
467            return Err(Error::InvalidState(None));
468        };
469        // Step 12. Let operation be an algorithm to run store a record into an object store with
470        // store, clone, key, and no-overwrite flag.
471        let request = IDBRequest::execute_async(
472            cx,
473            self,
474            |callback| {
475                AsyncOperation::ReadWrite(AsyncReadWriteOperation::PutItem {
476                    callback,
477                    key: serialized_key,
478                    value: serialized_value,
479                    should_overwrite: !no_overwrite,
480                    key_generator_current_number: key_generator_current_number_for_put,
481                })
482            },
483            None,
484            None,
485        )?;
486        // Keep the in-memory key generator in sync with the queued put request.
487        if let Some(next_key_generator_current_number) = key_generator_current_number_for_put {
488            self.key_generator_current_number
489                .set(Some(next_key_generator_current_number));
490        }
491        // Step 13. Return the result (an IDBRequest) of running asynchronously execute a request
492        // with handle and operation.
493        Ok(request)
494    }
495
496    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-opencursor>
497    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-openkeycursor>
498    fn open_cursor(
499        &self,
500        cx: &mut JSContext,
501        query: HandleValue,
502        direction: IDBCursorDirection,
503        key_only: bool,
504    ) -> Fallible<DomRoot<IDBRequest>> {
505        // Step 1. Let transaction be this object store handle's transaction.
506        // Step 2. Let store be this object store handle's object store.
507
508        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
509        self.verify_not_deleted()?;
510
511        // Step 4. If transaction is not active, throw a "TransactionInactiveError" DOMException.
512        self.check_transaction_active()?;
513
514        // Step 5. Let range be the result of running the steps to convert a value to a key range
515        // with query. Rethrow any exceptions.
516        //
517        // The query parameter may be a key or an IDBKeyRange to use as the cursor's range. If null
518        // or not given, an unbounded key range is used.
519        let range = convert_value_to_key_range(cx, query, Some(false))?;
520
521        // Step 6. Let cursor be a new cursor with transaction set to transaction, an undefined
522        // position, direction set to direction, got value flag unset, and undefined key and value.
523        // The source of cursor is store. The range of cursor is range.
524        //
525        // NOTE: A cursor that has the key only flag unset implements the IDBCursorWithValue
526        // interface as well.
527        let cursor = if key_only {
528            IDBCursor::new(
529                cx,
530                &self.global(),
531                &self.transaction,
532                direction,
533                false,
534                ObjectStoreOrIndex::ObjectStore(Dom::from_ref(self)),
535                range.clone(),
536                key_only,
537            )
538        } else {
539            DomRoot::upcast(IDBCursorWithValue::new(
540                cx,
541                &self.global(),
542                &self.transaction,
543                direction,
544                false,
545                ObjectStoreOrIndex::ObjectStore(Dom::from_ref(self)),
546                range.clone(),
547                key_only,
548            ))
549        };
550
551        // Step 7. Run the steps to asynchronously execute a request and return the IDBRequest
552        // created by these steps. The steps are run with this object store handle as source and
553        // the steps to iterate a cursor as operation, using the current Realm as targetRealm, and
554        // cursor.
555        let iteration_param = IterationParam {
556            cursor: Trusted::new(&cursor),
557            key: None,
558            primary_key: None,
559            count: None,
560        };
561
562        IDBRequest::execute_async(
563            cx,
564            self,
565            |callback| {
566                AsyncOperation::ReadOnly(AsyncReadOnlyOperation::Iterate {
567                    callback,
568                    key_range: range,
569                })
570            },
571            None,
572            Some(iteration_param),
573        )
574        .inspect(|request| cursor.set_request(request))
575    }
576
577    pub(crate) fn add_index(
578        &self,
579        cx: &mut JSContext,
580        name: DOMString,
581        options: &IDBIndexParameters,
582        key_path: KeyPath,
583    ) -> DomRoot<IDBIndex> {
584        let index = IDBIndex::new(
585            cx,
586            &self.global(),
587            self,
588            name.clone(),
589            options.multiEntry,
590            options.unique,
591            key_path,
592        );
593        self.index_set
594            .borrow_mut()
595            .insert(name, Dom::from_ref(&index));
596        index
597    }
598
599    pub(crate) fn has_index(&self, name: &DOMString) -> bool {
600        self.index_set.borrow().contains_key(name)
601    }
602
603    /// The caller must ensure that the original index exists.
604    pub(crate) fn rename_index(&self, name: &DOMString, new_name: &DOMString) {
605        let rename_index_operation = SyncOperation::RenameIndex(
606            self.global().origin().immutable().clone(),
607            self.db_name.to_string(),
608            self.name.borrow().to_string(),
609            String::from(name.clone()),
610            String::from(new_name.clone()),
611        );
612        self.get_idb_thread()
613            .send(IndexedDBThreadMsg::Sync(rename_index_operation))
614            .unwrap();
615
616        // We also need to update the key in the index set
617        let index = self
618            .index_set
619            .borrow_mut()
620            .remove(name)
621            .expect("Earlier steps of the algorithm checked that the index exists")
622            .as_rooted();
623        self.index_set
624            .borrow_mut()
625            .insert(new_name.clone(), Dom::from_ref(&index));
626    }
627}
628
629impl IDBObjectStoreMethods<crate::DomTypeHolder> for IDBObjectStore {
630    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-put>
631    fn Put(
632        &self,
633        cx: &mut JSContext,
634        value: HandleValue,
635        key: HandleValue,
636    ) -> Fallible<DomRoot<IDBRequest>> {
637        // Step 1. Return the result of running add or put with this, value, key and the
638        // no-overwrite flag false.
639        self.put(cx, value, key, false)
640    }
641
642    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-add>
643    fn Add(
644        &self,
645        cx: &mut JSContext,
646        value: HandleValue,
647        key: HandleValue,
648    ) -> Fallible<DomRoot<IDBRequest>> {
649        // Step 1. Return the result of running add or put with this, value, key and the
650        // no-overwrite flag true.
651        self.put(cx, value, key, true)
652    }
653
654    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-delete>
655    fn Delete(&self, cx: &mut JSContext, query: HandleValue) -> Fallible<DomRoot<IDBRequest>> {
656        // Step 1. Let transaction be this’s transaction.
657        // Step 2. Let store be this's object store.
658        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
659        self.verify_not_deleted()?;
660
661        // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
662        // Step 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.
663        self.check_readwrite_transaction_active()?;
664
665        // Step 6. Let range be the result of running the steps to convert a value to a key range with query and null disallowed flag set. Rethrow any exceptions.
666        let serialized_query = convert_value_to_key_range(cx, query, Some(true));
667        // Step 7. Let operation be an algorithm to run delete records from an object store with store and range.
668        // Step 8. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.
669        serialized_query.and_then(|key_range| {
670            IDBRequest::execute_async(
671                cx,
672                self,
673                |callback| {
674                    AsyncOperation::ReadWrite(AsyncReadWriteOperation::RemoveItem {
675                        callback,
676                        key_range,
677                    })
678                },
679                None,
680                None,
681            )
682        })
683    }
684
685    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-clear>
686    fn Clear(&self, cx: &mut JSContext) -> Fallible<DomRoot<IDBRequest>> {
687        // Step 1. Let transaction be this’s transaction.
688        // Step 2. Let store be this's object store.
689        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
690        self.verify_not_deleted()?;
691
692        // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
693        // Step 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.
694        self.check_readwrite_transaction_active()?;
695
696        // Step 6. Let operation be an algorithm to run clear an object store with store.
697        // Step 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.
698        IDBRequest::execute_async(
699            cx,
700            self,
701            |callback| AsyncOperation::ReadWrite(AsyncReadWriteOperation::Clear(callback)),
702            None,
703            None,
704        )
705    }
706
707    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-get>
708    fn Get(&self, cx: &mut JSContext, query: HandleValue) -> Fallible<DomRoot<IDBRequest>> {
709        // Step 1. Let transaction be this’s transaction.
710        // Step 2. Let store be this's object store.
711        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
712        self.verify_not_deleted()?;
713
714        // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
715        self.check_transaction_active()?;
716
717        // Step 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.
718        let serialized_query = convert_value_to_key_range(cx, query, Some(true));
719
720        // Step 6. Let operation be an algorithm to run retrieve a value from an object store with the current Realm record, store, and range.
721        // Step 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.
722        serialized_query.and_then(|q| {
723            IDBRequest::execute_async(
724                cx,
725                self,
726                |callback| {
727                    AsyncOperation::ReadOnly(AsyncReadOnlyOperation::GetItem {
728                        callback,
729                        key_range: q,
730                    })
731                },
732                None,
733                None,
734            )
735        })
736    }
737
738    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-getkey>
739    fn GetKey(&self, cx: &mut JSContext, query: HandleValue) -> Result<DomRoot<IDBRequest>, Error> {
740        // Step 1. Let transaction be this’s transaction.
741        // Step 2. Let store be this's object store.
742        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
743        self.verify_not_deleted()?;
744
745        // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
746        self.check_transaction_active()?;
747
748        // Step 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.
749        let serialized_query = convert_value_to_key_range(cx, query, Some(true));
750
751        // Step 6. Run the steps to asynchronously execute a request and return the IDBRequest created by these steps.
752        // The steps are run with this object store handle as source and the steps to retrieve a key from an object
753        // store as operation, using store and range.
754        serialized_query.and_then(|q| {
755            IDBRequest::execute_async(
756                cx,
757                self,
758                |callback| {
759                    AsyncOperation::ReadOnly(AsyncReadOnlyOperation::GetKey {
760                        callback,
761                        key_range: q,
762                    })
763                },
764                None,
765                None,
766            )
767        })
768    }
769
770    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-getall>
771    fn GetAll(
772        &self,
773        cx: &mut JSContext,
774        query: HandleValue,
775        count: Option<u32>,
776    ) -> Fallible<DomRoot<IDBRequest>> {
777        // Step 1. Let transaction be this’s transaction.
778        // Step 2. Let store be this's object store.
779        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
780        self.verify_not_deleted()?;
781
782        // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
783        self.check_transaction_active()?;
784
785        // Step 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.
786        let serialized_query = convert_value_to_key_range(cx, query, None);
787
788        // Step 6. Run the steps to asynchronously execute a request and return the IDBRequest created by these steps.
789        // The steps are run with this object store handle as source and the steps to retrieve a key from an object
790        // store as operation, using store and range.
791        serialized_query.and_then(|q| {
792            IDBRequest::execute_async(
793                cx,
794                self,
795                |callback| {
796                    AsyncOperation::ReadOnly(AsyncReadOnlyOperation::GetAllItems {
797                        callback,
798                        key_range: q,
799                        count,
800                    })
801                },
802                None,
803                None,
804            )
805        })
806    }
807
808    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-getallkeys>
809    fn GetAllKeys(
810        &self,
811        cx: &mut JSContext,
812        query: HandleValue,
813        count: Option<u32>,
814    ) -> Fallible<DomRoot<IDBRequest>> {
815        // Step 1. Let transaction be this’s transaction.
816        // Step 2. Let store be this's object store.
817        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
818        self.verify_not_deleted()?;
819
820        // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
821        self.check_transaction_active()?;
822
823        // Step 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.
824        let serialized_query = convert_value_to_key_range(cx, query, None);
825
826        // Step 6. Run the steps to asynchronously execute a request and return the IDBRequest created by these steps.
827        // The steps are run with this object store handle as source and the steps to retrieve a key from an object
828        // store as operation, using store and range.
829        serialized_query.and_then(|q| {
830            IDBRequest::execute_async(
831                cx,
832                self,
833                |callback| {
834                    AsyncOperation::ReadOnly(AsyncReadOnlyOperation::GetAllKeys {
835                        callback,
836                        key_range: q,
837                        count,
838                    })
839                },
840                None,
841                None,
842            )
843        })
844    }
845
846    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-count>
847    fn Count(&self, cx: &mut JSContext, query: HandleValue) -> Fallible<DomRoot<IDBRequest>> {
848        // Step 1. Let transaction be this’s transaction.
849        // Step 2. Let store be this's object store.
850        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
851        self.verify_not_deleted()?;
852
853        // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
854        self.check_transaction_active()?;
855
856        // Step 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.
857        let serialized_query = convert_value_to_key_range(cx, query, None);
858
859        // Step 6. Let operation be an algorithm to run count the records in a range with store and range.
860        // Step 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.
861        serialized_query.and_then(|q| {
862            IDBRequest::execute_async(
863                cx,
864                self,
865                |callback| {
866                    AsyncOperation::ReadOnly(AsyncReadOnlyOperation::Count {
867                        callback,
868                        key_range: q,
869                    })
870                },
871                None,
872                None,
873            )
874        })
875    }
876
877    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-opencursor>
878    fn OpenCursor(
879        &self,
880        cx: &mut JSContext,
881        query: HandleValue,
882        direction: IDBCursorDirection,
883    ) -> Fallible<DomRoot<IDBRequest>> {
884        self.open_cursor(cx, query, direction, false)
885    }
886
887    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-openkeycursor>
888    fn OpenKeyCursor(
889        &self,
890        cx: &mut JSContext,
891        query: HandleValue,
892        direction: IDBCursorDirection,
893    ) -> Fallible<DomRoot<IDBRequest>> {
894        self.open_cursor(cx, query, direction, true)
895    }
896
897    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-name>
898    fn Name(&self) -> DOMString {
899        self.name.borrow().clone()
900    }
901
902    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-name>
903    fn SetName(&self, value: DOMString) -> ErrorResult {
904        // Step 1. Let name be the given value.
905        let name = value;
906
907        // Step 2. Let transaction be this’s transaction.
908        let transaction = &self.transaction;
909
910        // Step 3. Let store be this’s object store.
911        // Step 4. If store has been deleted, throw an "InvalidStateError" DOMException.
912        self.verify_not_deleted()?;
913
914        // Step 5. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.
915        if transaction.Mode() != IDBTransactionMode::Versionchange {
916            return Err(Error::InvalidState(None));
917        }
918        // Step 6. If transaction’s state is not active, throw a "TransactionInactiveError" DOMException.
919        self.check_transaction_active()?;
920
921        // Step 7. If store’s name is equal to name, terminate these steps.
922        if *self.name.borrow() == name {
923            return Ok(());
924        }
925
926        // Step 8. If an object store named name already exists in store’s database,
927        // throw a "ConstraintError" DOMException.
928        if transaction.Db().object_store_exists(&name) {
929            return Err(Error::Constraint(None));
930        }
931
932        let old_name = self.name.borrow().clone();
933        if let Some(abort_state) = self.abort_state_on_abort.borrow_mut().as_mut() &&
934            abort_state.rollback_name.is_none()
935        {
936            abort_state.rollback_name = Some(old_name.clone());
937        }
938
939        // Step 9. Set store’s name to name.
940        transaction
941            .Db()
942            .rename_object_store_name(&old_name, name.clone());
943        // Step 10. Set this’s name to name.
944        *self.name.borrow_mut() = name.clone();
945        transaction.rename_object_store_handle_cache(&old_name, &name, self);
946        Ok(())
947    }
948
949    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-keypath>
950    fn KeyPath(&self, cx: &mut JSContext, mut ret_val: MutableHandleValue) {
951        match &self.key_path {
952            Some(KeyPath::String(path)) => path.safe_to_jsval(cx, ret_val),
953            Some(KeyPath::StringSequence(paths)) => paths.safe_to_jsval(cx, ret_val),
954            None => ret_val.set(NullValue()),
955        }
956    }
957
958    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-indexnames>
959    fn IndexNames(&self, cx: &mut JSContext) -> DomRoot<DOMStringList> {
960        DOMStringList::new_sorted(cx, &self.global(), self.index_set.borrow().keys())
961    }
962
963    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-transaction>
964    fn Transaction(&self) -> DomRoot<IDBTransaction> {
965        self.transaction()
966    }
967
968    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-autoincrement>
969    fn AutoIncrement(&self) -> bool {
970        self.has_key_generator()
971    }
972
973    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-createindex>
974    fn CreateIndex(
975        &self,
976        cx: &mut JSContext,
977        name: DOMString,
978        key_path: StringOrStringSequence,
979        options: &IDBIndexParameters,
980    ) -> Fallible<DomRoot<IDBIndex>> {
981        let key_path: KeyPath = key_path.into();
982        // Step 3. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.
983        if self.transaction.Mode() != IDBTransactionMode::Versionchange {
984            return Err(Error::InvalidState(None));
985        }
986
987        // Step 4. If store has been deleted, throw an "InvalidStateError" DOMException.
988        self.verify_not_deleted()?;
989        // Step 5. If transaction is not active, throw a "TransactionInactiveError" DOMException.
990        self.check_transaction_active()?;
991
992        // Step 6. If an index named name already exists in store, throw a "ConstraintError" DOMException.
993        if self.has_index(&name) {
994            return Err(Error::Constraint(None));
995        }
996
997        let js_key_path = match key_path.clone() {
998            KeyPath::String(s) => StringOrStringSequence::String(s),
999            KeyPath::StringSequence(s) => StringOrStringSequence::StringSequence(s),
1000        };
1001
1002        // Step 7. If keyPath is not a valid key path, throw a "SyntaxError" DOMException.
1003        if !is_valid_key_path(cx, &js_key_path)? {
1004            return Err(Error::Syntax(None));
1005        }
1006        // Step 8. Let unique be set if options’s unique member is true, and unset otherwise.
1007        // Step 9. Let multiEntry be set if options’s multiEntry member is true, and unset otherwise.
1008        // Step 10. If keyPath is a sequence and multiEntry is set, throw an "InvalidAccessError" DOMException.
1009        if matches!(key_path, KeyPath::StringSequence(_)) && options.multiEntry {
1010            return Err(Error::InvalidAccess(None));
1011        }
1012
1013        // Step 11. Let index be a new index in store.
1014        // Set index’s name to name and key path to keyPath. If unique is set, set index’s unique flag.
1015        // If multiEntry is set, set index’s multiEntry flag.
1016        let create_index_operation = SyncOperation::CreateIndex(
1017            self.global().origin().immutable().clone(),
1018            self.db_name.to_string(),
1019            self.name.borrow().to_string(),
1020            name.to_string(),
1021            key_path.clone().into(),
1022            options.unique,
1023            options.multiEntry,
1024        );
1025        if self
1026            .get_idb_thread()
1027            .send(IndexedDBThreadMsg::Sync(create_index_operation))
1028            .is_err()
1029        {
1030            return Err(Error::Operation(None));
1031        }
1032
1033        // Step 12. Add index to this object store handle's index set.
1034        let index = self.add_index(cx, name, options, key_path);
1035
1036        // Step 13. Return a new index handle associated with index and this object store handle.
1037        Ok(index)
1038    }
1039
1040    /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-deleteindex>
1041    fn DeleteIndex(&self, name: DOMString) -> Fallible<()> {
1042        // Step 3. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.
1043        if self.transaction.Mode() != IDBTransactionMode::Versionchange {
1044            return Err(Error::InvalidState(None));
1045        }
1046        // Step 4. If store has been deleted, throw an "InvalidStateError" DOMException.
1047        self.verify_not_deleted()?;
1048        // Step 5. If transaction is not active, throw a "TransactionInactiveError" DOMException.
1049        self.check_transaction_active()?;
1050        // Step 6. Let index be the index named name in store if one exists,
1051        // or throw a "NotFoundError" DOMException otherwise.
1052        if !self.index_set.borrow().contains_key(&name) {
1053            return Err(Error::NotFound(None));
1054        }
1055        // Step 7. Remove index from this object store handle's index set.
1056        self.index_set.borrow_mut().retain(|n, _| n != &name);
1057        // Step 8. Destroy index.
1058        let delete_index_operation = SyncOperation::DeleteIndex(
1059            self.global().origin().immutable().clone(),
1060            self.db_name.to_string(),
1061            self.name.borrow().to_string(),
1062            String::from(name),
1063        );
1064        self.get_idb_thread()
1065            .send(IndexedDBThreadMsg::Sync(delete_index_operation))
1066            .unwrap();
1067        Ok(())
1068    }
1069
1070    /// <https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index>
1071    fn Index(&self, name: DOMString) -> Fallible<DomRoot<IDBIndex>> {
1072        // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
1073        self.verify_not_deleted()?;
1074
1075        // Step 4. If the transaction's state is finished, then throw an "InvalidStateError" DOMException.
1076        if self.transaction.is_finished() {
1077            return Err(Error::InvalidState(None));
1078        }
1079
1080        // Step 5. Let index be the index named name in this’s index set if one exists, or throw a "NotFoundError" DOMException otherwise.
1081        let index_set = self.index_set.borrow();
1082        let index = index_set.get(&name).ok_or(Error::NotFound(None))?;
1083
1084        // Step 6. Return an index handle associated with index and this.
1085        Ok(index.as_rooted())
1086    }
1087}