forked from indexeddbshim/IndexedDBShim
-
Notifications
You must be signed in to change notification settings - Fork 2
/
IDBIndex.js
278 lines (252 loc) · 10.6 KB
/
IDBIndex.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
(function(idbModules, undefined) {
'use strict';
/**
* IDB Index
* http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex
* @param {IDBObjectStore} store
* @param {IDBIndexProperties} indexProperties
* @constructor
*/
function IDBIndex(store, indexProperties) {
this.objectStore = store;
this.name = indexProperties.columnName;
this.keyPath = indexProperties.keyPath;
this.multiEntry = indexProperties.optionalParams && indexProperties.optionalParams.multiEntry;
this.unique = indexProperties.optionalParams && indexProperties.optionalParams.unique;
this.__deleted = !!indexProperties.__deleted;
}
/**
* Clones an IDBIndex instance for a different IDBObjectStore instance.
* @param {IDBIndex} index
* @param {IDBObjectStore} store
* @protected
*/
IDBIndex.__clone = function(index, store) {
return new IDBIndex(store, {
columnName: index.name,
keyPath: index.keyPath,
optionalParams: {
multiEntry: index.multiEntry,
unique: index.unique
}
});
};
/**
* Creates a new index on an object store.
* @param {IDBObjectStore} store
* @param {IDBIndex} index
* @returns {IDBIndex}
* @protected
*/
IDBIndex.__createIndex = function(store, index) {
var columnExists = !!store.__indexes[index.name] && store.__indexes[index.name].__deleted;
// Add the index to the IDBObjectStore
store.__indexes[index.name] = index;
store.indexNames.push(index.name);
// Create the index in WebSQL
var transaction = store.transaction;
transaction.__addToTransactionQueue(function createIndex(tx, args, success, failure) {
function error(tx, err) {
failure(idbModules.util.createDOMException(0, "Could not create index \"" + index.name + "\"", err));
}
function applyIndex(tx) {
// Update the object store's index list
IDBIndex.__updateIndexList(store, tx, function() {
// Add index entries for all existing records
tx.executeSql("SELECT * FROM " + idbModules.util.quote(store.name), [], function(tx, data) {
idbModules.DEBUG && console.log("Adding existing " + store.name + " records to the " + index.name + " index");
addIndexEntry(0);
function addIndexEntry(i) {
if (i < data.rows.length) {
try {
var value = idbModules.Sca.decode(data.rows.item(i).value);
var indexKey = idbModules.Key.getValue(value, index.keyPath);
indexKey = idbModules.Key.encode(indexKey, index.multiEntry);
tx.executeSql("UPDATE " + idbModules.util.quote(store.name) + " set " + idbModules.util.quote(index.name) + " = ? where key = ?", [indexKey, data.rows.item(i).key], function(tx, data) {
addIndexEntry(i + 1);
}, error);
}
catch (e) {
// Not a valid value to insert into index, so just continue
addIndexEntry(i + 1);
}
}
else {
success(store);
}
}
}, error);
}, error);
}
if (columnExists) {
// For a previously existing index, just update the index entries in the existing column
applyIndex(tx);
}
else {
// For a new index, add a new column to the object store, then apply the index
var sql = ["ALTER TABLE", idbModules.util.quote(store.name), "ADD", idbModules.util.quote(index.name), "BLOB"].join(" ");
idbModules.DEBUG && console.log(sql);
tx.executeSql(sql, [], applyIndex, error);
}
});
};
/**
* Deletes an index from an object store.
* @param {IDBObjectStore} store
* @param {IDBIndex} index
* @protected
*/
IDBIndex.__deleteIndex = function(store, index) {
// Remove the index from the IDBObjectStore
store.__indexes[index.name].__deleted = true;
store.indexNames.splice(store.indexNames.indexOf(index.name), 1);
// Remove the index in WebSQL
var transaction = store.transaction;
transaction.__addToTransactionQueue(function createIndex(tx, args, success, failure) {
function error(tx, err) {
failure(idbModules.util.createDOMException(0, "Could not delete index \"" + index.name + "\"", err));
}
// Update the object store's index list
IDBIndex.__updateIndexList(store, tx, success, error);
});
};
/**
* Updates index list for the given object store.
* @param {IDBObjectStore} store
* @param {object} tx
* @param {function} success
* @param {function} failure
*/
IDBIndex.__updateIndexList = function(store, tx, success, failure) {
var indexList = {};
for (var i = 0; i < store.indexNames.length; i++) {
var idx = store.__indexes[store.indexNames[i]];
/** @type {IDBIndexProperties} **/
indexList[idx.name] = {
columnName: idx.name,
keyPath: idx.keyPath,
optionalParams: {
unique: idx.unique,
multiEntry: idx.multiEntry
},
deleted: !!idx.deleted
};
}
idbModules.DEBUG && console.log("Updating the index list for " + store.name, indexList);
tx.executeSql("UPDATE __sys__ set indexList = ? where name = ?", [JSON.stringify(indexList), store.name], function() {
success(store);
}, failure);
};
/**
* Retrieves index data for the given key
* @param {*|IDBKeyRange} key
* @param {string} opType
* @returns {IDBRequest}
* @private
*/
IDBIndex.prototype.__fetchIndexData = function(key, opType) {
var me = this;
var hasKey, encodedKey;
// key is optional
if (arguments.length === 1) {
opType = key;
hasKey = false;
}
else {
idbModules.Key.validate(key);
encodedKey = idbModules.Key.encode(key, me.multiEntry);
hasKey = true;
}
return me.objectStore.transaction.__addToTransactionQueue(function fetchIndexData(tx, args, success, error) {
var sql = ["SELECT * FROM", idbModules.util.quote(me.objectStore.name), "WHERE", idbModules.util.quote(me.name), "NOT NULL"];
var sqlValues = [];
if (hasKey) {
if (me.multiEntry) {
sql.push("AND", idbModules.util.quote(me.name), "LIKE ?");
sqlValues.push("%" + encodedKey + "%");
}
else {
sql.push("AND", idbModules.util.quote(me.name), "= ?");
sqlValues.push(encodedKey);
}
}
idbModules.DEBUG && console.log("Trying to fetch data for Index", sql.join(" "), sqlValues);
tx.executeSql(sql.join(" "), sqlValues, function(tx, data) {
var recordCount = 0, record = null;
if (me.multiEntry) {
for (var i = 0; i < data.rows.length; i++) {
var row = data.rows.item(i);
var rowKey = idbModules.Key.decode(row[me.name]);
if (hasKey && idbModules.Key.isMultiEntryMatch(encodedKey, row[me.name])) {
recordCount++;
record = record || row;
}
else if (!hasKey && rowKey !== undefined) {
recordCount = recordCount + (rowKey instanceof Array ? rowKey.length : 1);
record = record || row;
}
}
}
else {
recordCount = data.rows.length;
record = recordCount && data.rows.item(0);
}
if (opType === "count") {
success(recordCount);
}
else if (recordCount === 0) {
success(undefined);
}
else if (opType === "key") {
success(idbModules.Key.decode(record.key));
}
else { // when opType is value
success(idbModules.Sca.decode(record.value));
}
}, error);
});
};
/**
* Opens a cursor over the given key range.
* @param {IDBKeyRange} range
* @param {string} direction
* @returns {IDBRequest}
*/
IDBIndex.prototype.openCursor = function(range, direction) {
return new idbModules.IDBCursor(range, direction, this.objectStore, this, this.name, "value").__req;
};
/**
* Opens a cursor over the given key range. The cursor only includes key values, not data.
* @param {IDBKeyRange} range
* @param {string} direction
* @returns {IDBRequest}
*/
IDBIndex.prototype.openKeyCursor = function(range, direction) {
return new idbModules.IDBCursor(range, direction, this.objectStore, this, this.name, "key").__req;
};
IDBIndex.prototype.get = function(key) {
if (arguments.length === 0) {
throw new TypeError("No key was specified");
}
return this.__fetchIndexData(key, "value");
};
IDBIndex.prototype.getKey = function(key) {
if (arguments.length === 0) {
throw new TypeError("No key was specified");
}
return this.__fetchIndexData(key, "key");
};
IDBIndex.prototype.count = function(key) {
// key is optional
if (key === undefined) {
return this.__fetchIndexData("count");
}
else if (key instanceof idbModules.IDBKeyRange) {
return new idbModules.IDBCursor(key, "next", this.objectStore, this, this.name, "value", true).__req;
}
else {
return this.__fetchIndexData(key, "count");
}
};
idbModules.IDBIndex = IDBIndex;
}(idbModules));