LoginSignup
4
4

More than 5 years have passed since last update.

脱WebStorage! ハイブリッドアプリのデータ永続化(PouchDBでSQLite on Ionic)

Posted at

はじめに

ここで行ってるように、ハイブリッドアプリでlocalstorageを使うのはよろしくない。
なのでSQLiteを使う。
慣れ親しんだJSONで扱えるPouchDBがよさ気なので使ってみた。

基本チュートリアル(これが1番わかりやすい)

補足

  • テーブルはtypeプロパティで表現
  • DB保存場所:/Users/[username]/Library/Developer/CoreSimulator/Devices/[id]/data/Containers/Data/Application/[id]/Documents
  • 全件取得:DB.allDocs({ include_docs: true, attachments: true })
例)DB.allDocsの返却値
{"total_rows":253,
"offset":0,
"rows":[
    {"id":"000C105E-A22C-F4EA-A184-85C22E979B99",
    "key":"000C105E-A22C-F4EA-A184-85C22E979B99",
    "value":{"rev":"1-cc517b7f911eedde487b9a0bf4e520fb"},
    "doc":{"id":68,
            "name":"test",
            "age":25,
            "type":"users",
            "_id":"000C105E-A22C-F4EA-A184-85C22E979B99",
            "_rev":"1-cc517b7f911eedde487b9a0bf4e520fb"
            }
    },..
  • DBに変更があるごとに_revが変わるので変更した後帰ってくるrev_revに入れなおす必要あり。

パフォーマンス(on iOS Simulator)

SQLiteは遅いらしいので計測

// 397ms かかった
function removeAll(){
            var data = [];
            return $q.when(_db.allDocs({
                include_docs: true,
                attachments: true
            })).then(function(res){
                var rows = res.rows;
                for(var i=0;i<rows.length;i++){
                    var doc = rows[i].doc;
                    doc._deleted = true;
                    data.push(doc);
                }
                return $q.when(_db.bulkDocs(data));
            });
        }

確かにlocalstorageよりは遅い
特にwindowsとかはもっと遅いらしい

工夫
  • 毎回DBにアクセスするのは時間もかかるし、angularのdata-bindingも生かせないんで、$rootScope.$VMにDBと同期させて保持させておく。それをラッピングしたModelFactoryでも作って、findの時は全て$VMから取得。変更を加える場合はDBに変更を加えて、返ってきたobjectのrevを$VMにある_revをそれぞれid_idで比較ループして入れなおす。最後に_revが新しくなったobjectを$VMに入れなおすって行く形をとる。起動時に全て$VMに入れてからこれらを行えばうまく少ないDBアクセス回数で運用できそう。
  • _id以外の検索がめんどくさいので_idprefix検索を使ってtable全件取得とか出来るように、{_id:"users-1"}みたいにするといい。
{"ok":true,"id":"users-1","rev":"84-1092ef4c3c55010372d3b86ee96e2aa4"}

公式API等

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4