Dexie.js - table.delete(id) not working for per-row deletion - dexie

i'm just starting out with Dexie, and I seem to be coming unstuck.
I have a small database (less than 1000 rows), and i'm trying to delete each row one-by-one once I know that the row has been sent to a remote API.
I can also successfully save to the table (which is defined by an ID and a column storing a serialised object)
here's my code:
if (online) {
//we query the db and send each event
database.open()
let allEvents = database.events.toCollection()
let total = allEvents.count(function (count) {
console.log(count + ' events in total')
//a simple test to ensure we're seeing the right number of records
})
allEvents.each(function(thisEvent){
//push to remote API
console.log('deleting ' + thisEvent.id)
database.events.delete(thisEvent.id) //<= this doesn't seem to be working
})
}
All of this with the exception of the final delete statement.
Any ideas on how I should fix this? the important thing for me is to delete on a per-row basis.
thanks in advance!

I was experiencing the same problem, and the answer from Eugenia Pais wasn't working for me. So after some tests, I saw the trouble was with the type of the variable: I was using a string, but a number is needed, so this is how I solved it:
function removeRow (primaryKey) {
primaryKey = parseInt(primaryKey);
databaseName.tableName.where('primaryKey').equals(primaryKey).delete().then(function(deleteCount) {
console.log ("Deleted " + deleteCount + " rows");
}).catch(function(error) {
console.error ("Error: " + error);
});
So be aware you are using a number as argument.

The correct way to delete each row should be selecting the specific row and delete it:
database.tableName.where(indexId).equals(indexValue).delete();
The data type of the key is not a problem you could verify it in my example here: example
db.example.where('key').equals('one').delete();
Maybe you are trying to delete by a property that not is an index.

Related

In cmdb_rel_ci table I want to retrieve all the unique parent.sys_class_name with count for Type Depends on::Used by

In the cmdb_rel_ci table, I want to retrieve the value and total count of all the unique parent.sys_class_name values for Type(cmdb_rel_type) "Depends on::Used by".
I was trying to use with GlideAggregate, but classname is showing empty.
Can anyone offer some advice?
Use GlideAggregate on the cmdb_ci table, not cmdb_rel_ci. The rel table has no sys_class_name if I recall.
You could also try dot-walking to it using GlideRecord, or using a Join query.
I don't know what "for type Depends on::Used by" means. Pretty sure it doesn't mean anything.
Please take the time to explain your questions clearly and include your code next time if you're expecting anyone to take time out of their day to help you.
As suggested already, use Glideaggregate (more info here)
Try this as an example:
var ga = new GlideAggregate('cmdb_rel_ci');
ga.addQuery('type.name', 'STARTSWITH', 'Depends on::Used by');
ga.addAggregate('COUNT', 'parent');
ga.query();
while (ga.next()) {
var parent = ga.parent.getDisplayValue();
var parentCount = ga.getAggregate('COUNT', 'parent');
gs.info('CI ' + parent + ' has ' + parentCount + ' relationships with type Depends on::Used by');
}

Proper Upsert (Atomic Update Counter Field or Insert Document) with RethinkDB

After looking at some SO questions and issues on RethinkDB github, I failed to come to a clear conclusion if atomic Upsert is possible?
Essentially I would like to perform the same operation as ZINCRBY using Redis.
If member does not exist in the sorted set, it is added with increment
as its score (as if its previous score was 0.0). If key does not
exist, a new sorted set with the specified member as its sole member
is created.
The current implementation appears to differ from almost all databases that I have used. With the data being replaced or inserted not updated. This is a simple use case, like update the last visit, update the number of clicks, update a product quantity. So I must be missing something very obvious, because I cannot see a simple way to do this.
Yes, it is possible. After get on the key, perform an atomic replace. Something like this might work:
function set_or_increment_score(player, points){
return r.table('scores').get(player).replace(
row =>
{ id: player,
score: r.branch(
row.eq(null),
points,
row('score').add(points))
});
}
It has the following behaviour:
> set_or_increment_score("alice", 1).run(conn)
{ inserted: 1 }
> set_or_increment_score("alice", 2).run(conn)
{ replaced: 1 }
It works because get returns null when the document doesn't exist, and a replace on a non-existing document tuns into an insert. See the documentation for replace
So I end up using the following code to go around the no Update issue.
r.db("test").table("t").insert(
{id:"A", type:"player", species:"warrior", score:0, xp:0, armor:0},
{conflict: function(id, oldDoc, newDoc) {
return newDoc.merge(oldDoc).merge(
{armor: oldDoc("armor").add(1)});
}
}
)
Do you think this is more readable/elegant or do you see any issues with the code compared to your sample?

Parse query returning objects based on parameter string length (not the parameter I filter by though)

This has me stumped and I'm pulling my hair out here.
The simple query below finds speeches for the current user:
var _debug = function(cb) {
console.log('_debug')
var DebugParseObject = Parse.Object.extend("Speech");
var debugQuery = new Parse.Query(DebugParseObject);
debugQuery.equalTo("user", _getCurrentUser()); // Incorrect results only occurs when I set the user with this line
debugQuery.find({
success: function(results) {
console.log("Successfully retrieved " + results.length + " scores.");
cb(results);
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
};
The speech object class has the following extra columns
title
body
speech_id
user (pointer)
Here is the weird part: The query will only return the speeches whose body is a string less than about 1000 characters.
As in, I can have Speech A, with a 500 character string in the body field. It will be returned as one of the speeches. BUT if I increase Speech A's body string to about 1500 characters, it will NOT be returned any longer.
I can't understand why.
Some further points
It's only when I filter by the user. If I search for all speeches or query by a different parameter (e.g. title), then the correct amount is returned
This used to work fine yesterday and before
I manually deleted a user earlier (removed the row from the table), while their linked speeches still existed
I changed those speeches' users value from the deleted user id to a new users id
The speeches appear to have the correct user
I tried re-saving the user object on the speech's user property and it didn't do anything
Any help will be great! I feel like I've corrupted the user class when I deleted the user row. But I can't prove it.
The query syntax looks solid and you should be well within the storage limitations of Parse. In case you're curious, there's no explicit limit on string length, but Parse Objects are limited to 128k (except for Parse Files of course).
My guess is that something has gone awry when copying over a different user in place of the one you deleted. Manually changing data and pointers within the browser is always risky and prone to errors.

HandsOnTable manualRowMove not updating the DOM

The manualRowMove works fine visually but the underlying dom is not getting updated. After manualRowMove the HOT.getData() is showing the old sequence of data and not the latest sequence after row swap.
Please advise what I am doing wrong or is it a bug.
Turning on manualRowMove and moving rows around does not affect the original data source. HOT.getData() returns the original data source, which is not what the current state of the table is.
Plugins like manualRowMove, manualColMove, columnSorting are just abstractions that sit on top of the data layer. They maintain state on the handsontable object (ie the sortIndex attribute) which basically act as lookup tables from what the authors call "logical index" to "physical index". Read more about it here: https://github.com/handsontable/handsontable/wiki/Understanding-column-sorting-plugin
It seems like you are trying to allow users to sort the order of the table then save that order. You'll have to roll your own func to walk the table and use a method like getDataAtRow() to get data in table order.
the way I fixed this was to use a PHP script to push the new order to the database on the server (there needs to be some < / > swap logic, it isn't that easy in PHP land, but it is doable), in theory you could recollect the grid and "refresh" it but I didn't feel it was necessary. Obviously the original json from my database is listed by the order
afterRowMove: function (oldIndex, newIndex){
$.post('../ajax/partsOrder.php?id=212&new_parts_order=' + newIndex + '&old_parts_order=' + oldIndex, function(data) {
var msg = '';
if (data.err!=0 || data.url==0) {
msg = 'Error: ' + data.err;
}
else {
msg = 'Success: ' + data.msg;
}
console.log('partsOrder.php says: '+msg);
},"json");
}
PS: I think this is a major omission from handontable, I was not impressed that the getData() doesn't simply represent the gui. In fact it's borderline criminal that they even worked on the gui at all without this

How do I use FTSearchSorted to filter a view in XPages?

I'm working on my Excel exporting using Apache POI. I want to be able to include a query string to limit the exported contents, but I either end up getting 0 documents or getting a couple of documents.
When I get a couple of document, it's unclear if the view object is actually modified. It still responds to getEntryCount with 13 documents, but exports just 2 and doesn't print the columnValues for those two. If I don't use the search, it exports the entire view flawlessly.
The server-side javascript has these few relevant lines.
function createWorkbookStreamWithLabels(workbookName,sheetName,fieldList,dbName,viewName,colLabels,totalLabels,queryString){
...a bunch of other code to get a handle to the view...
postValidationError(control,"Entries: " + view.getEntryCount());
var docCount = view.FTSearchSorted(queryString);
postValidationError(control,"Query: " + queryString);
postValidationError(control,"Query count: " + docCount);
if ( docCount == 0) return;
...code that walks the view and prints the contents...
}
My 0 hit queries include:
FIELD lastname CONTAINS e
and
[state] CONTAINS V
The one that gets two hits is simple:
VA
The view is sorted and now the database is full-text indexed. The column containing State is now sorted and click to sort, ascending.
Just for reference, here's the function that displays my status messages.
function postValidationError(control, msg) {
if ((typeof msg) != "string")
return;
var msgObj = new javax.faces.application.FacesMessage(javax.faces.application.FacesMessage.SEVERITY_ERROR, msg, msg);
facesContext.addMessage(control.getClientId(facesContext), msgObj);
control.setValid(false);
}
What have I done wrong?
Update: the problem with my search queries is solved, but my code also seems to have a terrific tendency to crash HTTP or the server.

Resources