aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/gears/basestore.js
blob: 5db01fa1d76c252ca134ec07b87e009e645e7fc7 (plain)
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
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// 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 Definition of goog.gears.BaseStore which
 * is a base class for the various database stores. It provides
 * the basic structure for creating, updating and removing the store, as well
 * as versioning. It also provides ways to interconnect stores.
 *
 */

goog.provide('goog.gears.BaseStore');
goog.provide('goog.gears.BaseStore.SchemaType');

goog.require('goog.Disposable');



/**
 * This class implements the common store functionality
 *
 * @param {goog.gears.Database} database The data base to store the data in.
 * @constructor
 * @extends {goog.Disposable}
 */
goog.gears.BaseStore = function(database) {
  goog.Disposable.call(this);

  /**
   * The underlying database that holds the message store.
   * @private
   * @type {goog.gears.Database}
   */
  this.database_ = database;
};
goog.inherits(goog.gears.BaseStore, goog.Disposable);


/**
 * Schema definition types
 * @enum {number}
 */
goog.gears.BaseStore.SchemaType = {
  TABLE: 1,
  VIRTUAL_TABLE: 2,
  INDEX: 3,
  BEFORE_INSERT_TRIGGER: 4,
  AFTER_INSERT_TRIGGER: 5,
  BEFORE_UPDATE_TRIGGER: 6,
  AFTER_UPDATE_TRIGGER: 7,
  BEFORE_DELETE_TRIGGER: 8,
  AFTER_DELETE_TRIGGER: 9
};


/**
 * The name of the store. Subclasses should override and choose their own
 * name. That name is used for the maintaining the version string
 * @protected
 * @type {string}
 */
goog.gears.BaseStore.prototype.name = 'Base';


/**
 * The version number of the database schema. It is used to determine whether
 * the store's portion of the database needs to be updated. Subclassses should
 * override this value.
 * @protected
 * @type {number}
 */
goog.gears.BaseStore.prototype.version = 1;


/**
 * The database schema for the store. This is an array of objects, where each
 * object describes a database object (table, index, trigger). Documentation
 * about the object's fields can be found in the #createSchema documentation.
 * This is in the prototype so that it can be overriden by the subclass. This
 * field is read only.
 * @protected
 * @type {Array.<Object>}
 */
goog.gears.BaseStore.prototype.schema = [];


/**
 * Gets the underlying database.
 * @return {goog.gears.Database}
 * @protected
 */
goog.gears.BaseStore.prototype.getDatabaseInternal = function() {
  return this.database_;
};


/**
 * Updates the tables for the message store in the case where
 * they are out of date.
 *
 * @protected
 * @param {number} persistedVersion the current version of the tables in the
 * database.
 */
goog.gears.BaseStore.prototype.updateStore = function(persistedVersion) {
  // TODO(user): Need to figure out how to handle updates
  // where to store the version number and is it globale or per unit.
};


/**
 * Preloads any applicable data into the tables.
 *
 * @protected
 */
goog.gears.BaseStore.prototype.loadData = function() {
};


/**
 * Creates in memory cache of data that is stored in the tables.
 *
 * @protected
 */
goog.gears.BaseStore.prototype.getCachedData = function() {
};


/**
 * Informs other stores that this store exists .
 *
 * @protected
 */
goog.gears.BaseStore.prototype.informOtherStores = function() {
};


/**
 * Makes sure that tables needed for the store exist and are up to date.
 */
goog.gears.BaseStore.prototype.ensureStoreExists = function() {
  var persistedVersion = this.getStoreVersion();

  if (persistedVersion) {
    if (persistedVersion != this.version) {
      // update
      this.database_.begin();
      try {
        this.updateStore(persistedVersion);
        this.setStoreVersion_(this.version);
        this.database_.commit();
      } catch (ex) {
        this.database_.rollback(ex);
        throw Error('Could not update the ' + this.name + ' schema ' +
            ' from version ' + persistedVersion + ' to ' + this.version +
            ': ' + (ex.message || 'unknown exception'));
      }
    }
  } else {
    // create
    this.database_.begin();
    try {
      // This is rarely necessary, but it's possible if we rolled back a
      // release and dropped the schema on version n-1 before installing
      // again on version n.
      this.dropSchema(this.schema);

      this.createSchema(this.schema);

      // Ensure that the version info schema exists.
      this.createSchema([{
        type: goog.gears.BaseStore.SchemaType.TABLE,
        name: 'StoreVersionInfo',
        columns: [
          'StoreName TEXT NOT NULL PRIMARY KEY',
          'Version INTEGER NOT NULL'
        ]}], true);
      this.loadData();
      this.setStoreVersion_(this.version);
      this.database_.commit();
    } catch (ex) {
      this.database_.rollback(ex);
      throw Error('Could not create the ' + this.name + ' schema' +
          ': ' + (ex.message || 'unknown exception'));
    }
  }
  this.getCachedData();
  this.informOtherStores();
};


/**
 * Removes the tables for the MessageStore
 */
goog.gears.BaseStore.prototype.removeStore = function() {
  this.database_.begin();
  try {
    this.removeStoreVersion();
    this.dropSchema(this.schema);
    this.database_.commit();
  } catch (ex) {
    this.database_.rollback(ex);
    throw Error('Could not remove the ' + this.name + ' schema' +
            ': ' + (ex.message || 'unknown exception'));
  }
};


/**
 * Returns the name of the store.
 *
 * @return {string} The name of the store.
 */
goog.gears.BaseStore.prototype.getName = function() {
  return this.name;
};


/**
 * Returns the version number for the specified store
 *
 * @return {number} The version number of the store. Returns 0 if the
 *     store does not exist.
 */
goog.gears.BaseStore.prototype.getStoreVersion = function() {
  try {
    return /** @type {number} */ (this.database_.queryValue(
        'SELECT Version FROM StoreVersionInfo WHERE StoreName=?',
        this.name)) || 0;
  } catch (ex) {
    return 0;
  }
};


/**
 * Sets the version number for the specified store
 *
 * @param {number} version The version number for the store.
 * @private
 */
goog.gears.BaseStore.prototype.setStoreVersion_ = function(version) {
  // TODO(user): Need to determine if we should enforce the fact
  // that store versions are monotonically increasing.
  this.database_.execute(
      'INSERT OR REPLACE INTO StoreVersionInfo ' +
      '(StoreName, Version) VALUES(?,?)',
      this.name,
      version);
};


/**
 * Removes the version number for the specified store
 */
goog.gears.BaseStore.prototype.removeStoreVersion = function() {
  try {
    this.database_.execute(
        'DELETE FROM StoreVersionInfo WHERE StoreName=?',
        this.name);
  } catch (ex) {
    // Ignore error - part of bootstrap process.
  }
};


/**
 * Generates an SQLITE CREATE TRIGGER statement from a definition array.
 * @param {string} onStr the type of trigger to create.
 * @param {Object} def  a schema statement definition.
 * @param {string} notExistsStr string to be included in the create
 *     indicating what to do.
 * @return {string} the statement.
 * @private
 */
goog.gears.BaseStore.prototype.getCreateTriggerStatement_ =
    function(onStr, def, notExistsStr) {
  return 'CREATE TRIGGER ' + notExistsStr + def.name + ' ' +
         onStr + ' ON ' + def.tableName +
         (def.when ? (' WHEN ' + def.when) : '') +
         ' BEGIN ' + def.actions.join('; ') + '; END';
};


/**
 * Generates an SQLITE CREATE statement from a definition object.
 * @param {Object} def  a schema statement definition.
 * @param {boolean=} opt_ifNotExists true if the table or index should be
 *     created only if it does not exist. Otherwise trying to create a table
 *     or index that already exists will result in an exception being thrown.
 * @return {string} the statement.
 * @private
 */
