LoginSignup
2
5

More than 5 years have passed since last update.

【Cordova】cordova-sqlite-storageのlocationオプションと読み込み先のパスとの対応

Posted at

まとめ

cordova-sqlite-storageプラグインで

 db = window.sqlitePlugin.openDatabase({name: 'demo.db', location: 'default', });

のようにdbを開いたときのDBの読み込みパスは

Androidの場合は
"file:///data/data/{パッケージ名}/databases/demo.db"

です。
→cordovaのfilepluginを入れている場合は
cordova.file.applicationStorageDirectory + "databases/demo.db"
のように記述できます。

iOSの場合はiosDatabaseLocationというオプションを設定することが可能です。
読み込みパスとの対応は下記を参照してください。
https://github.com/litehelpers/Cordova-sqlite-storage#opening-a-database

背景とか

以下、上記の「まとめ」の内容を探すのが意外と大変だったという話なので、読み飛ばしても良いです。
サーバからダウンロードしたSQLiteのDBファイルをローカルに保存して読み込むという処理を実装する必要があったため、以下の流れで実装しました。
(cordova-plugin-file, cordova-plugin-file-transfer, cordova-sqlite-storageのプラグインを使用)

1 サーバからダウンロードしたDBファイルをローカルに保存する。
→cordova-plugin-file-transferのFileTransfer#downloadメソッドを使用
2 上記のファイルをcordova-sqlite-storageで読み込む。
→cordova-sqlite-storageのSqlitePlugin#openDatabaseメソッドを使用

このとき、1のdownloadメソッドでは保存パスとしてファイルのURLを指定することができます。

1の処理
function download(fileEntry, serverUri) {
    var fileTransfer = new FileTransfer();
    var fileURL = fileEntry.toURL();

    fileTransfer.download(
        serverUri,
        fileURL,
        function (entry) {
            console.log("Successful download...");
        },
        function (error) {
        },
        null,
        {
            headers: {
            }
        }

    );
}

しかし、2のopenDatabaseでは読み込場所としてlocationオプションを指定することはできるのですが、URLを直接指定することができないようです。
(locationにはdefault, Library, Documentなどのオプションを設定)

2の処理
  db = window.sqlitePlugin.openDatabase(
  {
      name: 'hoge.db',
      location: 'default' // 読み込み場所を設定。URL等を設定することはできない。
  });

というわけで、1の処理の保存先として「location="default"のときの読み込みパス」を設定することにしました。
が、Readmeを探してもlocation=defaultの時にどのパスを読みに行くのか、説明が載っていません。(探し方が悪いだけかもですが。。)
(ちなみにiOSの場合はiosDatabaseLocationというオプションを設定することが可能で、どのパスを読みに行くかの対応もReadmeの中に書いてありました。)

結局Githubのissuesから目的の情報を見つけることができました。

Setting path of DB
https://github.com/litehelpers/Cordova-sqlite-storage/issues/292

cordova fileplugin can copy over your files
Android default location: cordova.file.applicationStorageDirectory+"databases/your_database_name"
IOS location (with location:1 parameter) cordova.file.documentsDirectory+"your_database_name"

ということだそうです。

参考にしたサイト

litehelpers/Cordova-sqlite-storage
https://github.com/litehelpers/Cordova-sqlite-storage

apache/cordova-plugin-file-transfer
https://github.com/apache/cordova-plugin-file-transfer

Setting path of DB
https://github.com/litehelpers/Cordova-sqlite-storage/issues/292

2
5
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
2
5