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
use crate::{
transaction::transaction_request,
utils::{
make_key_range, map_cursor_advance_err, map_cursor_advance_until_err,
map_cursor_advance_until_primary_key_err, map_cursor_delete_err, map_cursor_update_err,
map_open_cursor_err,
},
};
use futures_util::future::Either;
use std::{future::Future, marker::PhantomData, ops::RangeBounds};
use web_sys::{
wasm_bindgen::{JsCast, JsValue},
IdbCursor, IdbCursorDirection, IdbCursorWithValue, IdbIndex, IdbObjectStore, IdbRequest,
};
#[cfg(doc)]
use crate::{Index, ObjectStore};
#[cfg(doc)]
use web_sys::js_sys::Array;
/// The direction for a cursor
pub enum CursorDirection {
/// Advance one by one
Next,
/// Advance, skipping duplicate elements
NextUnique,
/// Go back, one by one
Prev,
/// Go back, skipping duplicate elements
PrevUnique,
}
impl CursorDirection {
pub(crate) fn to_sys(&self) -> IdbCursorDirection {
match self {
CursorDirection::Next => IdbCursorDirection::Next,
CursorDirection::NextUnique => IdbCursorDirection::Nextunique,
CursorDirection::Prev => IdbCursorDirection::Prev,
CursorDirection::PrevUnique => IdbCursorDirection::Prevunique,
}
}
}
/// Helper to build cursors over [`ObjectStore`]s
pub struct CursorBuilder<Err> {
source: Either<IdbObjectStore, IdbIndex>,
query: JsValue,
direction: IdbCursorDirection,
_phantom: PhantomData<Err>,
}
impl<Err> CursorBuilder<Err> {
pub(crate) fn from_store(store: IdbObjectStore) -> CursorBuilder<Err> {
CursorBuilder {
source: Either::Left(store),
query: JsValue::UNDEFINED,
direction: IdbCursorDirection::Next,
_phantom: PhantomData,
}
}
pub(crate) fn from_index(index: IdbIndex) -> CursorBuilder<Err> {
CursorBuilder {
source: Either::Right(index),
query: JsValue::UNDEFINED,
direction: IdbCursorDirection::Next,
_phantom: PhantomData,
}
}
/// Open the cursor
///
/// Internally, this uses [`IDBObjectStore::openCursor`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/openCursor).
pub fn open(self) -> impl Future<Output = crate::Result<Cursor<Err>, Err>> {
let req = match self.source {
Either::Left(store) => {
store.open_cursor_with_range_and_direction(&self.query, self.direction)
}
Either::Right(index) => {
index.open_cursor_with_range_and_direction(&self.query, self.direction)
}
};
match req {
Ok(open_req) => Either::Right(Cursor::from(open_req)),
Err(err) => Either::Left(std::future::ready(Err(map_open_cursor_err(err)))),
}
}
/// Open the cursor as a key-only cursor
///
/// Internally, this uses [`IDBObjectStore::openKeyCursor`](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/openKeyCursor).
pub fn open_key(self) -> impl Future<Output = crate::Result<Cursor<Err>, Err>> {
let req = match self.source {
Either::Left(store) => {
store.open_key_cursor_with_range_and_direction(&self.query, self.direction)
}
Either::Right(index) => {
index.open_key_cursor_with_range_and_direction(&self.query, self.direction)
}
};
match req {
Ok(open_req) => Either::Right(Cursor::from(open_req)),
Err(err) => Either::Left(std::future::ready(Err(map_open_cursor_err(err)))),
}
}
/// Limit the range of the cursor
///
/// Internally, this sets [this property](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openCursor#range).
pub fn range(mut self, range: impl RangeBounds<JsValue>) -> crate::Result<Self, Err> {
self.query = make_key_range(range)?;
Ok(self)
}
/// Define the direction of the cursor
///
/// Internally, this sets [this property](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openCursor#direction).
pub fn direction(mut self, direction: CursorDirection) -> Self {
self.direction = direction.to_sys();
self
}
}
/// Wrapper for [`IDBCursorWithValue`](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue)
pub struct Cursor<Err> {
sys: Option<IdbCursor>,
req: IdbRequest,
_phantom: PhantomData<Err>,
}
impl<Err> Cursor<Err> {
pub(crate) async fn from(req: IdbRequest) -> crate::Result<Cursor<Err>, Err> {
let res = transaction_request(req.clone())
.await
.map_err(map_open_cursor_err)?;
let is_already_over = res.is_null();
let sys = (!is_already_over).then(|| {
res.dyn_into::<IdbCursor>()
.expect("Cursor-returning request did not return an IDBCursor")
});
Ok(Cursor {
sys,
req,
_phantom: PhantomData,
})
}
/// Retrieve the value this [`Cursor`] is currently pointing at, or `None` if the cursor is completed
///
/// If this cursor was opened as a key-only cursor, then trying to call this method will panic.
///
/// Internally, this uses the [`IDBCursorWithValue::value`](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue/value) property.
pub fn value(&self) -> Option<JsValue> {
self.sys.as_ref().map(|sys| {
sys.dyn_ref::<IdbCursorWithValue>()
.expect("Called Cursor::value on a key-only cursor")
.value()
.expect("Unable to retrieve value from known-good cursor")
})
}
/// Retrieve the key this [`Cursor`] is currently pointing at, or `None` if the cursor is completed
///
/// Internally, this uses the [`IDBCursor::key`](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/key) property.
pub fn key(&self) -> Option<JsValue> {
self.sys.as_ref().map(|sys| {
sys.key()
.expect("Failed retrieving key from known-good cursor")
})
}
/// Retrieve the primary key this [`Cursor`] is currently pointing at, or `None` if the cursor is completed
///
/// Internally, this uses the [`IDBCursor::primaryKey`](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/key) property.
pub fn primary_key(&self) -> Option<JsValue> {
self.sys.as_ref().map(|sys| {
sys.primary_key()
.expect("Failed retrieving primary key from known-good cursor")
})
}
/// Advance this [`Cursor`] by `count` elements
///
/// Internally, this uses [`IDBCursor::advance`](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/advance).
pub async fn advance(&mut self, count: u32) -> crate::Result<(), Err> {
let Some(sys) = &self.sys else {
return Err(crate::Error::CursorCompleted);
};
sys.advance(count).map_err(map_cursor_advance_err)?;
if transaction_request(self.req.clone())
.await
.map_err(map_cursor_advance_err)?
.is_null()
{
self.sys = None;
}
Ok(())
}
/// Advance this [`Cursor`] until the provided key
///
/// Internally, this uses [`IDBCursor::continue`](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continue).
pub async fn advance_until(&mut self, key: &JsValue) -> crate::Result<(), Err> {
let Some(sys) = &self.sys else {
return Err(crate::Error::CursorCompleted);
};
sys.continue_with_key(key)
.map_err(map_cursor_advance_until_err)?;
if transaction_request(self.req.clone())
.await
.map_err(map_cursor_advance_until_err)?
.is_null()
{
self.sys = None;
}
Ok(())
}
/// Advance this [`Cursor`] until the provided primary key
///
/// This is a helper function for cursors built on top of [`Index`]es. It allows for
/// quick resumption of index walking, faster than [`Cursor::advance_until`] if the
/// primary key for the wanted element is known.
///
/// Note that this method does not work on cursors over object stores, nor on cursors
/// which are set with a direction of anything other than `Next` or `Prev`.
///
/// Internally, this uses [`IDBCursor::continuePrimaryKey`](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continuePrimaryKey).
pub async fn advance_until_primary_key(
&mut self,
index_key: &JsValue,
primary_key: &JsValue,
) -> crate::Result<(), Err> {
let Some(sys) = &self.sys else {
return Err(crate::Error::CursorCompleted);
};
sys.continue_primary_key(&index_key, primary_key)
.map_err(map_cursor_advance_until_primary_key_err)?;
if transaction_request(self.req.clone())
.await
.map_err(map_cursor_advance_until_primary_key_err)?
.is_null()
{
self.sys = None;
}
Ok(())
}
/// Deletes the value currently pointed by this [`Cursor`]
///
/// Note that this method does not work on key-only cursors over indexes.
///
/// Internally, this uses [`IDBCursor::delete`](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete).
pub async fn delete(&self) -> crate::Result<(), Err> {
let Some(sys) = &self.sys else {
return Err(crate::Error::CursorCompleted);
};
let req = sys.delete().map_err(map_cursor_delete_err)?;
transaction_request(req)
.await
.map_err(map_cursor_delete_err)?;
Ok(())
}
/// Update the value currently pointed by this [`Cursor`] to `value`
///
/// Note that this method does not work on key-only cursors over indexes.
///
/// Internally, this uses [`IDBCursor::update`](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/update).
pub async fn update(&self, value: &JsValue) -> crate::Result<(), Err> {
let Some(sys) = &self.sys else {
return Err(crate::Error::CursorCompleted);
};
let req = sys.update(value).map_err(map_cursor_update_err)?;
transaction_request(req)
.await
.map_err(map_cursor_update_err)?;
Ok(())
}
}