Commit 9dfff271 authored by Eric Seigne's avatar Eric Seigne
Browse files

migration sqlite -> indexdb

parent 4621a9e3
# 1.6.2
- possibilité d'adaptation de l'interface pour les revendeurs partenaires
- migration de SQLite vers IndexDB pour simplifier l'adoption dans f-droid et limiter les
dépendances externes -> phase transitoire, sqlite est encore présent le temps de faire
la migration des données
# 1.6.1
......
......@@ -160,82 +160,157 @@
//On nettoie l'historique au lancement de l'appli
cleanHistorique();
if (globalDB == null) {
if (globalIndexDB == null) {
$('#loadingStep').text('Etape 3a');
// myDebug("SQL : On essaye d'ouvrir la base de données ...");
if (typeof window.sqlitePlugin != 'undefined') {
globalDB = window.sqlitePlugin.openDatabase({
name: 'doliscan.db',
location: 'default',
androidDatabaseProvider: 'system'
}, function () {
$('#loadingStep').text('Etape 4');
myDebug("SQL : ouverture OK, creation des tables");
globalDB.executeSql('CREATE TABLE IF NOT EXISTS ldfsToSync (id Integer PRIMARY KEY AUTOINCREMENT, url Text, jsonData Text, localFileName Text);');
myDebug("SQL : create ldfsToSync ok");
// globalDB.executeSql('CREATE UNIQUE INDEX IF NOT EXISTS localFileName on ldfsToSync (localFileName);');
globalDB.executeSql('DROP INDEX IF EXISTS localFileName;');
myDebug("SQL : create/drop index on ldfsToSync ok");
globalDB.executeSql('DELETE FROM ldfsToSync WHERE localFileName IS NULL;');
myDebug("SQL : clean up ldfsToSync ok");
globalDB.executeSql("DELETE FROM ldfsToSync WHERE localFileName='undefined';");
myDebug("SQL : clean up 2 ldfsToSync ok");
globalDB.executeSql('CREATE TABLE IF NOT EXISTS config (key Text, value Text);');
myDebug("SQL : create config ok");
//Si on a des entrees en double
globalDB.executeSql('DELETE FROM config WHERE rowid NOT IN (SELECT max(rowid) FROM config GROUP BY key)');
globalDB.executeSql('CREATE UNIQUE INDEX IF NOT EXISTS keyIndex on config (key);');
myDebug("SQL : fin de création des tables");
$('#loadingStep').text('Etape 5');
globalDB.readTransaction(function (t) {
$('#loadingStep').text('Etape 6');
myDebug("SQL : select ...");
t.executeSql('SELECT * FROM config WHERE value IS NOT NULL;', [],
function (tx, rs) {
let nbRes = rs.rows.length;
// myDebug("SQL : select * from config -> " + nbRes);
let i = 0;
for (i = 0; i < nbRes; i++) {
let k = rs.rows.item(i).key;
let v = rs.rows.item(i).value;
//Mise a jour uniquement si non vide
if (v !== null && v != "") {
localStorage.setItem(k, v);
myDebug(' (c) SQL select localStorage ' + k + ' -> ' + v);
}
else {
myDebug(' (c) SQL select localStorage ' + k + ' -> null on ne fait donc pas le localStorage :-)');
}
}
//le SQL s'est déroulé ...
myDebug("SQL : read OK");
$('#loadingStep').text('Etape 7a');
switchLoginOrMenu();
}, function (tx, error) {
myDebug(" SQL Error " + error.message);
$('#loadingStep').text('Etape 7b');
switchLoginOrMenu();
});
});
$('#loadingStep').text('Etape 8');
myDebug("SQL : end config ok");
var openRequest = window.indexedDB.open(databaseName, databaseVersion);
openRequest.onerror = function (event) {
myDebug(openRequest.errorCode);
};
openRequest.onsuccess = function (event) {
// Database is open and initialized - we're good to proceed.
globalIndexDB = openRequest.result;
myDebug("global db type indexDB open ok");
$('#loadingStep').text('Etape 4a');
var objectStore = globalIndexDB.transaction("config").objectStore("config");
objectStore.openCursor().onsuccess = function (event) {
$('#loadingStep').text('Etape 5a');
var cursor = event.target.result;
if (cursor) {
$('#loadingStep').text('Etape 6a');
myDebug("Lecture IndexDB " + cursor.key + " is " + cursor.value.value);
let k = cursor.key;
let v = cursor.value.value;
//Mise a jour uniquement si non vide
if (v !== null && v != "") {
localStorage.setItem(k, v);
myDebug(' (c) IndexDB select localStorage ' + k + ' -> ' + v);
}
else {
myDebug(' (c) IndexDB select localStorage ' + k + ' -> null on ne fait donc pas le localStorage :-)');
}
cursor.continue();
myDebug("IndexDB : read OK");
$('#loadingStep').text('Etape 7a');
switchLoginOrMenu();
}
else {
$('#loadingStep').text('Etape 6b');
myDebug("No more entries!");
switchLoginOrMenu();
}
};
objectStore.openCursor().onerror = function (event) {
myDebug(" IndexDB Error " + error.message);
$('#loadingStep').text('Etape 7b');
switchLoginOrMenu();
});
}
else {
}
};
openRequest.onupgradeneeded = function (event) {
$('#loadingStep').text('Etape 4b');
ons.notification.alert("Un élément nécessaire au bon fonctionnement de l'application n'est pas disponible ! (Erreur SQLite)", { title: "Erreur" }).then(function () {
closePage(true);
});
}
myDebug("global db upgrade or create");
// This is either a newly created database, or a new version number
// has been submitted to the open() call.
var db = event.target.result;
db.onerror = function () {
myDebug(db.errorCode);
};
// Create an object store and indexes. A key is a data value used to organize
// and retrieve values in the object store. The keyPath option identifies where
// the key is stored. If a key path is specified, the store can only contain
// JavaScript objects, and each object stored must have a property with the
// same name as the key path (unless the autoIncrement option is true).
var storeLDF = db.createObjectStore('ldfsToSync', { keyPath: 'id' });
// Define the indexes we want to use. Objects we add to the store don't need
// to contain these properties, but they will only appear in the specified
// index of they do.
//
// syntax: store.createIndex(indexName, keyPath[, parameters]);
//
// All these values could have duplicates, so set unique to false
storeLDF.createIndex('url', 'url', { unique: false });
storeLDF.createIndex('jsonData', 'jsonData', { unique: false });
storeLDF.createIndex('localFileName', 'localFileName', { unique: false });
myDebug("SQL : index on ldfsToSync ok");
// Once the store is created, populate it
storeLDF.transaction.oncomplete = function (event) {
// The transaction method takes an array of the names of object stores
// and indexes that will be in the scope of the transaction (or a single
// string to access a single object store). The transaction will be
// read-only unless the optional 'readwrite' parameter is specified.
// It returns a transaction object, which provides an objectStore method
// to access one of the object stores that are in the scope of this
//transaction.
//TODO ?
// var customerStore = db.transaction('customers', 'readwrite').objectStore('customers');
// customers.forEach(function (customer) {
// customerStore.add(customer);
// });
};
var storeConfig = db.createObjectStore('config', { keyPath: 'key' });
// storeConfig.createIndex('value', 'value', { unique: false });
myDebug("SQL : create config ok");
storeConfig.transaction.oncomplete = function (event) {
//Migration des données depuis SQLite ?
if (typeof window.sqlitePlugin != 'undefined') {
globalDB = window.sqlitePlugin.openDatabase({
name: 'doliscan.db',
location: 'default',
androidDatabaseProvider: 'system'
}, function () {
myDebug("SQL : migration 1");
$('#loadingStep').text('Data Migration 1');
globalDB.readTransaction(function (t) {
$('#loadingStep').text('Data Migration 2');
myDebug("SQL : select ...");
t.executeSql('SELECT * FROM config WHERE value IS NOT NULL;', [],
function (tx, rs) {
let nbRes = rs.rows.length;
// myDebug("SQL : select * from config -> " + nbRes);
let i = 0;
for (i = 0; i < nbRes; i++) {
let k = rs.rows.item(i).key;
let v = rs.rows.item(i).value;
//Mise a jour uniquement si non vide
if (v !== null && v != "") {
// localStorage.setItem(k, v);
localStoreData(k, v);
myDebug(' (c) SQL select localStorage ' + k + ' -> ' + v);
}
else {
myDebug(' (c) SQL select localStorage ' + k + ' -> null on ne fait donc pas le localStorage :-)');
}
}
//le SQL s'est déroulé ...
myDebug("SQL : read OK");
$('#loadingStep').text('Data Migration 3a');
switchLoginOrMenu();
}, function (tx, error) {
myDebug(" SQL Error " + error.message);
$('#loadingStep').text('Data Migration 3b');
switchLoginOrMenu();
});
});
$('#loadingStep').text('Data Migration 4');
myDebug("SQL : end data migration");
});
}
$('#loadingStep').text('Etape 5a');
switchLoginOrMenu();
}
$('#loadingStep').text('Etape 5b');
};
}
else {
$('#loadingStep').text('Etape 3b');
......
......@@ -2,7 +2,7 @@
* (c) Éric Seigne <eric.seigne@cap-rel.fr> - 2019-2020 - GNU AGPLv3
* full source code in src/ subfolder, this file is minifyed
*/
var globalDevMode=true;var globalMyCamera;var globalpictureSource;var globaldestinationType;var globalNetworkResponse=Date.now();var globalCurrentPage="";var globalCurrentTitle="";var globalDB=null;var globalTenMinuts=60*10*1000;var globalCompatibleWithAPIVersion=4;var globalDoliScanDomain="";var globalLastInsertId="";var globalSyncInProgress=false;var globalPictureFileName="";var globalAppVersion="1.6.0";var dataLDF="";var dataIK="";var globalMyNavigator=undefined;var globalResumable=undefined;var globalProgressBar=undefined;var globalTypeFrais="";var globalSrvKeys=['email','api_token','firstname','name','adresse','cp','ville','pays','send_copy_to','compta_email','compta_ik','compta_peage','compta_hotel','compta_train','compta_carburant','compta_taxi','compta_restauration','compta_divers','compta_compteperso','compta_tvadeductible','official_app_version','official_app_message','mode_simple'];function errorHandlerCustomFile(title,message){myDebug('errorHandlerCustomFile : '+title+' -- message follow:');myDebug(message);}
var globalDevMode=true;var globalMyCamera;var globalpictureSource;var globaldestinationType;var globalNetworkResponse=Date.now();var globalCurrentPage="";var globalCurrentTitle="";var globalDB=null;var globalIndexDB=null;var databaseEngine='IndexDB';var databaseName='doliscanDB';var databaseVersion=1;var globalTenMinuts=60*10*1000;var globalCompatibleWithAPIVersion=4;var globalDoliScanDomain="";var globalLastInsertId="";var globalSyncInProgress=false;var globalPictureFileName="";var globalAppVersion="1.6.0";var dataLDF="";var dataIK="";var globalMyNavigator=undefined;var globalResumable=undefined;var globalProgressBar=undefined;var globalTypeFrais="";var globalSrvKeys=['email','api_token','firstname','name','adresse','cp','ville','pays','send_copy_to','compta_email','compta_ik','compta_peage','compta_hotel','compta_train','compta_carburant','compta_taxi','compta_restauration','compta_divers','compta_compteperso','compta_tvadeductible','official_app_version','official_app_message','mode_simple'];function errorHandlerCustomFile(title,message){myDebug('errorHandlerCustomFile : '+title+' -- message follow:');myDebug(message);}
function loadCustomCSS(){let cssFileName=cordova.file.cacheDirectory+'custom.css';myDebug("loadCustomCSS : "+cssFileName);window.resolveLocalFileSystemURL(cssFileName,function(fileEntry){myDebug("loadCustomCSS (2): "+JSON.stringify(fileEntry));fileEntry.file(function(file){var reader=new FileReader();var fileSize=file.size;myDebug("loadCustomCSS (3) Size = "+file.size);reader.onloadend=function(e){var fileContent=reader.result;myDebug("loadCustomCSS : append to header "+fileContent);$('head').append(fileContent);};reader.readAsText(file);},errorHandlerCustomFile.bind(null,"Error on FileEntry "+cssFileName));},errorHandlerCustomFile.bind(null,"Error on resolveLocalFileSystemURL "+cssFileName));}
function downloadCustomCSS(){$.ajaxSetup({timeout:10000,headers:{'X-CSRF-TOKEN':localGetData("api_token")}});if(ajaxDownloadCSS)
ajaxDownloadCSS.abort();var ajaxDownloadCSS=$.ajax({type:"POST",timeout:5000,url:localGetData("api_server")+"/api/CustomizingApp/css",data:{email:localGetData("email"),},beforeSend:function(xhr){xhr.setRequestHeader('Authorization','Bearer '+localGetData("api_token"));},xhrFields:{responseType:'arraybuffer',withCredentials:true},success:function(data){globalNetworkResponse=Date.now();hideWait();myDebug('downloadCustomCSS : done');let blob=new Blob([data],{type:"text/css"});let cssFileName='/custom.css';myDebug(blob.size);myDebug(data);window.resolveLocalFileSystemURL(cordova.file.cacheDirectory,function(directoryEntry){myDebug('downloadCustomCSS Write to '+cordova.file.cacheDirectory);directoryEntry.getFile(cssFileName,{create:true},function(fileEntry){myDebug('downloadCustomCSS Write to '+cssFileName);fileEntry.createWriter(function(fileWriter){fileWriter.onwriteend=function(e){myDebug('downloadCustomCSS Write of file completed.');myDebug(fileEntry.fullPath);myDebug(fileEntry);loadCustomCSS();};fileWriter.onerror=function(e){};fileWriter.write(data);});});});},error:function(result){hideWait();myDebug('downloadCustomCSS error.');}});}
......@@ -197,7 +197,7 @@ globalCurrentPage=destination;let onsContent=document.getElementById('mainconten
return true;}
function cleanHistorique(){myDebug('call cleanHistorique');listeContent=new Array('');localStoreData("history",JSON.stringify(listeContent));}
function closeSession(){localStoreData("api_token",null);localStoreData("name_server",null);askQuitOrGoto("login.html");}
ons.ready(function(){ons.enableDeviceBackButtonHandler();ons.setDefaultDeviceBackButtonListener(function(event){fn.back();});var path=window.location.pathname;var page=path.split("/").pop();if(page!="index.html"){if(globalDB==null){if(typeof window.sqlitePlugin!='undefined'){globalDB=window.sqlitePlugin.openDatabase({name:'doliscan.db',location:'default',androidDatabaseProvider:'system'},function(){});}}}});document.addEventListener("deviceready",NDFonDeviceReady,false);function NDFonDeviceReady(){myDebug("NDFonDeviceReady de ndf.js");if(navigator.camera!==undefined){globalMyCamera=navigator.camera;globalPictureSource=navigator.camera.PictureSourceType;globalDestinationType=navigator.camera.DestinationType;globalMyCamera.cleanup();}
ons.ready(function(){ons.enableDeviceBackButtonHandler();ons.setDefaultDeviceBackButtonListener(function(event){fn.back();});var path=window.location.pathname;var page=path.split("/").pop();if(page!="index.html"){if(globalIndexDB==null){var openRequest=window.indexedDB.open(databaseName,databaseVersion);openRequest.onerror=function(event){myDebug(openRequest.errorCode);};openRequest.onsuccess=function(event){globalIndexDB=openRequest.result;myDebug("global db type indexDB open ok");}}}});document.addEventListener("deviceready",NDFonDeviceReady,false);function NDFonDeviceReady(){myDebug("NDFonDeviceReady de ndf.js");if(navigator.camera!==undefined){globalMyCamera=navigator.camera;globalPictureSource=navigator.camera.PictureSourceType;globalDestinationType=navigator.camera.DestinationType;globalMyCamera.cleanup();}
else{myDebug("Erreur: camera introuvable !");}
myDebug("NDFonDeviceReady de ndf.js : camera ready");}
function onPhotoDataSuccess(imageData){myDebug("onPhotoDataSuccess :"+imageURI);var smallImage=document.getElementById('smallImage');smallImage.style.display='block';smallImage.src="data:image/jpeg;base64,"+imageData;var photoFacturette=document.getElementById('photoFacturette');photoFacturette.value="2";}
......@@ -324,10 +324,11 @@ function fixedEncodeURIComponent(str){return encodeURIComponent(str).replace(/[!
function addLocalStorageEntry(liste,entry){if((typeof liste!='undefined')&&(liste!==null)&&(liste!="")){if((typeof entry!='undefined')&&(entry!==null)&&(entry!="")){var listeContent=JSON.parse(localGetData(liste));if(Array.isArray(listeContent)){listeContent.push(entry);listeContent=myUniqueSort(listeContent);}
else{listeContent=new Array(entry);}
localStoreData(liste,JSON.stringify(listeContent));}}}
function localStoreData(key,value){localStorage.setItem(key,value);if(key=='history'){return;}
if(globalDB==null){if(typeof window.sqlitePlugin!='undefined'){globalDB=window.sqlitePlugin.openDatabase({name:'doliscan.db',location:'default',androidDatabaseProvider:'system'},function(){myDebug("SQL : re-ouverture OK");});}}
if(globalDB!==null){globalDB.transaction(function(tx){tx.executeSql('DELETE FROM config WHERE key=?;',[key],function(res){},function(error){myDebug(' SQL delete error: '+error.message);});});if(value!==null){globalDB.transaction(function(tx){tx.executeSql('INSERT INTO config VALUES(?,?);',[key,value],function(res){},function(error){myDebug(' SQL insert error: '+error.message);});});}
else{myDebug(" SQL ERR: Accès à globalDB impossible pour stocker "+key+" val "+value);}}}
function localStoreData(lakey,lavalue){localStorage.setItem(lakey,lavalue);if(lakey=='history'){return;}
if(globalIndexDB==null){var openRequest=window.indexedDB.open(databaseName,databaseVersion);openRequest.onerror=function(event){myDebug(openRequest.errorCode);myDebug("global db type indexDB re-open error");};openRequest.onsuccess=function(event){globalIndexDB=openRequest.result;myDebug("global db type indexDB re-open ok");}}
if(globalIndexDB!==null){myDebug("global db type indexDB put data asked ...");var transaction=globalIndexDB.transaction(["config"],"readwrite");var objectStore=transaction.objectStore("config");var request=objectStore.put({key:lakey,data:lavalue});request.oncomplete=function(){myDebug("objectStore.put ok");}
request.onerror=function(){myDebug("objectStore.put err pour "+lakey+" : "+lavalue);}}
else{myDebug(" ERR: Accès à globalIndexDB impossible pour stocker "+lakey+" val "+lavalue);}}
function localGetData(key){if((typeof localStorage.getItem(key)!='undefined')&&(localStorage.getItem(key)!==null)&&(localStorage.getItem(key)!=null)&&(localStorage.getItem(key)!='null')&&(localStorage.getItem(key)!="")&&(localStorage.getItem(key)!=undefined)){myDebug('localGetData : '+key+' -> '+localStorage.getItem(key));return localStorage.getItem(key);}
myDebug("localGetData: on retourne null pour "+key)
return null;}
......
......@@ -10,6 +10,10 @@ var globalNetworkResponse = Date.now(); // Date a laquelle on a reçu une répon
var globalCurrentPage = ""; // Page courante pour gérer le retour précédent
var globalCurrentTitle = ""; // Titre de la page courante
var globalDB = null; // Le connecteur vers la base de données SQLite
var globalIndexDB = null; // Le connecteur vers la base de données IndexDB
var databaseEngine = 'IndexDB';
var databaseName = 'doliscanDB';
var databaseVersion = 1;
var globalTenMinuts = 60 * 10 * 1000; // 10 minutes pour l'implementation du keepalive (avant de basculer en full API je pense)
var globalCompatibleWithAPIVersion = 4; // On incrémentera la version de l'API compatible quand on modifie des choses importantes sur le serveur
var globalDoliScanDomain = ""; // Pour basculer sur un serveur auto-hebergé
......
......@@ -171,12 +171,4 @@ function closeSession() {
localStoreData("api_token", null);
localStoreData("name_server", null);
askQuitOrGoto("login.html");
// TODO migration apple / IOS à terminer
// globalDB.close(function () {
// myDebug('database is closed ok');
// }, function (error) {
// myDebug('ERROR closing database');
// });
// window.location.replace('index.html');
}
......@@ -14,17 +14,15 @@ ons.ready(function () {
var path = window.location.pathname;
var page = path.split("/").pop();
if (page != "index.html") {
if (globalDB == null) {
if (typeof window.sqlitePlugin != 'undefined') {
// myDebug("SQL : On essaye d'ouvrir la base de données ...");
globalDB = window.sqlitePlugin.openDatabase({
name: 'doliscan.db',
location: 'default',
androidDatabaseProvider: 'system'
}, function () {
// myDebug("SQL : ouverture OK (ndf-head hors index.html normalement)");
});
if (globalIndexDB == null) {
var openRequest = window.indexedDB.open(databaseName, databaseVersion);
openRequest.onerror = function (event) {
myDebug(openRequest.errorCode);
};
openRequest.onsuccess = function (event) {
// Database is open and initialized - we're good to proceed.
globalIndexDB = openRequest.result;
myDebug("global db type indexDB open ok");
}
}
}
......
......@@ -976,6 +976,7 @@ document.addEventListener('init', function (event) {
else {
myDebug("SQL globalBD is NOT null ...");
//TODO globalIndexDB
globalDB.executeSql('SELECT * FROM config;', [],
function (rs) {
let nbRes = rs.rows.length;
......
/*
* (c) Éric Seigne <eric.seigne@cap-rel.fr> - 2019 - GNU AGPLv3
* (c) Éric Seigne <eric.seigne@cap-rel.fr> - 2019-2021 - GNU AGPLv3
*/
//Ajoute une entrée dans une liste locale
/**
* Ajout d'une entrée dans le stockage local
*
* @param {[type]} liste [liste description]
* @param {[type]} entry [entry description]
*
* @return {[type]} [return description]
*/
function addLocalStorageEntry(liste, entry) {
if ((typeof liste != 'undefined') && (liste !== null) && (liste != "")) {
if ((typeof entry != 'undefined') && (entry !== null) && (entry != "")) {
......@@ -21,89 +28,104 @@ function addLocalStorageEntry(liste, entry) {
}
//Ajoute une valeur dans la base de données - remplace celle qui existerait deja
function localStoreData(key, value) {
localStorage.setItem(key, value);
/**
* Ajout ou remplace une donnée dans la base de données
* (stockage persistant)
*
* @param {[type]} lakey [lakey description]
* @param {[type]} lavalue [lavalue description]
*
* @return {[type]} [return description]
*/
function localStoreData(lakey, lavalue) {
localStorage.setItem(lakey, lavalue);
// myDebug('localStoreData : ' + key + ' et ' + value);
//Pas la peine de stocker ça en SQL
if (key == 'history') {
if (lakey == 'history') {
return;
}
if (globalDB == null) {
if (globalIndexDB == null) {
// myDebug("SQL : On essaye d'ouvrir la base de données ...");
if (typeof window.sqlitePlugin != 'undefined') {
globalDB = window.sqlitePlugin.openDatabase({
name: 'doliscan.db',
location: 'default',
androidDatabaseProvider: 'system'
}, function () {
myDebug("SQL : re-ouverture OK");
});
// if (databaseEngine == 'IndexDB') {
var openRequest = window.indexedDB.open(databaseName, databaseVersion);
openRequest.onerror = function (event) {
myDebug(openRequest.errorCode);
myDebug("global db type indexDB re-open error");
};
openRequest.onsuccess = function (event) {
// Database is open and initialized - we're good to proceed.
globalIndexDB = openRequest.result;
myDebug("global db type indexDB re-open ok");
}
// }
// else {
// if (typeof window.sqlitePlugin != 'undefined') {
// globalDB = window.sqlitePlugin.openDatabase({
// name: 'doliscan.db',
// location: 'default',
// androidDatabaseProvider: 'system'
// }, function () {
// myDebug("SQL : re-ouverture OK");
// });
// }
// }
}
if (globalDB !== null) {
// myDebug(' SQL on stocke : ' + key + ' et ' + value);
globalDB.transaction(function (tx) {
tx.executeSql('DELETE FROM config WHERE key=?;', [key],
// globalDB.executeSql('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?);', [key, value],
function (res) {
// myDebug(" SQL delete ok, " + res.rowsAffected + " rows affected");
},
function (error) {
myDebug(' SQL delete error: ' + error.message);
});
});
if (value !== null) {
globalDB.transaction(function (tx) {
tx.executeSql('INSERT INTO config VALUES(?,?);', [key, value],
// globalDB.executeSql('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?);', [key, value],
function (res) {
// myDebug(" SQL insert ok for " + key + ":" + value + ", " + res.insertId + "id, rows affected: " + res.rowsAffected);
},
function (error) {
myDebug(' SQL insert error: ' + error.message);
});
});
// globalDB.transaction(function (tx) {
// myDebug(' localStoreData dans le SQL');
// tx.executeSql('INSERT OR REPLACE INTO config VALUES (?,?);', [key, value]);
// }, function (error) {
// myDebug(' localStoreData SQL INSERT / UPDATE error for: ' + key + " value " + value + " -> message: " + error.message);
// }, function () {
// myDebug(' localStoreData SQL INSERT / UPDATE OK for ' + key + " value " + value);
// });
// myDebug(' SQL apres la requete SQL pour ' + key);
if (globalIndexDB !== null) {
// if (databaseEngine == 'IndexDB') {
myDebug("global db type indexDB put data asked ...");
var transaction = globalIndexDB.transaction(["config"], "readwrite");
var objectStore = transaction.objectStore("config");
var request = objectStore.put({ key: lakey, data: lavalue });
request.oncomplete = function () {
myDebug("objectStore.put ok");
}
else {
myDebug(" SQL ERR: Accès à globalDB impossible pour stocker " + key + " val " + value);
request.onerror = function () {
myDebug("objectStore.put err pour " + lakey + " : " + lavalue);
}
// }
// else {
// // myDebug(' SQL on stocke : ' + key + ' et ' + value);
// globalDB.transaction(function (tx) {
// tx.executeSql('DELETE FROM config WHERE key=?;', [lakey],
// // globalDB.executeSql('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?);', [key, value],
// function (res) {
// // myDebug(" SQL delete ok, " + res.rowsAffected + " rows affected");
// },
// function (error) {
// myDebug(' SQL delete error: ' + error.message);
// });
// });
// if (value !== null) {
// globalDB.transaction(function (tx) {
// tx.executeSql('INSERT INTO config VALUES(?,?);', [lakey, lavalue],
// // globalDB.executeSql('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?);', [key, value],
// function (res) {
// // myDebug(" SQL insert ok for " + key + ":" + value + ", " + res.insertId + "id, rows affected: " + res.rowsAffected);
// },
// function (error) {
// myDebug(' SQL insert error: ' + error.message);
// });
// });
// }
// }
}
else {
myDebug(" ERR: Accès à globalIndexDB impossible pour stocker " + lakey + " val " + lavalue);
}
}
//Recherche la cle et retourne la valeur correspondante
//retourne null si vide ou n'existe pas
/* a tester sous la forme d'un promise
function localGetData(key) {
return new Promise((resolve, reject) => {
if (
(typeof localStorage.getItem(key) != 'undefined')
&& (localStorage.getItem(key) !== null)
&& (localStorage.getItem(key) != null)
&& (localStorage.getItem(key) != 'null')
&& (localStorage.getItem(key) != "")
&& (localStorage.getItem(key) != undefined)
) {
myDebug('localGetData : ' + key + ' -> ' + localStorage.getItem(key));
resolve(localStorage.getItem(key));
}
myDebug("localGetData: on retourne null pour " + key)
reject(null);
});
*/
/**
* Récupère une donnée locale
*
* @param {[type]} key [key description]
*
* @return {[type]} [return description]
*/
function localGetData(key) {
if (
(typeof localStorage.getItem(key) != 'undefined')
......@@ -118,19 +140,4 @@ function localGetData(key) {
}
myDebug("localGetData: on retourne null pour " + key)
return null;
// globalDB.transaction(function (tx) {
// req = 'SELECT value FROM config WHERE key = ?';
// tx.executeSql(req, [key], function (tx, rs) {
// myDebug('SQL Request : ' + req + ' with key=' + key + ' -> ' + rs.rows.item(0).value);
// if (rs.rows.item(0) == undefined) {
// myDebug(' -> return false');
// return false;
// }
// myDebug(' -> return value ' + rs.rows.item(0).value);
// return rs.rows.item(0);
// }, function (tx, error) {
// myDebug('SQL SELECT error: ' + error.message);
// });
// });
// return false;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment