Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does indexedDB use a "version"?

I'm just learning about indexedDB, and this is my understanding of setting up a database. You call .open(dbName) to get a DB instance. If no database of this name exists on the user's computer (for instance if this is their first visit to the site) then this triggers an onUpdateNeeded event, which is therefore where you should do initialization stuff like creating the ObjectStores.

Now, you can also pass in a version - .open(dbName, version) - and if the database exists but uses a lower version, this forces an onUpdateNeeded event regardless. Now, I can see the utility of this... but why have an integer argument? If the point of the "version" argument is to force updates, why not just have a forceUpdate flag? Why have an integer version argument which you therefore need to increment ever higher as you debug your code, presumably reaching version 156 after many days of debugging?

Is the version used in some functionality that I'm not aware of beyond just forcing updates, and if not, what is the rationale behind it? Also, are you intended to just keep changing the version during development but keep it fixed once the app is released, or is the idea that you should keep changing it throughout the lifecycle of your app?

like image 457
Jack M Avatar asked Dec 15 '15 21:12

Jack M


1 Answers

The monotonically increasing integer allows this pattern:

var open = indexedDB.open('db', 3);
open.onupgradeneeded = function(e) {
  var db = open.result;
  if (e.oldVersion < 1) {
    // create v1 schema
  }
  if (e.oldVersion < 2) {
    // upgrade v1 to v2 schema
  }
  if (e.oldVersion < 3) {
    // upgrade v2 to v3 schema
  }
  // ...
};
open.onsuccess = function() {
  var db = open.result;
  // ...
};

This is a very common pattern. Obviously, one could imagine that this is done manually - developers could track a version in a special metadata table - rather than enshrining it in the standard. But it's common enough that it was built-in, similar to indexes and key generators.

There's a valid argument that this makes the API too complicated for beginners, but without a time machine it's somewhat moot.

...

If you're debugging locally and the changes are constrained to your machine then deleting/recreating the database is probably easier than writing schema upgrade logic for each minor change.

like image 170
Joshua Bell Avatar answered Sep 19 '22 15:09

Joshua Bell