How to create an imported SQLite database backup using Ionic 2

In my Ionic 2 app, I want to have a backup function. I have SQLite DB with lots of data. This data must be added back to the application. My idea was to export this data to SQL using uk.co.workingedge.cordova.plugin.sqliteporter and save this sql to a file (with Cordova writeFile ). The import function loads the file (File.readAsText) and writes the data to the DB again using importSqlToDb.

Press the button:

// trigger export
this.dbService.dumpDatabase();
// trigger import
this.dbService.importDatabase();

DBService:

public dumpDatabase() {
   let _self = this;
   (<any>window).cordova.plugins.sqlitePorter.exportDbToSql(this.database, {
     successFn: function (sql, count) {
       if (count > 0) {
         _self.fileService.exportSQLToFile(sql);
       } else {
         // show message
       }
     },
     dataOnly: true
  });
}

public importDatabase() {
   this.fileService.importSQLFromFile().then((sql) => {
    (<any>window).cordova.plugins.sqlitePorter.importSqlToDb(this.database, sql, {
    successFn: function (count) {
      alert("Successfully imported " + count + " SQL statements to DB");
    },
    errorFn: function (error) {
      alert("The following error occurred: " + error.message);
    },
    progressFn: function (current, total) {
      console.log("Imported " + current + "/" + total + " statements");
    }
    });
 }, (message) => {
     [...]
 });

}

FileService:

exportSQLToFile(sql) {
   let fs = cordova.file.externalDataDirectory;
   let fileName = "Dump.sql";
   File.writeFile(fs, fileName, sql, {replace: true}).then((success) => {
      [...]
   }, (error) => {
      [...]
   });
}

importSQLFromFile(): Promise<any> { 
   let fs = cordova.file.externalDataDirectory;
   let fileName = "Dump.sql";

   return new Promise((resolve, reject) => {
     // check if backup exists
     File.checkFile(fs, fileName).then(() => {
       return File.readAsText(fs, fileName).then((result) => {
         if(typeof result == "string") {
           resolve(result);
         } else {
           reject(result);
         }
       }).catch((error) => {
         reject(error.message);
       });
     }).catch((error) => {
       reject(error.message);
     });
   });
 }

I would like to give the user control over the location of the file and make it possible to choose from different backups during recovery.

- - , ?

+4

Source: https://habr.com/ru/post/1673514/


All Articles