goog.gears.BaseStore.prototype.getCreateStatement_ =
    function(def, opt_ifNotExists) {
  var notExists = opt_ifNotExists ? 'IF NOT EXISTS ' : '';
  switch (def.type) {
    case goog.gears.BaseStore.SchemaType.TABLE:
      return 'CREATE TABLE ' + notExists + def.name + ' (\n' +
             def.columns.join(',\n  ') +
             ')';
    case goog.gears.BaseStore.SchemaType.VIRTUAL_TABLE:
      return 'CREATE VIRTUAL TABLE ' + notExists + def.name +
             ' USING FTS2 (\n' + def.columns.join(',\n  ') + ')';
    case goog.gears.BaseStore.SchemaType.INDEX:
      return 'CREATE' + (def.isUnique ? ' UNIQUE' : '') +
             ' INDEX ' + notExists + def.name + ' ON ' +
             def.tableName + ' (\n' + def.columns.join(',\n  ') + ')';
    case goog.gears.BaseStore.SchemaType.BEFORE_INSERT_TRIGGER:
      return this.getCreateTriggerStatement_('BEFORE INSERT', def, notExists);
    case goog.gears.BaseStore.SchemaType.AFTER_INSERT_TRIGGER:
      return this.getCreateTriggerStatement_('AFTER INSERT', def, notExists);
    case goog.gears.BaseStore.SchemaType.BEFORE_UPDATE_TRIGGER:
      return this.getCreateTriggerStatement_('BEFORE UPDATE', def, notExists);
    case goog.gears.BaseStore.SchemaType.AFTER_UPDATE_TRIGGER:
      return this.getCreateTriggerStatement_('AFTER UPDATE', def, notExists);
    case goog.gears.BaseStore.SchemaType.BEFORE_DELETE_TRIGGER:
      return this.getCreateTriggerStatement_('BEFORE DELETE', def, notExists);
    case goog.gears.BaseStore.SchemaType.AFTER_DELETE_TRIGGER:
      return this.getCreateTriggerStatement_('AFTER DELETE', def, notExists);
  }
  return '';
};


/**
 * Generates an SQLITE DROP statement from a definition array.
 * @param {Object} def  a schema statement definition.
 * @return {string} the statement.
 * @private
 */
goog.gears.BaseStore.prototype.getDropStatement_ = function(def) {
  switch (def.type) {
    case goog.gears.BaseStore.SchemaType.TABLE:
    case goog.gears.BaseStore.SchemaType.VIRTUAL_TABLE:
      return 'DROP TABLE IF EXISTS ' + def.name;
    case goog.gears.BaseStore.SchemaType.INDEX:
      return 'DROP INDEX IF EXISTS ' + def.name;
    case goog.gears.BaseStore.SchemaType.BEFORE_INSERT_TRIGGER:
    case goog.gears.BaseStore.SchemaType.AFTER_INSERT_TRIGGER:
    case goog.gears.BaseStore.SchemaType.BEFORE_UPDATE_TRIGGER:
    case goog.gears.BaseStore.SchemaType.AFTER_UPDATE_TRIGGER:
    case goog.gears.BaseStore.SchemaType.BEFORE_DELETE_TRIGGER:
    case goog.gears.BaseStore.SchemaType.AFTER_DELETE_TRIGGER:
      return 'DROP TRIGGER IF EXISTS ' + def.name;
  }
  return '';
};


/**
 * Creates tables and indicies in the target database.
 *
 * @param {Array} defs  definition arrays. This is an array of objects
 *    where each object describes a database object to create and drop.
 *    each object contains a 'type' field which of type
 *    goog.gears.BaseStore.SchemaType. Each object also contains a
 *    'name' which contains the name of the object to create.
 *    A table object contains a 'columns' field which is an array
 *       that contains the column definitions for the table.
 *    A virtual table object contains c 'columns' field which contains
 *       the name of the columns. They are assumed to be of type text.
 *    An index object contains a 'tableName' field which is the name
 *       of the table that the index is on. It contains an 'isUnique'
 *       field which is a boolean indicating whether the index is
 *       unqiue or not. It also contains a 'columns' field which is
 *       an array that contains the columns names (possibly along with the
 *       ordering) that form the index.
 *    The trigger objects contain a 'tableName' field indicating the
 *       table the trigger is on. The type indicates the type of trigger.
 *       The trigger object may include a 'when' field which contains
 *       the when clause for the trigger. The trigger object also contains
 *       an 'actions' field which is an array of strings containing
 *       the actions for this trigger.
 * @param {boolean=} opt_ifNotExists true if the table or index should be
 *     created only if it does not exist. Otherwise trying to create a table
 *     or index that already exists will result in an exception being thrown.
 */
