My favorites
▼
|
Sign in
webstorageportabilitylayer
Portable database access using Gears or HTML5 databases
Project Home
Wiki
Issues
Source
Export to GitHub
Checkout
Browse
Changes
Source path:
svn
/
trunk
/
simplenotes
/
simplenotes.js
r2
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
/*
Copyright 2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @fileoverview A concrete example of the cache pattern for building an offline
* webapplication: a cache for SimpleNotes.
*/
google.wspl.simplenotes = google.wspl.simplenotes || {};
google.logger('start simplenotes.js');
/**
* Status keys for the write buffer.
* @enum {number}
*/
google.wspl.simplenotes.WriteBufferStates = {
/**
* The update is in flight to the server.
*/
INFLIGHT: 1,
/**
* The update needs to be (re)sent to the server but is not in flight.
*/
SEND: 2,
/**
* The update needs to be applied to the cached notes.
*/
REAPPLY: 8
};
/**
* Creates a SimpleNotes cache wrapping a backing database.
* @constructor
*/
google.wspl.simplenotes.Cache = function() {
this.dbms_ = google.wspl.DatabaseFactory.createDatabase(
'simple-notes', 'http://yourdomain/dbworker.js');
/**
* Cache directory is a two-tuple over a range. (Holes
* must be allowed to support delection.)
* This is the lower (inclusive) bound of the cached range.
* @type {number}
* @private
*/
this.start_ = -1;
/**
*
* This is the upper (inclusive) bound of the cached range.
* @type {number}
* @private
*/
this.end_ = -1;
/**
* Start of range of notes known to exist on server at time of last
* response.
* @param {number}
*/
this.serverStart_ = -1;
/**
* End of range of notes known to exist on server at time of last
* response.
* @param {number}
*/
this.serverEnd_ = -1;
/**
* Time of last refresh.
* @type {number}
* @private
*/
this.lastRefresh_ = -1;
/**
* Last missing query.
* @type {Object}
* @private
*/
this.lastMiss_ = undefined;
};
/**
* Interval between refreshes in milliseconds.
* @type {number}
* @private
*/
google.wspl.simplenotes.Cache.TIME_BETWEEN_REFRESH_ = 2000;
google.wspl.simplenotes.Cache.CREATE_CACHED_NOTES_ =
new google.wspl.Statement(
'CREATE TABLE IF NOT EXISTS cached_notes (' +
'noteKey INTEGER UNIQUE PRIMARY KEY,' +
'subject TEXT,' +
'body TEXT' +
');'
);
google.wspl.simplenotes.Cache.CREATE_WRITE_BUFFER_ =
new google.wspl.Statement(
'CREATE TABLE IF NOT EXISTS write_buffer (' +
'sequence INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT,' +
'noteKey INTEGER,' +
'status INTEGER,' +
'subject TEXT,' +
'body TEXT' +
');'
);
google.wspl.simplenotes.Cache.DETERMINE_MIN_KEY_ =
new google.wspl.Statement(
'SELECT MIN(noteKey) as minNoteKey FROM cached_notes;');
google.wspl.simplenotes.Cache.DETERMINE_MAX_KEY_ =
new google.wspl.Statement(
'SELECT MAX(noteKey) as maxNoteKey FROM cached_notes;');
/**
* Builds a cache and writebuffer combination for notes and then
* invokes the given callback.
* @param {function) callback.
*/
google.wspl.simplenotes.Cache.prototype.startCache = function(callback) {
google.logger('startCache');
var statc = 0;
var self = this;
var perStatCallback = function(tx, result) {
google.logger('perStatCallback');
if (statc == 4) {
self.start_ = (result.isValidRow()) ? result.getRow().minNoteKey : -1;
self.serverStart_ = self.start_; // Temporary. Remove when server exists.
} else if (statc == 5) {
self.end_ = (result.isValidRow()) ? result.getRow().maxNoteKey : -1;
self.serverEnd_ = self.end_; // Temporary. Remove when server exists.
}
statc++;
};
this.dbms_.executeAll([
google.wspl.simplenotes.Cache.CREATE_CACHED_NOTES_,
google.wspl.simplenotes.Cache.CREATE_WRITE_BUFFER_,
google.wspl.simplenotes.Cache.CREATE_UPDATE_TRIGGER_,
google.wspl.simplenotes.Cache.CREATE_REPLAY_TRIGGER_,
google.wspl.simplenotes.Cache.DETERMINE_MIN_KEY_,
google.wspl.simplenotes.Cache.DETERMINE_MAX_KEY_],
{onSuccess: perStatCallback, onFailure: this.logError_},
{onSuccess: callback, onFailure: this.logError_});
google.logger('finished startCache');
};
/**
* Stub function to be replaced with a server communication.
* @param {Array.<Object>} updates Payload to send to server.
*/
google.wspl.simplenotes.Cache.prototype.sendXhrPost = function(updates) {
google.logger('Should dispatch XHR to server now.');
};
/**
* @type {google.wspl.Statement}
* @private
*/
google.wspl.simplenotes.Cache.LIST_CACHED_NOTES_ =
new google.wspl.Statement(
'SELECT noteKey, subject from cached_notes WHERE ' +
'noteKey >= ? AND ' +
'noteKey <= ? ' +
';'
);
/**
* Tests if the given range is stored in the cache.
* Note that this mechanism requires extension to handle the
* creation of new notes.
* @param {number} start Lower bound (inclusive) on range.
* @param {number} end Uppder bound (inclusive) on range.
* @private
*/
google.wspl.simplenotes.Cache.prototype.isCacheHit_ = function(start, end) {
return start >= this.start_ && end <= this.end_
};
/**
* Logs a possibly useful error message.
* @param {Object} error An error descriptor.
* @private
*/
google.wspl.simplenotes.Cache.prototype.logError_ = function(error) {
google.logger('Simple Notes Cache is sad: ' + error);
};
/**
* Queries the cache for a list of note headers.
* @param {number} start The lower id in a range of notes.
* @param {number} end The higher id in a range of notes.
* @param {function(Array.<Object>)} valuesCallback A function to call
* with the result set after the transaction has completed.
* @private
*/
google.wspl.simplenotes.Cache.prototype.getNoteList_ = function(start, end,
valuesCallback) {
var notes = [];
var accumulateResults = function(tx, result) {
for(; result.isValidRow(); result.next()) {
notes.push(result.getRow());
google.logger('pushed...');
}
};
var inTransactionGetNotes = function(tx) {
tx.execute(google.wspl.simplenotes.Cache.LIST_CACHED_NOTES_.
createStatement([start, end]), {
onSuccess: accumulateResults,
onFailure: this.logError_});
};
var hit = this.isCacheHit_(start, end);
this.dbms_.createTransaction(inTransactionGetNotes, {onSuccess: function() {
valuesCallback(notes, hit);
}, onFailure: this.logError_});
if (hit) {
this.fetchFromServer(this.start_, this.end_); // Refresh
} else {
this.fetchFromServer(Math.min(this.start_, start), Math.max(this.end_, end));
this.lastMiss_ = {callback: valuesCallback, start: start, end: end};
}
};
/**
* @type {google.wspl.Statement}
* @private
*/
google.wspl.simplenotes.Cache.GET_ONE_NOTE_ =
new google.wspl.Statement(
'SELECT noteKey, subject, body from cached_notes WHERE ' +
'noteKey = ? ' +
';'
);
/**
* Queries the cache for a list of note headers.
* @param {number} noteId The note to get from the cache.
* @param {function(Array.<Object>)} valuesCallback A function to call
* with the result set after the transaction has completed.
* @private
*/
google.wspl.simplenotes.Cache.prototype.getOneNote_ = function(noteId,
callback) {
var note;
this.dbms_.execute(google.wspl.simplenotes.Cache.GET_ONE_NOTE_.
createStatement([noteId]),
{onSuccess: function(tx, result) { note = result.getRow(); },
onFailure: this.logError_},
{onSuccess: function() { callback(note, true); },
onFailure: this.logError_});
};
/**
* Queries the cache for either a list of notes or a single note including
* its body.
* @param {string} type The kind of values desired: 'list' or 'fullnote'.
* @param {Array.<number>} query The query for the values.
* @param {function(Array.<Object>)} valuesCallback A function to call
* with the result set after the transaction has completed.
*/
google.wspl.simplenotes.Cache.prototype.getValues = function(type,
query, valuesCallback) {
// Reduce any query to what would be available from the server
query[0] = Math.max(this.serverStart_, query[0]);
query[1] = Math.min(this.serverEnd_, query[1]);
if (type == 'list') {
this.getNoteList_(query[0], query[1], valuesCallback);
} else if (type == 'fullnote') {
this.getOneNote_(query[0], valuesCallback);
}
};
/**
* SQL trigger to insert a new change from write buffer to
* cache.
* @private
*/
google.wspl.simplenotes.Cache.CREATE_UPDATE_TRIGGER_ =
new google.wspl.Statement(
'CREATE TRIGGER IF NOT EXISTS updateTrigger ' +
'AFTER INSERT ON write_buffer ' +
'BEGIN ' +
' REPLACE INTO cached_notes ' +
' SELECT noteKey, subject, body ' +
' FROM write_buffer WHERE status & 8 = 8; ' +
' UPDATE write_buffer SET status = status & ~ 8; ' +
'END;'
);
/**
* SQL trigger to replay changes from the write buffer to
* the cache.
* @private
*/
google.wspl.simplenotes.Cache.CREATE_REPLAY_TRIGGER_ =
new google.wspl.Statement(
'CREATE TRIGGER IF NOT EXISTS replayTrigger ' +
'AFTER UPDATE ON write_buffer WHEN NEW.status & 8 = 8 ' +
'BEGIN ' +
' REPLACE INTO cached_notes ' +
' SELECT noteKey, subject, body ' +
' FROM write_buffer ' +
' WHERE noteKey = NEW.noteKey ' +
' ORDER BY sequence ASC;' +
' UPDATE write_buffer SET status = status & ~ 8; ' +
'END;'
);
/**
* SQL statement to mark actions for replay.
*/
google.wspl.simplenotes.Cache.MARK_FOR_REPLAY =
new google.wspl.Statement(
'UPDATE write_buffer SET status = status | 8;');
/**
* SQL statement to insert notes updates.
* @type {!google.wspl.Statement}
* @private
*/
google.wspl.simplenotes.Cache.INSERT_UI_UPDATE_ =
new google.wspl.Statement(
'INSERT INTO write_buffer (' +
'noteKey, status, subject, body' +
') ' + 'VALUES(?,?,?,?);');
/**
* Updates the given entry and write a new write buffer entry.
* @param {number} noteKey
* @param {string} subject
* @param {string} body
* @param {function(number)} ackCallback
*/
google.wspl.simplenotes.Cache.prototype.applyUiChange = function(noteKey,
subject, body, ackCallback) {
var self = this;
var update = [noteKey, 2 | 8, subject, body];
var stat = google.wspl.simplenotes.Cache.INSERT_UI_UPDATE_.createStatement(
update);
this.dbms_.execute(stat, null, {onSuccess: function() {
google.logger('applyUiChange cb');
ackCallback(noteKey);
}, onFailure: function (error) {
self.logError_(error);
ackCallback(-1);
}});
};
/**
* SQL statement to insert notes updates.
* @type {!google.wspl.Statement}
* @private
*/
google.wspl.simplenotes.Cache.INSERT_NOTE_ =
new google.wspl.Statement(
'REPLACE INTO cached_notes (noteKey, subject, body) ' +
'VALUES(?,?,?);' );
/**
* SQL statement to force replay of pending actions by setting a bit
* flag on each write-buffer row indicating that it should be reapplied
* to the contents of the cache.
* @type {!google.wspl.Statement}
* @private
*/
google.wspl.simplenotes.Cache.FORCE_REPLAY_ =
new google.wspl.Statement(
'UPDATE write_buffer SET status = status | 8;' );
/**
* SQL statement to delete notes no longer to be cached.
* @type {!google.wspl.Statement}
* @private
*/
google.wspl.simplenotes.Cache.EVICT_ =
new google.wspl.Statement(
'DELETE FROM cached_notes WHERE noteKey < ? OR noteKey > ?;');
/**
* Applies the changes delivered from the server by first inserting
* them into the cache and reapplying the write-buffer to the cache.
* @param {!Array.<Object>} notes An array of arrays.
*/
google.wspl.simplenotes.Cache.prototype.insertUpdate = function(notes) {
var self = this; var stats = [];
var start = notes[0].noteKey;
var end = notes[0].noteKey;
for (var i = 0; i < notes.length; i++) {
stats.push(google.wspl.simplenotes.Cache.INSERT_NOTE_.
createStatement([notes[i].noteKey, notes[i].subject, notes[i].body]));
start = Math.min(start, notes[0].noteKey);
end = Math.max(end, notes[0].noteKey);
}
stats.push(google.wspl.simplenotes.Cache.EVICT_.createStatement([start, end]));
stats.push(google.wspl.simplenotes.Cache.FORCE_REPLAY_);
var inTrans = function(tx) {
self.start_ = start;
self.end_ = end;
tx.executeAll(stats);
};
var afterInsert = function(tx) {
if (this.lastMiss_ &&
this.isCacheHit_(this.lastMiss_.start, this.lastMiss_.end)) {
this.lastMiss_.callback(notes);
this.lastMiss_ = undefined;
}
};
this.dbms_.createTransaction(inTrans, {onSuccess: afterInsert,
onError: this.logError_});
};
/**
* SQL statement to force replay of pending actions by setting a bit
* flag on each write-buffer row indicating that it should be reapplied
* to the contents of the cache.
* @type {!google.wspl.Statement}
* @private
*/
google.wspl.simplenotes.Cache.GET_UPDATES_TO_RESEND_ =
new google.wspl.Statement(
'SELECT noteKey, subject, body FROM write_buffer WHERE status & 2 = 2;');
/**
* SQL statement to mark write buffer statements as inflight.
* @type {!google.wspl.Statement}
* @private
*/
google.wspl.simplenotes.Cache.MARK_AS_INFLIGHT_ =
new google.wspl.Statement(
'UPDATE write_buffer SET status = status & ~2 | 1 WHERE status & 2 = 2;');
/**
* Fetches new material from the server as required.
* @param {number} start
* @param {number} end
* @param {function} opt_valueCallBack
*/
google.wspl.simplenotes.Cache.prototype.fetchFromServer = function(start,
end) {
google.logger('fetchFromServer');
var now = this.dbms_.getCurrentTime();
if (start >= this.start_ && end <= this.end_ &&
now - this.lastRefresh_ <
google.wspl.simplenotes.Cache.TIME_BETWEEN_REFRESH_) {
return;
}
var updates = []; var self = this; var flag = 1; var sql = []
sql.push(google.wspl.simplenotes.Cache.GET_UPDATES_TO_RESEND_);
sql.push(google.wspl.simplenotes.Cache.MARK_AS_INFLIGHT_);
var accumulateUpdates = function(tx, rs) {
if (flag == 1) {
for(; rs.isValidRow(); rs.next()) { updates.push(['u', rs.getRow()]); }
flag++;
}
};
var ackAndPost = function() {
updates.push(['q', {start: start, end: end}]);
self.sendXhrPost(updates);
};
this.dbms_.executeAll(sql,
{onSuccess: accumulateUpdates, onFailure: this.logError_},
{onSuccess: ackAndPost, onFailure: this.logError_});
};
Show details
Hide details
Change log
r1
by robkroeger on May 25, 2009
Diff
Initial import of web storage portability layer
Go to:
/trunk
/trunk/README
/trunk/databasefactory.js
/trunk/dbworker.js
/trunk/dbworker_test.html
/trunk/dbworkerstarter.js
/trunk/dbwrapper_gears.js
/trunk/dbwrapper_gears_test.html
/trunk/dbwrapper_html5.js
/trunk/dbwrapper_html5_test.html
/trunk/dbwrapperapi.js
/trunk/dbwrapperapi_test.html
/trunk/gears_resultset.js
/trunk/gears_resultset_test.html
/trunk/gears_transaction.js
/trunk/gears_transaction_test.html
/trunk/gearsutils.js
/trunk/gearsutils_test.html
/trunk/global_functions.js
/trunk/simplenotes
/trunk/simplenotes/index.html
/trunk/simplenotes/simplenotes.js
/trunk/simplenotes/styles.css
/trunk/simplenotes/template.js
Project members,
sign in
to write a code review
Older revisions
All revisions of this file
File info
Size: 14884 bytes, 503 lines
View raw file
Powered by
Google Project Hosting