3

I'm having problems with this code when I upgrade the version without any other modification, and I can't understand the reason.

function create_registry() {
    var version = 1;
    var indexeddb_db = "examples"; // database
    var indexeddb_table = "examples_table"; // table

    // open the database
    var indexeddb_request = indexedDB.open( indexeddb_db, version ); // connect + open database
    var db = false;

    // if error
    indexeddb_request.onerror = function ( event ) {
        console.log( event.target );
        console.trace();
    }

    // if success
    indexeddb_request.onsuccess = function ( event ) {
        console.log( event.target );
        console.trace();
    }

    // if onupgradeneeded
    indexeddb_request.onupgradeneeded = function( event ) {
        console.log( event.target );
        console.trace();
        db = event.target.result;
        var objectStore = db.createObjectStore( indexeddb_table, { keyPath: 'url' } );
    }

}

The first time that the page is loaded, the indexedDB object (database) is created and the table inside is created. Everything works fine. First the onupgradeneeded is executed and then the onsuccess is launched.

If I reload the page without any changes, everything works fine, the onsuccess is launched.

But, if I change the version number, then I get the errors mentioned below. Those errors are described briefly in the W3C spec of the Indexed Database API, but that doesn't help me much so far. After the onupgradeneeded is executed, the onerror is execute and there I have an AbortError, but that doesn't tell me much more either.

Chrome 28 "Uncaught Error: ConstraintError: DOM IDBDatabase Exception 0"

Firefox 22 "A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one. "

As far as I can tell, the problem is that I'm trying to recreate the same object with the same keypath, but isn't the new version making the script recreate the whole object?

Why Am I getting the error? Shouldn't the onupgradeneeded just update the version number and rewrite the object (database)?

4

1 回答 1

6

据我所知,问题是我正在尝试使用相同的键路径重新创建相同的对象

那是对的。虽然 keypath 与它无关,只是对象存储与现有对象存储具有相同的名称。

新版本不是让脚本重新创建整个对象吗?

不会。对象存储(以及索引和数据)在升级过程中是持久的,除非您在onupgradeneeded. 因此,为了避免该错误,您应该检查event.oldVersion第一次创建数据库时哪个为 0,随后将是以前的版本号。然后,您可以仅在数据库首次初始化时创建对象存储,也可以在升级时重新创建之前将其删除。

更新:MDN IDBDatabase.createObjectStore上的相关文档阐明了如何使用此调用需要唯一性。

IDBDatabase 接口的 createObjectStore() 方法创建并返回一个的对象存储或索引。

该方法采用商店的名称以及允许您定义重要的可选属性的参数对象。您可以使用该属性来唯一标识商店中的各个对象。由于属性是一个标识符,它应该对每个对象都是唯一的,并且每个对象都应该具有该属性。

于 2013-07-21T13:21:30.370 回答