goog.gears.BaseStore.prototype.createSchema = function(defs, opt_ifNotExists) {
  this.database_.begin();
  try {
    for (var i = 0; i < defs.length; ++i) {
      var sql = this.getCreateStatement_(defs[i], opt_ifNotExists);
      this.database_.execute(sql);
    }
    this.database_.commit();
  } catch (ex) {
    this.database_.rollback(ex);
  }
};


/**
 * Drops tables and indicies in a target database.
 *
 * @param {Array} defs Definition arrays.
 */
goog.gears.BaseStore.prototype.dropSchema = function(defs) {
  this.database_.begin();
  try {
    for (var i = defs.length - 1; i >= 0; --i) {
      this.database_.execute(this.getDropStatement_(defs[i]));
    }
    this.database_.commit();
  } catch (ex) {
    this.database_.rollback(ex);
  }
};


/**
 * Creates triggers specified in definitions. Will first attempt
 * to drop the trigger with this name first.
 *
 * @param {Array} defs Definition arrays.
 */
goog.gears.BaseStore.prototype.createTriggers = function(defs) {
  this.database_.begin();
  try {
    for (var i = 0; i < defs.length; i++) {
      var def = defs[i];
      switch (def.type) {
        case goog.gears.BaseStore.SchemaType.BEFORE_INSERT_TRIGGER:
        case goog.gears.BaseStore.SchemaType.AFTER_INSERT_TRIGGER:
        case goog.gears.BaseStore.SchemaType.BEFORE_UPDATE_TRIGGER:
        case goog.gears.BaseStore.SchemaType.AFTER_UPDATE_TRIGGER:
        case goog.gears.BaseStore.SchemaType.BEFORE_DELETE_TRIGGER:
        case goog.gears.BaseStore.SchemaType.AFTER_DELETE_TRIGGER:
          this.database_.execute('DROP TRIGGER IF EXISTS ' + def.name);
          this.database_.execute(this.getCreateStatement_(def));
          break;
      }
    }
    this.database_.commit();
  } catch (ex) {
    this.database_.rollback(ex);
  }
};


/**
 * Returns true if the table exists in the database
 *
 * @param {string} name The table name.
 * @return {boolean} Whether the table exists in the database.
 */
goog.gears.BaseStore.prototype.hasTable = function(name) {
  return this.hasInSchema_('table', name);
};


/**
 * Returns true if the index exists in the database
 *
 * @param {string} name The index name.
 * @return {boolean} Whether the index exists in the database.
 */
goog.gears.BaseStore.prototype.hasIndex = function(name) {
  return this.hasInSchema_('index', name);
};


/**
 * @param {string} name The name of the trigger.
 * @return {boolean} Whether the schema contains a trigger with the given name.
 */
goog.gears.BaseStore.prototype.hasTrigger = function(name) {
  return this.hasInSchema_('trigger', name);
};


/**
 * Returns true if the database contains the index or table
 *
 * @private
 * @param {string} type The type of object to test for, 'table' or 'index'.
 * @param {string} name The table or index name.
 * @return {boolean} Whether the database contains the index or table.
 */
goog.gears.BaseStore.prototype.hasInSchema_ = function(type, name) {
  return this.database_.queryValue('SELECT 1 FROM SQLITE_MASTER ' +
      'WHERE TYPE=? AND NAME=?',
      type,
      name) != null;
};


/** @override */
goog.gears.BaseStore.prototype.disposeInternal = function() {
  goog.gears.BaseStore.superClass_.disposeInternal.call(this);
  this.database_ = null;
};


/**
 * HACK(arv): The JSCompiler check for undefined properties sees that these
 * fields are never set and raises warnings.
 * @type {Array.<Object>}
 * @private
 */
goog.gears.schemaDefDummy_ = [
  {
    type: '',
    name: '',
    when: '',
    tableName: '',
    actions: [],
    isUnique: false
  }
];