forked from indexeddbshim/IndexedDBShim
-
Notifications
You must be signed in to change notification settings - Fork 2
/
IDBDatabase.js
275 lines (248 loc) · 10.3 KB
/
IDBDatabase.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
import {createDOMException} from './DOMException';
import {createEvent} from './Event';
import * as util from './util';
import DOMStringList from './DOMStringList';
import IDBObjectStore from './IDBObjectStore';
import IDBTransaction from './IDBTransaction';
import * as Sca from './Sca';
import CFG from './CFG';
import {EventTargetFactory} from 'eventtarget';
const listeners = ['onabort', 'onclose', 'onerror', 'onversionchange'];
const readonlyProperties = ['name', 'version', 'objectStoreNames'];
/**
* IDB Database Object
* http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#database-interface
* @constructor
*/
function IDBDatabase () {
throw new TypeError('Illegal constructor');
}
const IDBDatabaseAlias = IDBDatabase;
IDBDatabase.__createInstance = function (db, name, oldVersion, version, storeProperties) {
function IDBDatabase () {
this[Symbol.toStringTag] = 'IDBDatabase';
util.defineReadonlyProperties(this, readonlyProperties);
this.__db = db;
this.__closed = false;
this.__oldVersion = oldVersion;
this.__version = version;
this.__name = name;
listeners.forEach((listener) => {
Object.defineProperty(this, listener, {
enumerable: true,
configurable: true,
get: function () {
return this['__' + listener];
},
set: function (val) {
this['__' + listener] = val;
}
});
});
listeners.forEach((l) => {
this[l] = null;
});
this.__setOptions({
legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB
});
this.__transactions = [];
this.__objectStores = {};
this.__objectStoreNames = DOMStringList.__createInstance();
const itemCopy = {};
for (let i = 0; i < storeProperties.rows.length; i++) {
const item = storeProperties.rows.item(i);
// Safari implements `item` getter return object's properties
// as readonly, so we copy all its properties (except our
// custom `currNum` which we don't need) onto a new object
itemCopy.name = item.name;
itemCopy.keyPath = Sca.decode(item.keyPath);
['autoInc', 'indexList'].forEach(function (prop) {
itemCopy[prop] = JSON.parse(item[prop]);
});
itemCopy.idbdb = this;
const store = IDBObjectStore.__createInstance(itemCopy);
this.__objectStores[store.name] = store;
this.objectStoreNames.push(store.name);
}
this.__oldObjectStoreNames = this.objectStoreNames.clone();
}
IDBDatabase.prototype = IDBDatabaseAlias.prototype;
return new IDBDatabase();
};
IDBDatabase.prototype = EventTargetFactory.createInstance();
IDBDatabase.prototype[Symbol.toStringTag] = 'IDBDatabasePrototype';
/**
* Creates a new object store.
* @param {string} storeName
* @param {object} [createOptions]
* @returns {IDBObjectStore}
*/
IDBDatabase.prototype.createObjectStore = function (storeName /* , createOptions */) {
let createOptions = arguments[1];
storeName = String(storeName); // W3C test within IDBObjectStore.js seems to accept string conversion
if (!(this instanceof IDBDatabase)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length === 0) {
throw new TypeError('No object store name was specified');
}
IDBTransaction.__assertVersionChange(this.__versionTransaction); // this.__versionTransaction may not exist if called mistakenly by user in onsuccess
IDBTransaction.__assertNotFinishedObjectStoreMethod(this.__versionTransaction);
IDBTransaction.__assertActive(this.__versionTransaction);
createOptions = Object.assign({}, createOptions);
let keyPath = createOptions.keyPath;
keyPath = keyPath === undefined ? null : keyPath = util.convertToSequenceDOMString(keyPath);
if (keyPath !== null && !util.isValidKeyPath(keyPath)) {
throw createDOMException('SyntaxError', 'The keyPath argument contains an invalid key path.');
}
if (this.__objectStores[storeName] && !this.__objectStores[storeName].__pendingDelete) {
throw createDOMException('ConstraintError', 'Object store "' + storeName + '" already exists in ' + this.name);
}
const autoIncrement = createOptions.autoIncrement;
if (autoIncrement && (keyPath === '' || Array.isArray(keyPath))) {
throw createDOMException('InvalidAccessError', 'With autoIncrement set, the keyPath argument must not be an array or empty string.');
}
/** @name IDBObjectStoreProperties **/
const storeProperties = {
name: storeName,
keyPath: keyPath,
autoInc: autoIncrement,
indexList: {},
idbdb: this
};
const store = IDBObjectStore.__createInstance(storeProperties, this.__versionTransaction);
return IDBObjectStore.__createObjectStore(this, store);
};
/**
* Deletes an object store.
* @param {string} storeName
*/
IDBDatabase.prototype.deleteObjectStore = function (storeName) {
if (!(this instanceof IDBDatabase)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length === 0) {
throw new TypeError('No object store name was specified');
}
IDBTransaction.__assertVersionChange(this.__versionTransaction);
IDBTransaction.__assertNotFinishedObjectStoreMethod(this.__versionTransaction);
IDBTransaction.__assertActive(this.__versionTransaction);
const store = this.__objectStores[storeName];
if (!store) {
throw createDOMException('NotFoundError', 'Object store "' + storeName + '" does not exist in ' + this.name);
}
IDBObjectStore.__deleteObjectStore(this, store);
};
IDBDatabase.prototype.close = function () {
if (!(this instanceof IDBDatabase)) {
throw new TypeError('Illegal invocation');
}
this.__closed = true;
if (this.__unblocking) {
this.__unblocking.check();
}
};
/**
* Starts a new transaction.
* @param {string|string[]} storeNames
* @param {string} mode
* @returns {IDBTransaction}
*/
IDBDatabase.prototype.transaction = function (storeNames /* , mode */) {
let mode = arguments[1];
storeNames = typeof storeNames === 'string'
? [storeNames]
: (util.isIterable(storeNames)
? [ // Creating new array also ensures sequence is passed by value: https://heycam.github.io/webidl/#idl-sequence
...new Set( // to be unique
util.convertToSequenceDOMString(storeNames) // iterables have `ToString` applied (and we convert to array for convenience)
)
].sort() // must be sorted
: (function () {
throw new TypeError('You must supply a valid `storeNames` to `IDBDatabase.transaction`');
}()));
// Since SQLite (at least node-websql and definitely WebSQL) requires
// locking of the whole database, to allow simultaneous readwrite
// operations on transactions without overlapping stores, we'd probably
// need to save the stores in separate databases (we could also consider
// prioritizing readonly but not starving readwrite).
// Even for readonly transactions, due to [issue 17](https://github.com/nolanlawson/node-websql/issues/17),
// we're not currently actually running the SQL requests in parallel.
if (typeof mode === 'number') {
mode = mode === 1 ? 'readwrite' : 'readonly';
CFG.DEBUG && console.log('Mode should be a string, but was specified as ', mode); // Todo Deprecated: Remove this option as no longer in spec
} else {
mode = mode || 'readonly';
}
IDBTransaction.__assertNotVersionChange(this.__versionTransaction);
if (this.__closed) {
throw createDOMException('InvalidStateError', 'An attempt was made to start a new transaction on a database connection that is not open');
}
const objectStoreNames = DOMStringList.__createInstance();
storeNames.forEach((storeName) => {
if (!this.objectStoreNames.contains(storeName)) {
throw createDOMException('NotFoundError', 'The "' + storeName + '" object store does not exist');
}
objectStoreNames.push(storeName);
});
if (storeNames.length === 0) {
throw createDOMException('InvalidAccessError', 'No valid object store names were specified');
}
if (mode !== 'readonly' && mode !== 'readwrite') {
throw new TypeError('Invalid transaction mode: ' + mode);
}
// Do not set __active flag to false yet: https://github.com/w3c/IndexedDB/issues/87
const trans = IDBTransaction.__createInstance(this, objectStoreNames, mode);
this.__transactions.push(trans);
return trans;
};
// Todo __forceClose: Add tests for `__forceClose`
IDBDatabase.prototype.__forceClose = function (msg) {
const me = this;
me.close();
let ct = 0;
me.__transactions.forEach(function (trans) {
trans.on__abort = function () {
ct++;
if (ct === me.__transactions.length) {
// Todo __forceClose: unblock any pending `upgradeneeded` or `deleteDatabase` calls
const evt = createEvent('close');
setTimeout(() => {
me.dispatchEvent(evt);
});
}
};
trans.__abortTransaction(createDOMException('AbortError', 'The connection was force-closed: ' + (msg || '')));
});
};
listeners.forEach((listener) => {
Object.defineProperty(IDBDatabase.prototype, listener, {
enumerable: true,
configurable: true,
get: function () {
throw new TypeError('Illegal invocation');
},
set: function (val) {
throw new TypeError('Illegal invocation');
}
});
});
readonlyProperties.forEach((prop) => {
Object.defineProperty(IDBDatabase.prototype, prop, {
enumerable: true,
configurable: true,
get: function () {
throw new TypeError('Illegal invocation');
}
});
});
Object.defineProperty(IDBDatabase.prototype, 'constructor', {
enumerable: false,
writable: true,
configurable: true,
value: IDBDatabase
});
Object.defineProperty(IDBDatabase, 'prototype', {
writable: false
});
export default IDBDatabase;