【问题标题】:Custom query in angular-indexedDBangular-indexedDB 中的自定义查询
【发布时间】:2017-02-19 19:37:55
【问题描述】:

我在我的应用程序中使用bramski/angular-indexedDB。基本的 CRUD 操作工作正常,但自定义查询没有按预期工作。 我正在使用代码

 angular.module('myModuleName', ['indexedDB'])
      .config(function ($indexedDBProvider) {
        $indexedDBProvider
          .connection('myIndexedDB')
          .upgradeDatabase(1, function(event, db, tx){
            var objStore = db.createObjectStore('people', {keyPath: 'ssn'});
            objStore.createIndex('name_idx', 'age', {unique: false});
            objStore.createIndex('name_idx, age_idx', ['name', 'age'] , {unique: false});
    });

基本查询操作如下所示

$indexedDB.openStore('people', function(x){
   var find = x.query();
   find = find.$eq('John');
   find = find.$index("name_idx");    
   x.eachWhere(find).then(function(e){
      $scope.list= e;
   });
});

以下查询结果。

select * from people where name='John'

但是,在上述场景中,我们如何执行自定义查询,例如

select * from people where name='John' and age='25';
delete from people where name='John' and age='25';

【问题讨论】:

  • 查看该提供程序的源代码,该提供程序似乎只针对单个键执行查询。看来您必须修改该提供程序的来源并编写自己的多键查询函数,或者在客户端编写过滤器以排除额外数据。
  • 对不起,我是 indexeddb 的新手。我们不能使用配置的索引组合来获取这些详细信息吗?即 objStore.createIndex('name_idx, age_idx', ['name', 'age'] , {unique: false});

标签: angularjs indexeddb


【解决方案1】:

您使用的库没有复杂的查询,但是您可以为它编写一个纯 js 解决方案,类似于:

首先您需要将索引定义为:

objStore.createIndex('name_age_idx', ['name', 'age'] , {unique: false});

然后你可以对那些匹配搜索结果的值进行搜索查询

searchIndexedDB = function (name, age, callback) {
  var request = indexedDB.open(dbName);
  request.onsuccess = function(e) {
    var db = e.target.result;
    var trans = db.transaction(objectStoreName, 'readonly');
    var store = trans.objectStore(objectStoreName);
    var index = store.index('name_age_idx');
    var keyRange = IDBKeyRange.only([name, age]);
    // open the index for all objects with the same name and age
    var openCursorRequest = index.openCursor(keyRange);

    openCursorRequest.onsuccess = function(e) {
        let result = e.target.result;
        // first check if value is found
        if(result){
            callback(result.value); // your callback will be called per object
            // result.delete() - to delete your object
            result.continue(); // to continue itterating - calls the next cursor request
        }
    };

    trans.oncomplete = function(e) {
        db.close();
    };

    openCursorRequest.onerror = function(e) {
        console.log("Error Getting: ", e);
    };
  };
  request.onerror = myStorage.indexedDB.onerror;
}

如果您需要范围 from 和索引,只需将 keyrange 更改为:

var keyRange = IDBKeyRange.bound([name,fromAge], [value, toAge]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-07
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2019-11-14
    相关资源
    最近更新 更多