forked from indexeddbshim/IndexedDBShim
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Key.js
758 lines (712 loc) · 28.3 KB
/
Key.js
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
import {createDOMException} from './DOMException';
import * as util from './util';
import {cmp} from './IDBFactory';
import CFG from './CFG';
/**
* Encodes the keys based on their types. This is required to maintain collations
*/
const collations = ['invalid', 'number', 'date', 'string', 'binary', 'array'];
/**
* The sign values for numbers, ordered from least to greatest.
* - "negativeInfinity": Sorts below all other values.
* - "bigNegative": Negative values less than or equal to negative one.
* - "smallNegative": Negative values between negative one and zero, noninclusive.
* - "smallPositive": Positive values between zero and one, including zero but not one.
* - "largePositive": Positive values greater than or equal to one.
* - "positiveInfinity": Sorts above all other values.
*/
const signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];
const types = {
invalid: {
encode: function (key) {
return collations.indexOf('invalid') + '-';
},
decode: function (key) {
return undefined;
}
},
// Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa
// notation.
//
// sign: takes a value between zero and five, inclusive. Represents infinite cases
// and the signs of both the exponent and the fractional part of the number.
// exponent: padded to two base-32 digits, represented by the 32's compliment in the
// "smallPositive" and "bigNegative" cases to ensure proper lexical sorting.
// mantissa: also called the fractional part. Normed 11-digit base-32 representation.
// Represented by the 32's compliment in the "smallNegative" and "bigNegative"
// cases to ensure proper lexical sorting.
number: {
// The encode step checks for six numeric cases and generates 14-digit encoded
// sign-exponent-mantissa strings.
encode: function (key) {
let key32 = Math.abs(key).toString(32);
// Get the index of the decimal.
const decimalIndex = key32.indexOf('.');
// Remove the decimal.
key32 = (decimalIndex !== -1) ? key32.replace('.', '') : key32;
// Get the index of the first significant digit.
const significantDigitIndex = key32.search(/[^0]/);
// Truncate leading zeros.
key32 = key32.slice(significantDigitIndex);
let sign, exponent, mantissa;
// Finite cases:
if (isFinite(key)) {
// Negative cases:
if (key < 0) {
// Negative exponent case:
if (key > -1) {
sign = signValues.indexOf('smallNegative');
exponent = padBase32Exponent(significantDigitIndex);
mantissa = flipBase32(padBase32Mantissa(key32));
// Non-negative exponent case:
} else {
sign = signValues.indexOf('bigNegative');
exponent = flipBase32(padBase32Exponent(
(decimalIndex !== -1) ? decimalIndex : key32.length
));
mantissa = flipBase32(padBase32Mantissa(key32));
}
// Non-negative cases:
} else {
// Negative exponent case:
if (key < 1) {
sign = signValues.indexOf('smallPositive');
exponent = flipBase32(padBase32Exponent(significantDigitIndex));
mantissa = padBase32Mantissa(key32);
// Non-negative exponent case:
} else {
sign = signValues.indexOf('bigPositive');
exponent = padBase32Exponent(
(decimalIndex !== -1) ? decimalIndex : key32.length
);
mantissa = padBase32Mantissa(key32);
}
}
// Infinite cases:
} else {
exponent = zeros(2);
mantissa = zeros(11);
sign = signValues.indexOf(
key > 0 ? 'positiveInfinity' : 'negativeInfinity'
);
}
return collations.indexOf('number') + '-' + sign + exponent + mantissa;
},
// The decode step must interpret the sign, reflip values encoded as the 32's complements,
// apply signs to the exponent and mantissa, do the base-32 power operation, and return
// the original JavaScript number values.
decode: function (key) {
const sign = +key.substr(2, 1);
let exponent = key.substr(3, 2);
let mantissa = key.substr(5, 11);
switch (signValues[sign]) {
case 'negativeInfinity':
return -Infinity;
case 'positiveInfinity':
return Infinity;
case 'bigPositive':
return pow32(mantissa, exponent);
case 'smallPositive':
exponent = negate(flipBase32(exponent));
return pow32(mantissa, exponent);
case 'smallNegative':
exponent = negate(exponent);
mantissa = flipBase32(mantissa);
return -pow32(mantissa, exponent);
case 'bigNegative':
exponent = flipBase32(exponent);
mantissa = flipBase32(mantissa);
return -pow32(mantissa, exponent);
default:
throw new Error('Invalid number.');
}
}
},
// Strings are encoded as JSON strings (with quotes and unicode characters escaped).
//
// If the strings are in an array, then some extra encoding is done to make sorting work correctly:
// Since we can't force all strings to be the same length, we need to ensure that characters line-up properly
// for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.
// To do this, each character of the string is prepended with a dash ("-"), and a space is added to the end of the string.
// This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,
// the indexes of each string's characters line up with each other.
string: {
encode: function (key, inArray) {
if (inArray) {
// prepend each character with a dash, and append a space to the end
key = key.replace(/(.)/g, '-$1') + ' ';
}
return collations.indexOf('string') + '-' + key;
},
decode: function (key, inArray) {
key = key.slice(2);
if (inArray) {
// remove the space at the end, and the dash before each character
key = key.substr(0, key.length - 1).replace(/-(.)/g, '$1');
}
return key;
}
},
// Arrays are encoded as JSON strings.
// An extra, value is added to each array during encoding to make empty arrays sort correctly.
array: {
encode: function (key) {
const encoded = [];
for (let i = 0; i < key.length; i++) {
const item = key[i];
const encodedItem = encode(item, true); // encode the array item
encoded[i] = encodedItem;
}
encoded.push(collations.indexOf('invalid') + '-'); // append an extra item, so empty arrays sort correctly
return collations.indexOf('array') + '-' + JSON.stringify(encoded);
},
decode: function (key) {
const decoded = JSON.parse(key.slice(2));
decoded.pop(); // remove the extra item
for (let i = 0; i < decoded.length; i++) {
const item = decoded[i];
const decodedItem = decode(item, true); // decode the item
decoded[i] = decodedItem;
}
return decoded;
}
},
// Dates are encoded as ISO 8601 strings, in UTC time zone.
date: {
encode: function (key) {
return collations.indexOf('date') + '-' + key.toJSON();
},
decode: function (key) {
return new Date(key.slice(2));
}
},
binary: { // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)
encode: function (key) {
return collations.indexOf('binary') + '-' + (key.byteLength
? Array.from(getCopyBytesHeldByBufferSource(key)).map((b) => util.padStart(b, 3, '0')) // e.g., '255,005,254,000,001,033'
: '');
},
decode: function (key) {
// Set the entries in buffer's [[ArrayBufferData]] to those in `value`
const k = key.slice(2);
const arr = k.length ? k.split(',').map((s) => parseInt(s, 10)) : [];
const buffer = new ArrayBuffer(arr.length);
const uint8 = new Uint8Array(buffer);
uint8.set(arr);
return buffer;
}
}
};
/**
* Return a padded base-32 exponent value.
* @param {number}
* @return {string}
*/
function padBase32Exponent (n) {
n = n.toString(32);
return (n.length === 1) ? '0' + n : n;
}
/**
* Return a padded base-32 mantissa.
* @param {string}
* @return {string}
*/
function padBase32Mantissa (s) {
return (s + zeros(11)).slice(0, 11);
}
/**
* Flips each digit of a base-32 encoded string.
* @param {string} encoded
*/
function flipBase32 (encoded) {
let flipped = '';
for (let i = 0; i < encoded.length; i++) {
flipped += (31 - parseInt(encoded[i], 32)).toString(32);
}
return flipped;
}
/**
* Base-32 power function.
* RESEARCH: This function does not precisely decode floats because it performs
* floating point arithmetic to recover values. But can the original values be
* recovered exactly?
* Someone may have already figured out a good way to store JavaScript floats as
* binary strings and convert back. Barring a better method, however, one route
* may be to generate decimal strings that `parseFloat` decodes predictably.
* @param {string}
* @param {string}
* @return {number}
*/
function pow32 (mantissa, exponent) {
exponent = parseInt(exponent, 32);
if (exponent < 0) {
return roundToPrecision(
parseInt(mantissa, 32) * Math.pow(32, exponent - 10)
);
} else {
if (exponent < 11) {
let whole = mantissa.slice(0, exponent);
whole = parseInt(whole, 32);
let fraction = mantissa.slice(exponent);
fraction = parseInt(fraction, 32) * Math.pow(32, exponent - 11);
return roundToPrecision(whole + fraction);
} else {
const expansion = mantissa + zeros(exponent - 11);
return parseInt(expansion, 32);
}
}
}
/**
*
*/
function roundToPrecision (num, precision) {
precision = precision || 16;
return parseFloat(num.toPrecision(precision));
}
/**
* Returns a string of n zeros.
* @param {number}
* @return {string}
*/
function zeros (n) {
return '0'.repeat(n);
}
/**
* Negates numeric strings.
* @param {string}
* @return {string}
*/
function negate (s) {
return '-' + s;
}
/**
* Returns the string "number", "date", "string", "binary", or "array"
*/
function getKeyType (key) {
if (Array.isArray(key)) return 'array';
if (util.isDate(key)) return 'date';
if (util.isBinary(key)) return 'binary';
const keyType = typeof key;
return ['string', 'number'].includes(keyType) ? keyType : 'invalid';
}
/**
* Keys must be strings, numbers (besides NaN), Dates (if value is not NaN),
* binary objects or Arrays
* @param input The key input
* @param seen An array of already seen keys
*/
function convertValueToKey (input, seen) {
return convertValueToKeyValueDecoded(input, seen, false, true);
}
/**
* Currently not in use
*/
function convertValueToMultiEntryKey (input) {
return convertValueToKeyValueDecoded(input, null, true, true);
}
// https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
function getCopyBytesHeldByBufferSource (O) {
let offset = 0;
let length = 0;
if (ArrayBuffer.isView(O)) { // Has [[ViewedArrayBuffer]] internal slot
const arrayBuffer = O.buffer;
if (arrayBuffer === undefined) {
throw new TypeError('Could not copy the bytes held by a buffer source as the buffer was undefined.');
}
offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)
length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)
} else {
length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)
}
// const octets = new Uint8Array(input);
// const octets = types.binary.decode(types.binary.encode(input));
return new Uint8Array(O.buffer || O, offset, length);
}
/**
* Shortcut utility to avoid returning full keys from `convertValueToKey`
* and subsequent need to process in calling code unless `fullKeys` is
* set; may throw
*/
function convertValueToKeyValueDecoded (input, seen, multiEntry, fullKeys) {
seen = seen || [];
if (seen.includes(input)) return {type: 'array', invalid: true, message: 'An array key cannot be circular'};
const type = getKeyType(input);
const ret = {type, value: input};
switch (type) {
case 'number': {
if (Number.isNaN(input)) {
return {type: 'NaN', invalid: true}; // List as 'NaN' type for convenience of consumers in reporting errors
}
return ret;
} case 'string': {
return ret;
} case 'binary': { // May throw (if detached)
// Get a copy of the bytes held by the buffer source
// https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
const octets = getCopyBytesHeldByBufferSource(input);
return {type: 'binary', value: octets};
} case 'array': { // May throw (from binary)
const len = input.length;
seen.push(input);
const keys = [];
for (let i = 0; i < len; i++) { // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated
if (!multiEntry && !Object.prototype.hasOwnProperty.call(input, i)) {
return {type, invalid: true, message: 'Does not have own index property'};
}
try {
const entry = input[i];
const key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry
if (key.invalid) {
if (multiEntry) {
continue;
}
return {type, invalid: true, message: 'Bad array entry value-to-key conversion'};
}
if (!multiEntry ||
(!fullKeys && keys.every((k) => cmp(k, key.value) !== 0)) ||
(fullKeys && keys.every((k) => cmp(k, key) !== 0))
) {
keys.push(fullKeys ? key : key.value);
}
} catch (err) {
if (!multiEntry) {
throw err;
}
}
}
return {type, value: keys};
} case 'date': {
if (!Number.isNaN(input.getTime())) {
return fullKeys ? {type, value: input.getTime()} : {type, value: new Date(input.getTime())};
}
return {type, invalid: true, message: 'Not a valid date'};
// Falls through
} case 'invalid': default: {
// Other `typeof` types which are not valid keys:
// 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function
const type = input === null ? 'null' : typeof input; // Convert `null` for convenience of consumers in reporting errors
return {type, invalid: true, message: 'Not a valid key; type ' + type};
}
}
}
function convertValueToMultiEntryKeyDecoded (key, fullKeys) {
return convertValueToKeyValueDecoded(key, null, true, fullKeys);
}
/**
* An internal utility
*/
function convertValueToKeyRethrowingAndIfInvalid (input, seen) {
const key = convertValueToKey(input, seen);
if (key.invalid) {
throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);
}
return key;
}
function extractKeyFromValueUsingKeyPath (value, keyPath, multiEntry) {
return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);
}
/**
* Not currently in use
*/
function evaluateKeyPathOnValue (value, keyPath, multiEntry) {
return evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, true);
}
/**
* May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)
* or `{invalid: true}` (e.g., `NaN`)
*/
function extractKeyValueDecodedFromValueUsingKeyPath (value, keyPath, multiEntry, fullKeys) {
const r = evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys);
if (r.failure) {
return r;
}
if (!multiEntry) {
return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);
}
return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);
}
/**
* Returns the value of an inline key based on a key path (wrapped in an object with key `value`)
* or `{failure: true}`
* @param {object} value
* @param {string|array} keyPath
* @param {boolean} multiEntry
* @returns {undefined|array|string}
*/
function evaluateKeyPathOnValueToDecodedValue (value, keyPath, multiEntry, fullKeys) {
if (Array.isArray(keyPath)) {
const result = [];
return keyPath.some((item) => {
const key = evaluateKeyPathOnValueToDecodedValue(value, item, multiEntry, fullKeys);
if (key.failure) {
return true;
}
result.push(key.value);
}, []) ? {failure: true} : {value: result};
}
if (keyPath === '') {
return {value};
}
const identifiers = keyPath.split('.');
return identifiers.some((idntfr, i) => {
if (idntfr === 'length' && (
typeof value === 'string' || Array.isArray(value)
)) {
value = value.length;
} else if (util.isBlob(value)) {
switch (idntfr) {
case 'size': case 'type':
value = value[idntfr];
break;
}
} else if (util.isFile(value)) {
switch (idntfr) {
case 'name': case 'lastModified':
value = value[idntfr];
break;
case 'lastModifiedDate':
value = new Date(value.lastModified);
break;
}
} else if (!util.isObj(value) || !Object.prototype.hasOwnProperty.call(value, idntfr)) {
return true;
} else {
value = value[idntfr];
return value === undefined;
}
}) ? {failure: true} : {value};
}
/**
* Sets the inline key value
* @param {object} value
* @param {*} key
* @param {string} keyPath
*/
function injectKeyIntoValueUsingKeyPath (value, key, keyPath) {
const identifiers = keyPath.split('.');
const last = identifiers.pop();
for (let i = 0; i < identifiers.length; i++) {
const identifier = identifiers[i];
const hop = Object.prototype.hasOwnProperty.call(value, identifier);
if (!hop) {
value[identifier] = {};
}
value = value[identifier];
}
value[last] = key; // key is already a `keyValue` in our processing so no need to convert
}
// See https://github.com/w3c/IndexedDB/pull/146
function checkKeyCouldBeInjectedIntoValue (value, keyPath) {
const identifiers = keyPath.split('.');
identifiers.pop();
for (let i = 0; i < identifiers.length; i++) {
if (!util.isObj(value)) {
return false;
}
const identifier = identifiers[i];
const hop = Object.prototype.hasOwnProperty.call(value, identifier);
if (!hop) {
return true;
}
value = value[identifier];
}
return util.isObj(value);
}
function isKeyInRange (key, range, checkCached) {
let lowerMatch = range.lower === undefined;
let upperMatch = range.upper === undefined;
const encodedKey = encode(key, true);
const lower = checkCached ? range.__lowerCached : encode(range.lower, true);
const upper = checkCached ? range.__upperCached : encode(range.upper, true);
if (range.lower !== undefined) {
if (range.lowerOpen && encodedKey > lower) {
lowerMatch = true;
}
if (!range.lowerOpen && encodedKey >= lower) {
lowerMatch = true;
}
}
if (range.upper !== undefined) {
if (range.upperOpen && encodedKey < upper) {
upperMatch = true;
}
if (!range.upperOpen && encodedKey <= upper) {
upperMatch = true;
}
}
return lowerMatch && upperMatch;
}
/**
* Determines whether an index entry matches a multi-entry key value.
* @param {string} encodedEntry The entry value (already encoded)
* @param {string} encodedKey The full index key (already encoded)
* @returns {boolean}
*/
function isMultiEntryMatch (encodedEntry, encodedKey) {
const keyType = collations[encodedKey.slice(0, 1)];
if (keyType === 'array') {
return encodedKey.indexOf(encodedEntry) > 1;
} else {
return encodedKey === encodedEntry;
}
}
function findMultiEntryMatches (keyEntry, range) {
const matches = [];
if (Array.isArray(keyEntry)) {
for (let i = 0; i < keyEntry.length; i++) {
let key = keyEntry[i];
if (Array.isArray(key)) {
if (range && range.lower === range.upper) {
continue;
}
if (key.length === 1) {
key = key[0];
} else {
const nested = findMultiEntryMatches(key, range);
if (nested.length > 0) {
matches.push(key);
}
continue;
}
}
if (range == null || isKeyInRange(key, range, true)) {
matches.push(key);
}
}
} else {
if (range == null || isKeyInRange(keyEntry, range, true)) {
matches.push(keyEntry);
}
}
return matches;
}
/**
* Not currently in use but keeping for spec parity
*/
function convertKeyToValue (key) {
const type = key.type;
const value = key.value;
switch (type) {
case 'number': case 'string': {
return value;
} case 'array': {
const array = [];
const len = value.length;
let index = 0;
while (index < len) {
const entry = convertKeyToValue(value[index]);
array[index] = entry;
index++;
}
return array;
} case 'date': {
return new Date(value);
} case 'binary': {
const len = value.length;
const buffer = new ArrayBuffer(len);
// Set the entries in buffer's [[ArrayBufferData]] to those in `value`
const uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);
uint8.set(value);
return buffer;
} case 'invalid': default:
throw new Error('Bad key');
}
}
function encode (key, inArray) {
// Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation
if (key === undefined) {
return null;
}
// array, date, number, string, binary (should already have detected "invalid")
return types[getKeyType(key)].encode(key, inArray);
}
function decode (key, inArray) {
if (typeof key !== 'string') {
return undefined;
}
return types[collations[key.slice(0, 1)]].decode(key, inArray);
}
function roundTrip (key, inArray) {
return decode(encode(key, inArray), inArray);
}
const MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)
function getCurrentNumber (tx, store, callback, sqlFailCb) {
tx.executeSql('SELECT "currNum" FROM __sys__ WHERE "name" = ?', [util.escapeSQLiteStatement(store.__currentName)], function (tx, data) {
if (data.rows.length !== 1) {
callback(1); // eslint-disable-line standard/no-callback-literal
} else {
callback(data.rows.item(0).currNum);
}
}, function (tx, error) {
sqlFailCb(createDOMException('DataError', 'Could not get the auto increment value for key', error));
});
}
// Bump up the auto-inc counter if the key path-resolved value is valid (greater than old value and >=1) OR
// if a manually passed in key is valid (numeric and >= 1) and >= any primaryKey
function setCurrentNumber (tx, store, num, successCb, failCb) {
const sql = 'UPDATE __sys__ SET "currNum" = ? WHERE "name" = ?';
num = num === MAX_ALLOWED_CURRENT_NUMBER
? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner
: num + 1;
const sqlValues = [num, util.escapeSQLiteStatement(store.__currentName)];
CFG.DEBUG && console.log(sql, sqlValues);
tx.executeSql(sql, sqlValues, function (tx, data) {
successCb(num);
}, function (tx, err) {
failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));
});
}
function generateKeyForStore (tx, store, cb, sqlFailCb) {
getCurrentNumber(tx, store, function (key) {
if (key > MAX_ALLOWED_CURRENT_NUMBER) { // 2 ^ 53 (See <https://github.com/w3c/IndexedDB/issues/147>)
return cb('failure'); // eslint-disable-line standard/no-callback-literal
}
// Increment current number by 1 (we cannot leverage SQLite's
// autoincrement (and decrement when not needed), as decrementing
// will be overwritten/ignored upon the next insert)
setCurrentNumber(tx, store, key,
function () {
cb(null, key);
},
sqlFailCb
);
}, sqlFailCb);
}
// Fractional or numbers exceeding the max do not get changed in the result
// per https://github.com/w3c/IndexedDB/issues/147
// so we do not return a key
function possiblyUpdateKeyGenerator (tx, store, key, successCb, sqlFailCb) {
// Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers
// (or numbers larger than the max) are now to have the explicit effect of
// setting the current number (up to the max), so we do not optimize them
// out here
if (typeof key !== 'number' || key < 1) { // Optimize with no need to get the current number
// Auto-increment attempted with a bad key;
// we are not to change the current number, but the steps don't call for failure
// Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1
successCb();
} else {
// If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher
// to determine which to use and whether to update the current number
getCurrentNumber(tx, store, function (cn) {
const value = Math.floor(
Math.min(key, MAX_ALLOWED_CURRENT_NUMBER)
);
const useNewKeyForAutoInc = value >= cn;
if (useNewKeyForAutoInc) {
setCurrentNumber(tx, store, value, successCb, sqlFailCb);
} else { // Not updated
successCb();
}
}, sqlFailCb);
}
}
/* eslint-disable object-property-newline */
export {encode, decode, roundTrip, convertKeyToValue, convertValueToKeyValueDecoded,
convertValueToMultiEntryKeyDecoded,
convertValueToKey,
convertValueToMultiEntryKey, convertValueToKeyRethrowingAndIfInvalid,
extractKeyFromValueUsingKeyPath, evaluateKeyPathOnValue,
extractKeyValueDecodedFromValueUsingKeyPath, injectKeyIntoValueUsingKeyPath, checkKeyCouldBeInjectedIntoValue,
isMultiEntryMatch, isKeyInRange, findMultiEntryMatches,
generateKeyForStore, possiblyUpdateKeyGenerator};