i am new in indexedddb.
when I want to create a transaction with a inceased version of the database (I increase the version because otherwise the upgradneeded event is never executed), I have the error "A version change transaction is running" which displays.
that's my code (it's from MDN):
var request = window.indexedDB.open("new-db", 8);
request.addEventListener('upgradeneeded', event => {
console.log("bonjour");
var db = event.target.result;
var request = db.transaction([], "readwrite")
.objectStore("customers")
.delete("444-44-4444");
request.onsuccess = function (event) {
// c'est supprimé !
};
});
request.onsuccess = function () {
console.log("open");
}
THANKS FOR YOUR HELP.
Replace this:
var request = db.transaction([], "readwrite")
.objectStore("customers")
.delete("444-44-4444");
With this:
var existingVersionChangeTransaction = event.target.transaction;
existingVersionChangeTransaction.objectStore('customers').delete('444-44-4444');
Related
I try to open and save some data in an indexedDB.
The indexeddb is encapsulate in a webworker but each time i try to open a transaction on IE11, it throws a "notFoundError" (works well on FF).
This is my simplified code :
var dbApi = indexedDB || webkitIndexedDB || mozIndexedDB || msIndexedDB;
var transactionApi = IDBTransaction || webkitIDBTransaction || mozIDBTransaction || msIDBTransaction || {};
var request = dbApi.open('myDB', 1);
var db;
request.onerror = handle_error;
request.onupgradeneeded = handle_upgrade;
request.onsuccess = function(event) {
console.log("Open db ok");
db = event.target.result;
try {
var t = db.transaction(["packet"], (transactionApi.READ_WRITE ? transactionApi.READ_WRITE : 'readwrite')); // Throw error here
t.onsuccess = function() {
var os = t.objectStore("packet");
var cmd = os.put("Some data", -2);
}
}
catch(e) {
console.log(e);
}
};
Thanks
I answer myself : on IE11, we can't create indexeddb from webworker. Db has to be created from main thread and web worker is able to access it after.
Hello I want to build a local database for my phonegap so user can use it offline.
I have this in angular function that creates a database.
function Database() {
return {
create: function (itemDocs) {
var db = null;
var request = indexedDB.open("myDB", 1);
request.onsuccess = function (event) {
db = event.target.result;
console.log("DB loaded successfully");
};
request.onerror = function (event) {
console.log(event)
};
request.onupgradeneeded = function (event) {
db = event.target.result;
console.log("DB initiliazed / created");
//create collections
db.createObjectStore("items", {keyPath: "_id"});
//create documents
var transaction = db.transaction(["items"], "readwrite");
var items = transaction.objectStore("items");
items.add(itemDocs);
};
}
}
}
The itemDocs holds a mongoDB collection (which is an array of objects) and I want to store that collection inside indexedDB database the problem im having is that I'm getting this annoying error.
Uncaught InvalidStateError: Failed to execute 'transaction' on 'IDBDatabase': A version change transaction is running.
Use var transaction = event.target.transaction instead of var transaction = db.transaction(...);
A full answer is rather lengthy. Briefly, you don't want to create a new transaction in onupgradeneeded. There is already an active transaction available for you.
I am newbie to Node.js and I am writing DAO layer for HBase which will wrap thrift and provide clear interface to other layers. I am trying to write unit tests for it using sinon.js and mocha but not sure how to ensure mock one event of Thrift connection class and its event handler.
My DAO code is as follows:
var thrift = require('thrift');
var libDirRelativePath = "../../../lib";
var hbaseThriftDirPath = libDirRelativePath + "/hbase-gen-nodejs";
var hbase = require(hbaseThriftDirPath + '/THBaseService');
var hbaseTypes = require(hbaseThriftDirPath + '/hbase_types');
var thritfPrimaryServerAddress = 'nn2';
var thritfBackupServerAddress = 'backup-nn2';
var thriftServerPort = 9090;
exports.putRows = function(tableName, putObjectArray, callback) {
var primaryClusterConnection = thrift.createConnection(thritfPrimaryServerAddress, thriftServerPort, {
transport: thrift.TBufferedTransport,
protocol : thrift.TBinaryProtocol
});
console.log('DEBUG : connection object created.');
var client = thrift.createClient(hbase, primaryClusterConnection);
console.log('DEBUG : client object created.');
primaryClusterConnection.on('connect', onConnectOfPutRows);
primaryClusterConnection.on('connect', function() {
console.log('Connected to HBase thrift server at ' + thritfPrimaryServerAddress + ":" + thriftServerPort);
client.putMultiple(tableName, putObjectArray, callback);
connection.close();
});
primaryClusterConnection.on('error', function() {
console.log('Error occurred in HBase thirft server connection.');
});
}
For above code I Just want to create stubs primaryClusterConnection and client objects which I have managed but problem is that stub of primaryClusterConnection doesn't have any idea about connect event and its handler so console.log('Connected to HBase thrift server at '... line never gets executed. I want to test that part of the code as well. Can anyone please help me in writing proper stubs/mocks for this problem?
My test code is as follows:
var hbaseDao = require('../../../src/dao/hbase/HBaseDao.js');
var libDirRelativePath = "../../../lib";
var hbaseThriftDirPath = libDirRelativePath + "/hbase-gen-nodejs";
var hbase = require(hbaseThriftDirPath + '/THBaseService');
var chai = require('chai');
var should = chai.should();
var expect = chai.expect;
var sinon = require('sinon');
describe("HBaseDao", function() {
describe(".putRows()", function() {
it("Should execute callback after inserting objects in HBase.", function(done) {
var commonStub = sinon.stub();
var connection = {
close : function() {
console.log('connection closed.');
}
};
commonStub.withArgs('nn2', 9090).returns(connection);
var client = {};
commonStub.withArgs(hbase, connection).returns(client);
var tableName = 'DUMMY_READINGS_TABLE';
var callBackMethod = function() {
console.log('dummy callback function.');
};
commonStub.withArgs(tableName, [], callBackMethod).returns(0);
hbaseDao.putRows(tableName, [], callBackMethod);
expect(hbaseDaoSpy.callCount).to.equal(1);
done();
});
Let's start by simplifying the problem a bit.
it.only("Should execute callback after inserting objects in HBase.", function(done) {
var events = require('events');
var hbaseDao = new events.EventEmitter();
hbaseDao.putRows = function() {
console.log('putting rows');
this.emit('notify');
};
hbaseDao.on('notify', function(){
console.log('notify event fired');
done(); //here's where you call the callback to assert that the event has fired
});
sinon.spy(hbaseDao, 'putRows');
var commonStub = sinon.stub();
var tableName = 'DUMMY_READINGS_TABLE';
var client = {};
var connection = {
close : function() {
console.log('connection closed.');
}
};
var callBackMethod = function() {
console.log('dummy callback function.');
};
commonStub.withArgs('nn2', 9090).returns(connection);
commonStub.withArgs({}, connection).returns(client);
commonStub.withArgs(tableName, [], callBackMethod).returns(0);
hbaseDao.putRows(tableName, [], callBackMethod);
//assertions
assert(hbaseDao.putRows.calledOnce);
});
The above test will just work, because it creates a new "hbaseDao" from a simple event emitter and has the method and the notify event ready to go.
Because we're doing an async test, we need to have the done callback in the spec. Notice that this will only fire "done" when the event has occurred. Hence, the test will not pass unless the event fires. Also notice that we're spying specifically on the the hbaseDao 'putRows' and we're asserting that the its called once, another way to ensure that the test is working. Now consider this example and apply it to your original question.
I think you almost got it, but you need to put your done callback in the callback stub as so:
var callBackMethod = function() {
console.log('dummy callback function.');
done();
};
That way, when your primaryClusterConnection.on('connect') event is fired, the supplied callback will execute the done and complete the test.
That being said, you should leave your primaryClusterConnection intact and let the implementation details of hbaseDao not be considered in your test.
You mentioned that:
primaryClusterConnection doesn't have any idea about connect
But that can't be right, because you're creating a new connection in the test and there's nothing in your implementation that tells me you have changed the event handler for the connection.
So I think in the end, you're missing the point of the test, which is simply should execute callback... and you're stubbing out stuff that you don't even need to.
Try something like this:
//use it.only to make sure there's no other tests running
it.only("Should execute callback after inserting objects in HBase.", function(done) {
//get the class
var hbaseDao = require('../../../src/dao/hbase/HBaseDao.js');
//spy on the method
sinon.spy(hbaseDao, 'putRows');
//create a table name
var tableName = 'DUMMY_READINGS_TABLE';
//create callback method with done.
var callBackMethod = function() {
console.log('dummy callback function.');
done();
};
//run the function under test
hbaseDao.putRows(tableName, [], callBackMethod);
//assert called once
assert(hbaseDao.putRows.calledOnce);
});
I've just started developing an application with javascript for fxos using jQuery Mobile and already got stuck with a framework related problem. For my app I need to use tcp communication provided by mozilla API (mozTCPSocket), it works well when I run it outside from JQM events, but when I do the socket.open() call from a JQM event (eg. pageshow) it looks like the socket object is being killed after each call.
Here is my code:
window.addEventListener('DOMContentLoaded', function() {
'use strict';
var socket;
var host = "someserver";
var port = 6667;
//connect(); // when calling from here, connection works fine
$(document).bind("pageshow", function(e) {
if (typeof e.currentTarget.URL==="string") {
var haystack = $.mobile.path.parseUrl(e.currentTarget.URL);
var needle = /^#server/;
if (haystack.hash.search(needle)!==-1) {
connect(); // ...from here is failing
}
}
});
function connect() {
socket = navigator.mozTCPSocket.open(host,port);
}
socket.ondata = function (event) {
var data = event.data;
var lines = data.split('\r\n');
for (var i=0;i<lines.length;i++) {
if (lines[i].length>0) console.log(lines[i]);
}
}
});
What could be going wrong?
What's certainly wrong here is this:
socket.ondata = function (event) {
var data = event.data;
var lines = data.split('\r\n');
for (var i=0;i<lines.length;i++) {
if (lines[i].length>0) console.log(lines[i]);
}
}
You're setting the ondata method on an undefined object. Which means that any call to connect() later won't have any effect anyway. Also as you're defining a method of an undefined object, the method above probably is crashing.
You should rewrite your code to something like this.
window.addEventListener('DOMContentLoaded', function() {
'use strict';
var socket;
var host = "someserver";
var port = 6667;
//connect(); // when calling from here, connection works fine
$(document).bind("pageshow", function(e) {
if (typeof e.currentTarget.URL==="string") {
var haystack = $.mobile.path.parseUrl(e.currentTarget.URL);
var needle = /^#server/;
if (haystack.hash.search(needle)!==-1) {
connect(); // ...from here is failing
}
}
});
function connect() {
socket = navigator.mozTCPSocket.open(host, port);
socket.ondata = onData;
}
function onData (event) {
var data = event.data;
var lines = data.split('\r\n');
for (var i=0;i<lines.length;i++) {
if (lines[i].length>0) console.log(lines[i]);
}
}
});
var database = e.target.result;
var version = Number(database.version);
console.log("in onsuccess>>>>>>>>>>>>>>>>>>>>>>>>>> : "+dbName);
console.log(e);
database.close();
var secondRequest = indexedDB.open(dbName, (version+1));
console.log(secondRequest); // <-- error on this line
//console.log(secondRequest.result);
secondRequest.onupgradeneeded = function (e) {
console.log("in onupgradeneeded>>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log(e);
var database = e.target.result;
//database.setVersion(12);
var objectStore = database.createObjectStore(storeName, {
keyPath: 'id'
});
};
secondRequest.onsuccess = function (e) {
console.log("000000000000000000000000000000");
e.target.result.close();
};
secondRequest.onerror = function(e){
console.log("Error ------------------- ");
console.log(e);
}
in above console I am getting following error in
console.log(secondRequest);
error:
IDBOpenDBRequest
error : [Exception: DOMException]
I have added listner
IDBOpenDBRequest.onerror = function(e){
}
But It is not going there. Help me if anybody have solution.
Although you have some of the core concepts down, your code is really hard to follow as is. To begin with, this e event assignment is undefined:
var database = e.target.result;
Where is the database open()? Where is dbName coming from?
Provide more of your failing code, preferably via jsfiddle, and we'll help you find a solution.
UPDATE: Here's a working example of what you're trying to do.
Output div:
<div id="idb_version"></div>
Code:
var db_name = 'myname',
database_open_request = window.indexedDB.open(db_name);
database_open_request.addEventListener('success', function (e) {
database = e.target.result;
database.close();
var second_database_open_request = window.indexedDB.open(db_name, database.version + 1);
second_database_open_request.addEventListener('upgradeneeded', function (e) {
database = e.target.result;
database.close();
window.document.getElementById("idb_version").innerHTML = database.version;
});
});
When not specifying a version param, you get a reference to the most recent version on success callback. Then I listen for a versionchange and increase the version by one. Run this over and over and you'll see the version increase one by one.