-
-
Save jhowbhz/5e29a15b33d0f019f0f051ca5beede27 to your computer and use it in GitHub Desktop.
Script backup sqllite cordova com o plugin sqlporter e arquivo txt na raiz do dispositivo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @var db Base de dados para backup e restauracao | |
*/ | |
var db = window.openDatabase("CAMINHO DO BANCO", "1.0", "NOME DO BANCO", 5 * 2048); | |
/** | |
* Mostra o erro de arquivo | |
* @param {obj} error Recebe o objeto de erro | |
* @returns {void} | |
*/ | |
function falhaArquivo(error) { | |
myApp.hidePreloader(); | |
console.log("Plugin: FileSystem: Message: Arquivo não existe, não é gravável ou não é legível. Error code: " + error.code); | |
myApp.alert('Nenhum backup foi encontrado ou o backup está corrompido!'); | |
} | |
/** | |
* Confirmacao para iniciar o backup | |
* @returns {undefined} | |
*/ | |
function iniciaBackup() { | |
navigator.notification.confirm('Deseja iniciar o backup? Isso limpará seu backup atual. Essa ação não pode ser desfeita.', onConfirmBackup, 'Backup', 'Iniciar,Cancelar'); | |
} | |
/** | |
* Confirmado o inicio do backup | |
* @param {integer} button | |
* @returns {void} | |
*/ | |
function onConfirmBackup(button) { | |
if (button == 1) { | |
backup(); | |
} | |
} | |
/** | |
* Confirmacao para iniciar a restauracao | |
* @returns {void} | |
*/ | |
function restauraBackup() { | |
navigator.notification.confirm('Deseja iniciar a restauração? Isso limpará seus dados atuais. Essa ação não pode ser desfeita!', confirmaRestauracao, 'Restaurar', 'Iniciar,Cancelar'); | |
} | |
/** | |
* | |
* @param {integer} button Qual botao foi acionado | |
* @returns {void} | |
*/ | |
function confirmaRestauracao(button) { | |
if (button == 1) { | |
myApp.showPreloader("Aguarde!"); | |
restaurar(); | |
} | |
} | |
/** | |
* Inicia a restauracao do backup | |
* @returns {void} | |
*/ | |
function restaurar() { | |
var tabelas = ''; | |
var tabela = []; | |
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { | |
fileSystem.root.getFile("bkp.txt", null, function (fileEntry) { | |
fileEntry.file(function (file) { | |
var reader = new FileReader(); | |
reader.onloadend = function (evt) { | |
var data = JSON.parse(evt.target.result); | |
tabelas = data.data.inserts; | |
var sql = ''; | |
var querys = []; | |
for (var i = 0; i < Object.keys(tabelas).length; i++) { | |
var nome_tabela = Object.keys(tabelas)[i].toString(); | |
tabela.push(nome_tabela); | |
nova_tabela = tabelas[nome_tabela]; | |
if (nova_tabela.length) { | |
var insert = 'INSERT INTO ' + nome_tabela + '('; | |
var key = Object.keys(nova_tabela)[0]; | |
var value = nova_tabela[key]; | |
var tb = Object.keys(value); | |
var coluna = []; | |
var values = []; | |
for (var j = 0; j < tb.length; j++) { | |
coluna.push(tb[j]); | |
values.push("?"); | |
} | |
insert += coluna.join(', ') + ') '; | |
for (var k = 0; k < nova_tabela.length; k++) { | |
vlr = []; | |
$.each(nova_tabela[k], function (index, item) { | |
if (typeof item == "number") { | |
vlr.push(item); | |
} else { | |
vlr.push('"' + item + '"'); | |
} | |
}); | |
sql += insert + 'VALUES (' + vlr.join(', ') + ')'; | |
querys.push(sql); | |
sql = ''; | |
} | |
} | |
} | |
limpaTabelas(tabela, querys); | |
}; | |
reader.readAsText(file); | |
}, falhaArquivo); | |
}, falhaArquivo); | |
}, falhaArquivo); | |
} | |
/** | |
* Limpa as tabelas do banco antes de inserir os registros de backup | |
* @param {obj} tabelas Objeto com os nomes das tabelas | |
* @param {obj} querys Objeto com as strings de insercao de sql | |
* @returns {void} | |
*/ | |
function limpaTabelas(tabelas, querys) { | |
db.transaction(function (transaction) { | |
$.each(tabelas, function (index, item) { | |
transaction.executeSql("DELETE FROM " + item, [], null,null); | |
}); | |
}, function (error) { | |
console.log('ERRO LIMPA TABELAS' + error.message); | |
}, function () { | |
populaTabelas(querys); | |
}); | |
} | |
/** | |
* Popular as tabelas com os scripts de insercao | |
* @param {type} querys Objeto com as strings de insercao de sql | |
* @returns {undefined} | |
*/ | |
function populaTabelas(querys) { | |
db.transaction(function (transaction) { | |
$.each(querys, function (index, item) { | |
transaction.executeSql(item, [], null,null); | |
}); | |
}, function (error) { | |
console.log('ERRO POPULA TABELAS' + error.message); | |
}, function () { | |
myApp.hidePreloader(); | |
myApp.alert("Backup restaurado com sucesso!"); | |
}); | |
} | |
/** | |
* Inicia o backup do banco local | |
* @returns {void} | |
*/ | |
function backup() { | |
var successFn = function (json, count) { | |
myApp.hidePreloader(); | |
salvaArquivo(json); | |
}; | |
//https://github.com/dpa99c/cordova-sqlite-porter | |
cordova.plugins.sqlitePorter.exportDbToJson(db, { | |
successFn: successFn | |
}); | |
} | |
/** | |
* Salva o arquivo no dispositivo | |
* @param {json} json Recebe o json para gravar em arquivo no dispositivo | |
* @returns {void} | |
*/ | |
function salvaArquivo(json) { | |
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { | |
// Caminho para o arquivo ser gravado na raiz do dispositivo | |
fileSystem.root.getFile("bkp.txt", {create: true, exclusive: false}, function (fileEntry) { | |
fileEntry.createWriter(function (writer) { | |
writer.write(json); | |
}, falhaArquivo); | |
}, falhaArquivo); | |
}, falhaArquivo); | |
myApp.alert("O backup foi concluído com sucesso!"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment