Saturday, February 4, 2012

Indexed DB: To provide a key or not to provide a key

I am currently busy writing a little framework around the Indexed DB API to make it easier to use Indexed DB. One of the things I was struggling with was when the key parameter must or mustn’t be provided. So I tested every possible combinations.

For this I created 4 object stores with different combinations:

  • Object store 1: KeyPath: “Id”, autoIncrement = true
  • Object store 2: KeyPath: undefined, autoIncrement = true
  • Object store 3: KeyPath: “Id”, autoIncrement = false
  • Object store 4: KeyPath: undefined, autoIncrement = false

Next, I tried adding four different combinations, and here are the results.

Add/Put parameters

Object store configuration

Value

Key

Object store 1

Object store 2

Object store 3

Object store 4

{ Name: "test" } undefined successful successful failed failed
{ Id: 1, Name: "test" } undefined successful successful successful failed
{ Name: "test" } 1 failed successful failed successful
{ Id: 1, Name: "test" } 1 failed successful failed successful

 

Conclusion

  1. When a KeyPath is defined, the key parameter must be undefined
  2. When no KeyPath is defined and there is no autoIncrement, a key must be provided
  3. When no KeyPath is defined and there is autoIncrement, a key can be provided
  4. When a KeyPath is defined and there is no autoIncrement, an attribute with the name of the KeyPath must be present.

2 comments: