-
-
Notifications
You must be signed in to change notification settings - Fork 641
/
table.ts
594 lines (553 loc) · 21.2 KB
/
table.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import { BulkError, exceptions } from '../../errors';
import { Table as ITable } from '../../public/types/table';
import { TableSchema } from '../../public/types/table-schema';
import { TableHooks } from '../../public/types/table-hooks';
import { DexiePromise as Promise, PSD, newScope, rejection, beginMicroTickScope, endMicroTickScope } from '../../helpers/promise';
import { Transaction } from '../transaction';
import { Dexie } from '../dexie';
import { tempTransaction } from '../../functions/temp-transaction';
import { Collection } from '../collection';
import { isArray, keys, getByKeyPath, setByKeyPath, extend, getProto } from '../../functions/utils';
import { maxString } from '../../globals/constants';
import { combine } from '../../functions/combine';
import { PromiseExtended } from "../../public/types/promise-extended";
import { IndexableType } from '../../public/types/indexable-type';
import { debug } from '../../helpers/debug';
import { DBCoreTable } from '../../public/types/dbcore';
import { AnyRange } from '../../dbcore/keyrange';
import { workaroundForUndefinedPrimKey } from '../../functions/workaround-undefined-primkey';
import { Entity } from '../entity/Entity';
import { UpdateSpec } from '../../public';
import { cmp } from '../../functions/cmp';
/** class Table
*
* https://dexie.org/docs/Table/Table
*/
export class Table implements ITable<any, IndexableType> {
db: Dexie;
_tx?: Transaction;
name: string;
schema: TableSchema;
hook: TableHooks;
core: DBCoreTable;
_trans(
mode: IDBTransactionMode,
fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike<any> | void,
writeLocked?: boolean | string) : PromiseExtended<any>
{
const trans: Transaction = this._tx || PSD.trans;
const tableName = this.name;
// @ts-ignore: Use Chrome's Async Stack Tagging API to allow tracing and simplify debugging for dexie users.
const task = debug && typeof console !== 'undefined' && console.createTask && console.createTask(`Dexie: ${mode === 'readonly' ? 'read' : 'write' } ${this.name}`);
function checkTableInTransaction(resolve, reject, trans: Transaction) {
if (!trans.schema[tableName])
throw new exceptions.NotFound("Table " + tableName + " not part of transaction");
return fn(trans.idbtrans, trans) as Promise<any>;
}
// Surround all in a microtick scope.
// Reason: Browsers (modern Safari + older others)
// still as of 2018-10-10 has problems keeping a transaction
// alive between micro ticks. Safari because if transaction
// is created but not used in same microtick, it will go
// away. That specific issue could be solved in DBCore
// by opening the transaction just before using it instead.
// But older Firefoxes and IE11 (with Promise polyfills)
// will still have probs.
// The beginMicrotickScope()/endMicrotickScope() works
// in cooperation with Dexie.Promise to orchestrate
// the micro-ticks in endMicrotickScope() rather than
// in native engine.
const wasRootExec = beginMicroTickScope();
try {
let p = trans && trans.db._novip === this.db._novip ?
trans === PSD.trans ?
trans._promise(mode, checkTableInTransaction, writeLocked) :
newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) :
tempTransaction(this.db, mode, [this.name], checkTableInTransaction);
if (task) { // Dexie.debug = true so we trace errors
p._consoleTask = task;
p = p.catch(err => {
console.trace(err);
return rejection(err);
});
}
return p;
} finally {
if (wasRootExec) endMicroTickScope();
}
}
/** Table.get()
*
* https://dexie.org/docs/Table/Table.get()
*
**/
get(keyOrCrit, cb?) {
if (keyOrCrit && keyOrCrit.constructor === Object)
return this.where(keyOrCrit as { [key: string]: IndexableType }).first(cb);
if (keyOrCrit == null) return rejection(new exceptions.Type(`Invalid argument to Table.get()`));
return this._trans('readonly', (trans) => {
return this.core.get({trans, key: keyOrCrit})
.then(res => this.hook.reading.fire(res));
}).then(cb);
}
/** Table.where()
*
* https://dexie.org/docs/Table/Table.where()
*
**/
where(indexOrCrit: string | string[] | { [key: string]: IndexableType }) {
if (typeof indexOrCrit === 'string')
return new this.db.WhereClause(this, indexOrCrit);
if (isArray(indexOrCrit))
return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);
// indexOrCrit is an object map of {[keyPath]:value}
const keyPaths = keys(indexOrCrit);
if (keyPaths.length === 1)
// Only one critera. This was the easy case:
return this
.where(keyPaths[0])
.equals(indexOrCrit[keyPaths[0]]);
// Multiple criterias.
// Let's try finding a compound index that matches all keyPaths in
// arbritary order:
const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix => {
if (
ix.compound &&
keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) {
for (let i=0; i<keyPaths.length; ++i) {
if (keyPaths.indexOf(ix.keyPath[i]) === -1) return false;
}
return true;
}
return false;
}).sort((a,b) => a.keyPath.length - b.keyPath.length)[0];
if (compoundIndex && this.db._maxKey !== maxString) {
// Cool! We found such compound index
// and this browser supports compound indexes (maxKey !== maxString)!
const keyPathsInValidOrder = (compoundIndex.keyPath as string[]).slice(0, keyPaths.length);
return this
.where(keyPathsInValidOrder)
.equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp]));
}
if (!compoundIndex && debug) console.warn(
`The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit from a ` +
`compound index [${keyPaths.join('+')}]`);
// Ok, now let's fallback to finding at least one matching index
// and filter the rest.
const { idxByName } = this.schema;
function equals(a, b) {
return cmp(a, b) === 0; // Works with all indexable types including binary keys.
}
const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => {
const index = idxByName[keyPath];
const value = indexOrCrit[keyPath];
return [
prevIndex || index, // idx::=Pick index of first matching keypath
prevIndex || !index ? // filter::=null if not needed, otherwise combine function filter
combine(
prevFilterFn,
index && index.multi ?
x => {
const prop = getByKeyPath(x, keyPath);
return isArray(prop) && prop.some(item => equals(value, item));
} : x => equals(value, getByKeyPath(x, keyPath)))
: prevFilterFn
];
}, [null, null]);
return idx ?
this.where(idx.name).equals(indexOrCrit[idx.keyPath])
.filter(filterFunction) :
compoundIndex ?
this.filter(filterFunction) : // Has compound but browser bad. Allow filter.
this.where(keyPaths).equals(''); // No index at all. Fail lazily with "[a+b+c] is not indexed"
}
/** Table.filter()
*
* https://dexie.org/docs/Table/Table.filter()
*
**/
filter(filterFunction: (obj: any) => boolean) {
return this.toCollection().and(filterFunction);
}
/** Table.count()
*
* https://dexie.org/docs/Table/Table.count()
*
**/
count(thenShortcut?: any) {
return this.toCollection().count(thenShortcut);
}
/** Table.offset()
*
* https://dexie.org/docs/Table/Table.offset()
*
**/
offset(offset: number) {
return this.toCollection().offset(offset);
}
/** Table.limit()
*
* https://dexie.org/docs/Table/Table.limit()
*
**/
limit(numRows: number) {
return this.toCollection().limit(numRows);
}
/** Table.each()
*
* https://dexie.org/docs/Table/Table.each()
*
**/
each(callback: (obj: any, cursor: { key: IndexableType, primaryKey: IndexableType }) => any) {
return this.toCollection().each(callback);
}
/** Table.toArray()
*
* https://dexie.org/docs/Table/Table.toArray()
*
**/
toArray(thenShortcut?: any) {
return this.toCollection().toArray(thenShortcut);
}
/** Table.toCollection()
*
* https://dexie.org/docs/Table/Table.toCollection()
*
**/
toCollection() {
return new this.db.Collection(new this.db.WhereClause(this));
}
/** Table.orderBy()
*
* https://dexie.org/docs/Table/Table.orderBy()
*
**/
orderBy(index: string | string[]) {
return new this.db.Collection(
new this.db.WhereClause(this, isArray(index) ?
`[${index.join('+')}]` :
index));
}
/** Table.reverse()
*
* https://dexie.org/docs/Table/Table.reverse()
*
**/
reverse(): Collection {
return this.toCollection().reverse();
}
/** Table.mapToClass()
*
* https://dexie.org/docs/Table/Table.mapToClass()
*
**/
mapToClass(constructor: Function) {
const {db, name: tableName} = this;
this.schema.mappedClass = constructor;
if (constructor.prototype instanceof Entity) {
constructor = class extends (constructor as any) {
get db () { return db; }
table() { return tableName; }
}
}
// Collect all inherited property names (including method names) by
// walking the prototype chain. This is to avoid overwriting them from
// database data - so application code can rely on inherited props never
// becoming shadowed by database object props.
const inheritedProps = new Set<string>();
for (let proto = constructor.prototype; proto; proto = getProto(proto)) {
Object.getOwnPropertyNames(proto).forEach(propName => inheritedProps.add(propName));
}
// Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class
// no matter which method to use for reading (Table.get() or Table.where(...)... )
const readHook = (obj: Object) => {
if (!obj) return obj; // No valid object. (Value is null or undefined). Return as is.
// Create a new object that derives from constructor:
const res = Object.create(constructor.prototype);
// Clone members (but never those that collide with a property in the prototype
// hierchary (MUST BE ABLE TO RELY ON Entity methods and props!)):
for (let m in obj) if (!inheritedProps.has(m)) try { res[m] = obj[m]; } catch (_) { }
return res;
};
if (this.schema.readHook) {
this.hook.reading.unsubscribe(this.schema.readHook);
}
this.schema.readHook = readHook;
this.hook("reading", readHook);
return constructor;
}
/** @deprecated */
defineClass() {
function Class (content){
extend(this, content);
};
return this.mapToClass(Class);
}
/** Table.add()
*
* https://dexie.org/docs/Table/Table.add()
*
**/
add(obj, key?: IndexableType): PromiseExtended<IndexableType> {
const {auto, keyPath} = this.schema.primKey;
let objToAdd = obj;
if (keyPath && auto) {
objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);
}
return this._trans('readwrite', trans => {
return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd]});
}).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)
.then(lastResult => {
if (keyPath) {
// This part should be here for backward compatibility.
// If ever feeling too bad about this, please wait to a new major before removing it,
// and document the change thoroughly.
try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};
}
return lastResult;
});
}
/** Table.update()
*
* https://dexie.org/docs/Table/Table.update()
*
**/
update(keyOrObject, modifications: { [keyPath: string]: any; } | ((obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean)): PromiseExtended<number> {
if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {
const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);
if (key === undefined) return rejection(new exceptions.InvalidArgument(
"Given object does not contain its primary key"));
/*// object to modify. Also modify given object with the modifications:
// This part should be here for backward compatibility.
// If ever feeling too bad about mutating given object, please wait to a new major before removing it,
// and document the change thoroughly. TODO: Document this change!
if (!Object.isFrozen(keyOrObject)) try {
if (typeof modifications !== "function") {
keys(modifications).forEach(keyPath => {
setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);
});
} else {
// Now since we support function argument, we should have a similar behavior here as well
// (as long as we do this mutability stuff on the given object)
modifications(keyOrObject, {value: keyOrObject, primKey: key});
}
} catch {
// Maybe given object was frozen.
// This part is not essential. Just move on as nothing happened...
}*/
return this.where(":id").equals(key).modify(modifications);
} else {
// key to modify
return this.where(":id").equals(keyOrObject).modify(modifications);
}
}
/** Table.put()
*
* https://dexie.org/docs/Table/Table.put()
*
**/
put(obj, key?: IndexableType): PromiseExtended<IndexableType> {
const {auto, keyPath} = this.schema.primKey;
let objToAdd = obj;
if (keyPath && auto) {
objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);
}
return this._trans(
'readwrite',
trans => this.core.mutate({trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null}))
.then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)
.then(lastResult => {
if (keyPath) {
// This part should be here for backward compatibility.
// If ever feeling too bad about this, please wait to a new major before removing it,
// and document the change thoroughly.
try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};
}
return lastResult;
});
}
/** Table.delete()
*
* https://dexie.org/docs/Table/Table.delete()
*
**/
delete(key: IndexableType): PromiseExtended<void> {
return this._trans('readwrite',
trans => this.core.mutate({trans, type: 'delete', keys: [key]}))
.then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);
}
/** Table.clear()
*
* https://dexie.org/docs/Table/Table.clear()
*
**/
clear() {
return this._trans('readwrite',
trans => this.core.mutate({trans, type: 'deleteRange', range: AnyRange}))
.then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);
}
/** Table.bulkGet()
*
* https://dexie.org/docs/Table/Table.bulkGet()
*
* @param keys
*/
bulkGet(keys: IndexableType[]) {
return this._trans('readonly', trans => {
return this.core.getMany({
keys,
trans
}).then(result => result.map(res => this.hook.reading.fire(res)));
});
}
/** Table.bulkAdd()
*
* https://dexie.org/docs/Table/Table.bulkAdd()
*
**/
bulkAdd(
objects: readonly any[],
keysOrOptions?: ReadonlyArray<IndexableType> | { allKeys?: boolean },
options?: { allKeys?: boolean }
) {
const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;
options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });
const wantResults = options ? options.allKeys : undefined;
return this._trans('readwrite', trans => {
const {auto, keyPath} = this.schema.primKey;
if (keyPath && keys)
throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");
if (keys && keys.length !== objects.length)
throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");
const numObjects = objects.length; // Pick length here to allow garbage collection of objects later
let objectsToAdd = keyPath && auto ?
objects.map(workaroundForUndefinedPrimKey(keyPath)) :
objects;
return this.core.mutate(
{trans, type: 'add', keys: keys as IndexableType[], values: objectsToAdd, wantResults}
)
.then(({numFailures, results,lastResult, failures}) => {
const result = wantResults ? results : lastResult;
if (numFailures === 0) return result;
throw new BulkError(
`${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`, failures);
});
});
}
/** Table.bulkPut()
*
* https://dexie.org/docs/Table/Table.bulkPut()
*
**/
bulkPut(
objects: readonly any[],
keysOrOptions?: ReadonlyArray<IndexableType> | { allKeys?: boolean },
options?: { allKeys?: boolean }
) {
const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;
options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });
const wantResults = options ? options.allKeys : undefined;
return this._trans('readwrite', trans => {
const {auto, keyPath} = this.schema.primKey;
if (keyPath && keys)
throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");
if (keys && keys.length !== objects.length)
throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");
const numObjects = objects.length; // Pick length here to allow garbage collection of objects later
let objectsToPut = keyPath && auto ?
objects.map(workaroundForUndefinedPrimKey(keyPath)) :
objects;
return this.core.mutate(
{trans, type: 'put', keys: keys as IndexableType[], values: objectsToPut, wantResults}
)
.then(({numFailures, results, lastResult, failures}) => {
const result = wantResults ? results : lastResult;
if (numFailures === 0) return result;
throw new BulkError(
`${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`, failures);
});
});
}
/** Table.bulkUpdate()
*
* https://dexie.org/docs/Table.Table.bulkUpdate()
*/
bulkUpdate(
keysAndChanges: readonly { key: any; changes: UpdateSpec<any> }[]
): PromiseExtended<number> {
const coreTable = this.core;
const keys = keysAndChanges.map((entry) => entry.key);
const changeSpecs = keysAndChanges.map((entry) => entry.changes);
const offsetMap: number[] = [];
return this._trans('readwrite', (trans) => {
return coreTable.getMany({ trans, keys, cache: 'clone' }).then((objs) => {
const resultKeys: any[] = [];
const resultObjs: any[] = [];
keysAndChanges.forEach(({ key, changes }, idx) => {
const obj = objs[idx];
if (obj) {
for (const keyPath of Object.keys(changes)) {
const value = changes[keyPath];
if (keyPath === this.schema.primKey.keyPath) {
if (cmp(value, key) !== 0) {
throw new exceptions.Constraint(
`Cannot update primary key in bulkUpdate()`
);
}
} else {
setByKeyPath(obj, keyPath, value);
}
}
offsetMap.push(idx);
resultKeys.push(key);
resultObjs.push(obj);
}
});
const numEntries = resultKeys.length;
return coreTable
.mutate({
trans,
type: 'put',
keys: resultKeys,
values: resultObjs,
updates: {
keys,
changeSpecs
}
})
.then(({ numFailures, failures }) => {
if (numFailures === 0) return numEntries;
// Failure. bulkPut() may have a subset of keys
// so we must translate returned 'failutes' into the offsets of given argument:
for (const offset of Object.keys(failures)) {
const mappedOffset = offsetMap[Number(offset)];
if (mappedOffset != null) {
const failure = failures[offset];
delete failures[offset];
failures[mappedOffset] = failure;
}
}
throw new BulkError(
`${this.name}.bulkUpdate(): ${numFailures} of ${numEntries} operations failed`,
failures
);
});
});
});
}
/** Table.bulkDelete()
*
* https://dexie.org/docs/Table/Table.bulkDelete()
*
**/
bulkDelete(keys: ReadonlyArray<IndexableType>): PromiseExtended<void> {
const numKeys = keys.length;
return this._trans('readwrite', trans => {
return this.core.mutate({trans, type: 'delete', keys: keys as IndexableType[]});
}).then(({numFailures, lastResult, failures}) => {
if (numFailures === 0) return lastResult;
throw new BulkError(
`${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures);
});
}
}