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, AsyncSchemaOperation,
21 IndexedDBKeyType, IndexedDBThreadMsg,
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 operation = AsyncSchemaOperation::RenameIndex {
606 callback: self.transaction.create_abort_callback(),
607 index_name: name.to_string(),
608 new_name: new_name.to_string(),
609 };
610
611 if self
612 .get_idb_thread()
613 .send(IndexedDBThreadMsg::AsyncSchemaOperation {
614 origin: self.global().origin().immutable().clone(),
615 database_name: self.db_name.to_string(),
616 store_name: self.name.borrow().clone().into(),
617 operation,
618 transaction_serial_number: self.transaction.get_serial_number(),
619 })
620 .is_err()
621 {
622 warn!("Could not send AsyncSchemaOperation");
623 }
624
625 // We also need to update the key in the index set
626 let index = self
627 .index_set
628 .borrow_mut()
629 .remove(name)
630 .expect("Earlier steps of the algorithm checked that the index exists")
631 .as_rooted();
632 self.index_set
633 .borrow_mut()
634 .insert(new_name.clone(), Dom::from_ref(&index));
635 }
636}
637
638impl IDBObjectStoreMethods<crate::DomTypeHolder> for IDBObjectStore {
639 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-put>
640 fn Put(
641 &self,
642 cx: &mut JSContext,
643 value: HandleValue,
644 key: HandleValue,
645 ) -> Fallible<DomRoot<IDBRequest>> {
646 // Step 1. Return the result of running add or put with this, value, key and the
647 // no-overwrite flag false.
648 self.put(cx, value, key, false)
649 }
650
651 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-add>
652 fn Add(
653 &self,
654 cx: &mut JSContext,
655 value: HandleValue,
656 key: HandleValue,
657 ) -> Fallible<DomRoot<IDBRequest>> {
658 // Step 1. Return the result of running add or put with this, value, key and the
659 // no-overwrite flag true.
660 self.put(cx, value, key, true)
661 }
662
663 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-delete>
664 fn Delete(&self, cx: &mut JSContext, query: HandleValue) -> Fallible<DomRoot<IDBRequest>> {
665 // Step 1. Let transaction be this’s transaction.
666 // Step 2. Let store be this's object store.
667 // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
668 self.verify_not_deleted()?;
669
670 // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
671 // Step 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.
672 self.check_readwrite_transaction_active()?;
673
674 // 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.
675 let serialized_query = convert_value_to_key_range(cx, query, Some(true));
676 // Step 7. Let operation be an algorithm to run delete records from an object store with store and range.
677 // Step 8. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.
678 serialized_query.and_then(|key_range| {
679 IDBRequest::execute_async(
680 cx,
681 self,
682 |callback| {
683 AsyncOperation::ReadWrite(AsyncReadWriteOperation::RemoveItem {
684 callback,
685 key_range,
686 })
687 },
688 None,
689 None,
690 )
691 })
692 }
693
694 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-clear>
695 fn Clear(&self, cx: &mut JSContext) -> Fallible<DomRoot<IDBRequest>> {
696 // Step 1. Let transaction be this’s transaction.
697 // Step 2. Let store be this's object store.
698 // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
699 self.verify_not_deleted()?;
700
701 // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
702 // Step 5. If transaction is a read-only transaction, throw a "ReadOnlyError" DOMException.
703 self.check_readwrite_transaction_active()?;
704
705 // Step 6. Let operation be an algorithm to run clear an object store with store.
706 // Step 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.
707 IDBRequest::execute_async(
708 cx,
709 self,
710 |callback| AsyncOperation::ReadWrite(AsyncReadWriteOperation::Clear(callback)),
711 None,
712 None,
713 )
714 }
715
716 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-get>
717 fn Get(&self, cx: &mut JSContext, query: HandleValue) -> Fallible<DomRoot<IDBRequest>> {
718 // Step 1. Let transaction be this’s transaction.
719 // Step 2. Let store be this's object store.
720 // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
721 self.verify_not_deleted()?;
722
723 // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
724 self.check_transaction_active()?;
725
726 // Step 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.
727 let serialized_query = convert_value_to_key_range(cx, query, Some(true));
728
729 // Step 6. Let operation be an algorithm to run retrieve a value from an object store with the current Realm record, store, and range.
730 // Step 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.
731 serialized_query.and_then(|q| {
732 IDBRequest::execute_async(
733 cx,
734 self,
735 |callback| {
736 AsyncOperation::ReadOnly(AsyncReadOnlyOperation::GetItem {
737 callback,
738 key_range: q,
739 })
740 },
741 None,
742 None,
743 )
744 })
745 }
746
747 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-getkey>
748 fn GetKey(&self, cx: &mut JSContext, query: HandleValue) -> Result<DomRoot<IDBRequest>, Error> {
749 // Step 1. Let transaction be this’s transaction.
750 // Step 2. Let store be this's object store.
751 // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
752 self.verify_not_deleted()?;
753
754 // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
755 self.check_transaction_active()?;
756
757 // Step 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.
758 let serialized_query = convert_value_to_key_range(cx, query, Some(true));
759
760 // Step 6. Run the steps to asynchronously execute a request and return the IDBRequest created by these steps.
761 // The steps are run with this object store handle as source and the steps to retrieve a key from an object
762 // store as operation, using store and range.
763 serialized_query.and_then(|q| {
764 IDBRequest::execute_async(
765 cx,
766 self,
767 |callback| {
768 AsyncOperation::ReadOnly(AsyncReadOnlyOperation::GetKey {
769 callback,
770 key_range: q,
771 })
772 },
773 None,
774 None,
775 )
776 })
777 }
778
779 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-getall>
780 fn GetAll(
781 &self,
782 cx: &mut JSContext,
783 query: HandleValue,
784 count: Option<u32>,
785 ) -> Fallible<DomRoot<IDBRequest>> {
786 // Step 1. Let transaction be this’s transaction.
787 // Step 2. Let store be this's object store.
788 // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
789 self.verify_not_deleted()?;
790
791 // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
792 self.check_transaction_active()?;
793
794 // Step 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.
795 let serialized_query = convert_value_to_key_range(cx, query, None);
796
797 // Step 6. Run the steps to asynchronously execute a request and return the IDBRequest created by these steps.
798 // The steps are run with this object store handle as source and the steps to retrieve a key from an object
799 // store as operation, using store and range.
800 serialized_query.and_then(|q| {
801 IDBRequest::execute_async(
802 cx,
803 self,
804 |callback| {
805 AsyncOperation::ReadOnly(AsyncReadOnlyOperation::GetAllItems {
806 callback,
807 key_range: q,
808 count,
809 })
810 },
811 None,
812 None,
813 )
814 })
815 }
816
817 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-getallkeys>
818 fn GetAllKeys(
819 &self,
820 cx: &mut JSContext,
821 query: HandleValue,
822 count: Option<u32>,
823 ) -> Fallible<DomRoot<IDBRequest>> {
824 // Step 1. Let transaction be this’s transaction.
825 // Step 2. Let store be this's object store.
826 // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
827 self.verify_not_deleted()?;
828
829 // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
830 self.check_transaction_active()?;
831
832 // Step 5. Let range be the result of converting a value to a key range with query and true. Rethrow any exceptions.
833 let serialized_query = convert_value_to_key_range(cx, query, None);
834
835 // Step 6. Run the steps to asynchronously execute a request and return the IDBRequest created by these steps.
836 // The steps are run with this object store handle as source and the steps to retrieve a key from an object
837 // store as operation, using store and range.
838 serialized_query.and_then(|q| {
839 IDBRequest::execute_async(
840 cx,
841 self,
842 |callback| {
843 AsyncOperation::ReadOnly(AsyncReadOnlyOperation::GetAllKeys {
844 callback,
845 key_range: q,
846 count,
847 })
848 },
849 None,
850 None,
851 )
852 })
853 }
854
855 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-count>
856 fn Count(&self, cx: &mut JSContext, query: HandleValue) -> Fallible<DomRoot<IDBRequest>> {
857 // Step 1. Let transaction be this’s transaction.
858 // Step 2. Let store be this's object store.
859 // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
860 self.verify_not_deleted()?;
861
862 // Step 4. If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
863 self.check_transaction_active()?;
864
865 // Step 5. Let range be the result of converting a value to a key range with query. Rethrow any exceptions.
866 let serialized_query = convert_value_to_key_range(cx, query, None);
867
868 // Step 6. Let operation be an algorithm to run count the records in a range with store and range.
869 // Step 7. Return the result (an IDBRequest) of running asynchronously execute a request with this and operation.
870 serialized_query.and_then(|q| {
871 IDBRequest::execute_async(
872 cx,
873 self,
874 |callback| {
875 AsyncOperation::ReadOnly(AsyncReadOnlyOperation::Count {
876 callback,
877 key_range: q,
878 })
879 },
880 None,
881 None,
882 )
883 })
884 }
885
886 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-opencursor>
887 fn OpenCursor(
888 &self,
889 cx: &mut JSContext,
890 query: HandleValue,
891 direction: IDBCursorDirection,
892 ) -> Fallible<DomRoot<IDBRequest>> {
893 self.open_cursor(cx, query, direction, false)
894 }
895
896 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-openkeycursor>
897 fn OpenKeyCursor(
898 &self,
899 cx: &mut JSContext,
900 query: HandleValue,
901 direction: IDBCursorDirection,
902 ) -> Fallible<DomRoot<IDBRequest>> {
903 self.open_cursor(cx, query, direction, true)
904 }
905
906 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-name>
907 fn Name(&self) -> DOMString {
908 self.name.borrow().clone()
909 }
910
911 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-name>
912 fn SetName(&self, value: DOMString) -> ErrorResult {
913 // Step 1. Let name be the given value.
914 let name = value;
915
916 // Step 2. Let transaction be this’s transaction.
917 let transaction = &self.transaction;
918
919 // Step 3. Let store be this’s object store.
920 // Step 4. If store has been deleted, throw an "InvalidStateError" DOMException.
921 self.verify_not_deleted()?;
922
923 // Step 5. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.
924 if transaction.Mode() != IDBTransactionMode::Versionchange {
925 return Err(Error::InvalidState(None));
926 }
927 // Step 6. If transaction’s state is not active, throw a "TransactionInactiveError" DOMException.
928 self.check_transaction_active()?;
929
930 // Step 7. If store’s name is equal to name, terminate these steps.
931 if *self.name.borrow() == name {
932 return Ok(());
933 }
934
935 // Step 8. If an object store named name already exists in store’s database,
936 // throw a "ConstraintError" DOMException.
937 if transaction.Db().object_store_exists(&name) {
938 return Err(Error::Constraint(None));
939 }
940
941 let old_name = self.name.borrow().clone();
942 if let Some(abort_state) = self.abort_state_on_abort.borrow_mut().as_mut() &&
943 abort_state.rollback_name.is_none()
944 {
945 abort_state.rollback_name = Some(old_name.clone());
946 }
947
948 // Step 9. Set store’s name to name.
949 transaction
950 .Db()
951 .rename_object_store_name(&old_name, name.clone());
952 // Step 10. Set this’s name to name.
953 *self.name.borrow_mut() = name.clone();
954 transaction.rename_object_store_handle_cache(&old_name, &name, self);
955 Ok(())
956 }
957
958 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-keypath>
959 fn KeyPath(&self, cx: &mut JSContext, mut ret_val: MutableHandleValue) {
960 match &self.key_path {
961 Some(KeyPath::String(path)) => path.safe_to_jsval(cx, ret_val),
962 Some(KeyPath::StringSequence(paths)) => paths.safe_to_jsval(cx, ret_val),
963 None => ret_val.set(NullValue()),
964 }
965 }
966
967 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-indexnames>
968 fn IndexNames(&self, cx: &mut JSContext) -> DomRoot<DOMStringList> {
969 DOMStringList::new_sorted(cx, &self.global(), self.index_set.borrow().keys())
970 }
971
972 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-transaction>
973 fn Transaction(&self) -> DomRoot<IDBTransaction> {
974 self.transaction()
975 }
976
977 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-autoincrement>
978 fn AutoIncrement(&self) -> bool {
979 self.has_key_generator()
980 }
981
982 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-createindex>
983 fn CreateIndex(
984 &self,
985 cx: &mut JSContext,
986 name: DOMString,
987 key_path: StringOrStringSequence,
988 options: &IDBIndexParameters,
989 ) -> Fallible<DomRoot<IDBIndex>> {
990 let key_path: KeyPath = key_path.into();
991 // Step 3. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.
992 if self.transaction.Mode() != IDBTransactionMode::Versionchange {
993 return Err(Error::InvalidState(None));
994 }
995
996 // Step 4. If store has been deleted, throw an "InvalidStateError" DOMException.
997 self.verify_not_deleted()?;
998 // Step 5. If transaction is not active, throw a "TransactionInactiveError" DOMException.
999 self.check_transaction_active()?;
1000
1001 // Step 6. If an index named name already exists in store, throw a "ConstraintError" DOMException.
1002 if self.has_index(&name) {
1003 return Err(Error::Constraint(None));
1004 }
1005
1006 let js_key_path = match key_path.clone() {
1007 KeyPath::String(s) => StringOrStringSequence::String(s),
1008 KeyPath::StringSequence(s) => StringOrStringSequence::StringSequence(s),
1009 };
1010
1011 // Step 7. If keyPath is not a valid key path, throw a "SyntaxError" DOMException.
1012 if !is_valid_key_path(cx, &js_key_path)? {
1013 return Err(Error::Syntax(None));
1014 }
1015 // Step 8. Let unique be set if options’s unique member is true, and unset otherwise.
1016 // Step 9. Let multiEntry be set if options’s multiEntry member is true, and unset otherwise.
1017 // Step 10. If keyPath is a sequence and multiEntry is set, throw an "InvalidAccessError" DOMException.
1018 if matches!(key_path, KeyPath::StringSequence(_)) && options.multiEntry {
1019 return Err(Error::InvalidAccess(None));
1020 }
1021
1022 // Step 11. Let index be a new index in store.
1023 // Set index’s name to name and key path to keyPath. If unique is set, set index’s unique flag.
1024 // If multiEntry is set, set index’s multiEntry flag.
1025 let operation = AsyncSchemaOperation::CreateIndex {
1026 callback: self.transaction.create_abort_callback(),
1027 index_name: name.to_string(),
1028 key_path: key_path.clone().into(),
1029 unique: options.unique,
1030 multi_entry: options.multiEntry,
1031 };
1032
1033 if self
1034 .get_idb_thread()
1035 .send(IndexedDBThreadMsg::AsyncSchemaOperation {
1036 origin: self.global().origin().immutable().clone(),
1037 database_name: self.db_name.to_string(),
1038 store_name: self.name.borrow().clone().into(),
1039 operation,
1040 transaction_serial_number: self.transaction.get_serial_number(),
1041 })
1042 .is_err()
1043 {
1044 return Err(Error::Operation(None));
1045 }
1046
1047 // Step 12. Add index to this object store handle's index set.
1048 let index = self.add_index(cx, name, options, key_path);
1049
1050 // Step 13. Return a new index handle associated with index and this object store handle.
1051 Ok(index)
1052 }
1053
1054 /// <https://www.w3.org/TR/IndexedDB-3/#dom-idbobjectstore-deleteindex>
1055 fn DeleteIndex(&self, name: DOMString) -> Fallible<()> {
1056 // Step 3. If transaction is not an upgrade transaction, throw an "InvalidStateError" DOMException.
1057 if self.transaction.Mode() != IDBTransactionMode::Versionchange {
1058 return Err(Error::InvalidState(None));
1059 }
1060 // Step 4. If store has been deleted, throw an "InvalidStateError" DOMException.
1061 self.verify_not_deleted()?;
1062 // Step 5. If transaction is not active, throw a "TransactionInactiveError" DOMException.
1063 self.check_transaction_active()?;
1064 // Step 6. Let index be the index named name in store if one exists,
1065 // or throw a "NotFoundError" DOMException otherwise.
1066 if !self.index_set.borrow().contains_key(&name) {
1067 return Err(Error::NotFound(None));
1068 }
1069 // Step 7. Remove index from this object store handle's index set.
1070 self.index_set.borrow_mut().retain(|n, _| n != &name);
1071 // Step 8. Destroy index.
1072 let operation = AsyncSchemaOperation::DeleteIndex {
1073 callback: self.transaction.create_abort_callback(),
1074 index_name: name.to_string(),
1075 };
1076 if self
1077 .get_idb_thread()
1078 .send(IndexedDBThreadMsg::AsyncSchemaOperation {
1079 origin: self.global().origin().immutable().clone(),
1080 database_name: self.db_name.to_string(),
1081 store_name: self.name.borrow().clone().into(),
1082 operation,
1083 transaction_serial_number: self.transaction.get_serial_number(),
1084 })
1085 .is_err()
1086 {
1087 return Err(Error::Operation(None));
1088 }
1089 Ok(())
1090 }
1091
1092 /// <https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index>
1093 fn Index(&self, name: DOMString) -> Fallible<DomRoot<IDBIndex>> {
1094 // Step 3. If store has been deleted, throw an "InvalidStateError" DOMException.
1095 self.verify_not_deleted()?;
1096
1097 // Step 4. If the transaction's state is finished, then throw an "InvalidStateError" DOMException.
1098 if self.transaction.is_finished() {
1099 return Err(Error::InvalidState(None));
1100 }
1101
1102 // Step 5. Let index be the index named name in this’s index set if one exists, or throw a "NotFoundError" DOMException otherwise.
1103 let index_set = self.index_set.borrow();
1104 let index = index_set.get(&name).ok_or(Error::NotFound(None))?;
1105
1106 // Step 6. Return an index handle associated with index and this.
1107 Ok(index.as_rooted())
1108 }
1109}