I am working with the database in ionic, I call one API that returns me a number of records, I have to insert those records into the database and when to insert operations are completed then I want to call select records from the database. problem is asynchronous behavior, the select records from the database called before the insert operations are completed. can anyone help me to resolve this? my code is below...
DbProvider:
export class DbProvider {
public addData(dId: string, sId: string, subId: string, subName: string,
dDate: string, cId: string, cName: string, stdId: string, stdName: string,
) {
return new Promise((resolve, reject) => {
this.db.executeSql("INSERT INTO data (dId , sId , subId , subName ," +
" dDate , cId , cName , stdId , stdName ) VALUES (?, ?,?, ?,?, ?,?, ?,?)",
[dId, sId, subId, subName, dDate, cId, cName, stdId, stdName]).then((data) => {
resolve(data);
}, (error) => {
reject(error.tostring());
});
});
}
}
database insert and call
for (let temp of ApiData) {
this.DbHandler.IsAvailable(temp.dId).then(data => {
if (data) {
console.log("did Available editing " + data);
this.DbHandler.editData(temp.dId, temp.sId, temp.subId, temp.subName,
temp.dDate, temp.cId, temp.cName);
} else {
console.log("did not Available inserting " + data);
this.DbHandler.addData(temp.dId, temp.sId, temp.subId, temp.subName,
temp.dDate, temp.cId, temp.cName);
}
});
}
this.getDataFromDb();
I have multiple INSERTs I'd like to be done before starting SELECT requests. My problem is that the INSERT is not yet finished when the SELECT fires.
Call read from DB in then method:
let promises = [];
for (let temp of ApiData) {
let promise = new Promise((resolve, reject) => {
this.DbHandler.IsAvailable(temp.dId).then(data => {
if (data) {
console.log("did Available editing " + data);
this.DbHandler.editData(temp.dId, temp.sId, temp.subId, temp.subName,
temp.dDate, temp.cId, temp.cName).then(() => resolve());
} else {
console.log("did not Available inserting " + data);
this.DbHandler.addData(temp.dId, temp.sId, temp.subId, temp.subName,
temp.dDate, temp.cId, temp.cName).then(() => resolve());
}
});
};
promises.push(promise);
}
Promise.all(promises).then(() => this.getDataFromDb());
Related
I have a database that has a queues table that holds queues names and ids, and the two queue tables (queue 1, and queue 2).
now i have a function that is supposed to add orders to the right queue, but it's only adding to the second queue and i'm already using a for loop to change the queue that should be used.
here's the code
for (int i = 0; i < tmpQueuesIds.length; i++){
await http.post(GlobalState.ADDTOQUEUE, body: {
'queueId': tmpQueuesIds[i].toString(),
'timeinmin': tmpTimes[tmpQueuesIds[i]].toString(),
'resId': _globalState.get('resId').toString(),
'userId': userId.toString(),
});
print("QueueId: " + tmpQueuesIds[i].toString());
print("OrderTime: " + tmpTimes[tmpQueuesIds[i]].toString());
Future.delayed(Duration(milliseconds: 500));
}
and here's the output:
I/flutter ( 3238): QueueId: 1
I/flutter ( 3238): OrderTime: 6
I/flutter ( 3238): QueueId: 2
I/flutter ( 3238): OrderTime: 10
as you can see i have two queues and the values are being changed, but it's inserting the value 10 twice to the queue 2, it should be inserting value 6 to queue 1 and value 10 to queue 2.
and here's the api code
try {
router.post('/', (req, res, next) => {
queueId = req.body.queueId;
resId = req.body.resId;
timeinmin = req.body.timeinmin;
userId = req.body.userId;
var orderId;
sqlQuery = `SELECT id FROM orders where userid = ${userId} and isdone = false`;
con.query(sqlQuery, (err, rows) => {
try {
lastIndex = rows['rows'].length - 1;
orderId = rows['rows'][lastIndex]['id'];
} catch{
console.log('something wrong with setting orderId or lastIndex value in addToQueue.js');
}
if (!err) {
sqlQuery2 = `SELECT name FROM queues where id = ${queueId}`;
try {
con.query(sqlQuery2, function (err, rows) {
try {
queueName = rows['rows'][0]['name'];
} catch{
console.log('something wrong with setting queueName value in addToQueue.js');
}
if (!err) {
sqlQuery2 = `INSERT INTO ${queueName} (timeinmin, resid, orderid) VALUES(${timeinmin}, ${resId}, ${orderId})`;
try {
con.query(sqlQuery2, function (err, rows) {
if (!err) {
res.sendStatus(201);
console.log('added to queue');
} else {
console.error("Failed to add to queue");
console.log(err);
res.sendStatus(202);
}
});
} catch{
console.log('Something went down.');
}
} else {
console.error("Failure");
console.log(err);
res.sendStatus(202);
}
});
} catch{
console.log('Something went down.');
}
} else {
console.log(err);
res.sendStatus(202);
}
})
});
} catch{
console.log('Error');
}
help me please, thanks.
I can't find any problems with your code.
My advice is to try restarting your IDEs and if the problem still persists try restarting your whole computer.
I am asking this , because sometimes(rarely) my query doing multiple additions.
I am opening db every page at the top.
var db = SQLite.openDatabase({name:'appdb.db',createFromLocation: '~appdb.db'})
my query is
db.transaction((tx) => {
tx.executeSql('INSERT INTO messages (chatID,messageID,senderID,message,uri,type,date)'+
'values(?,?,?,?,?,?,?)',[this.state.chatID,data.messageID,data.senderID,data.message,data.uri,data.type,data.date], (tx, results) => {
});
});
I think about convert to this for every query
import db from '../Classes/db';
db.open();
db.transaction((tx) => {
tx.executeSql('INSERT INTO messages (chatID,messageID,senderID,message,uri,type,date)'+
'values(?,?,?,?,?,?,?)',[this.state.chatID,data.messageID,data.senderID,data.message,data.uri,data.type,data.date], (tx, results) => {
});
});
db.close();
I need to make an insert query in mssql but I can't come around how to parse the values that come from an object to the query. I have this so far. I'm using a string builder, I put what the outcome of query is in the commented part
form = {x:'value1', y:'value2', z:'value3'}
return new Promise(
(resolve, reject) => {
var query = calculation.insert(form).toQuery();
//query.text value will be: 'INSERT INTO [table] ([x], [y], [z]) VALUES (#1, #2, #3)'
//query.values will be ['value1', 'value2', 'value3']
new sql.Request().input('values', sql.VarChar, query.values).query(query.text).then(result => {
return { completed: true }
}).catch(err => {
throw err;
{ completed: false };
})
}
)
But this is not working. I can't figure how to parse the query.values properly to the query. Can anyone help? Thanks
I have a weird conflict with my pouchDB code trying to update a document in my database
code:
this.addToExistingUser = function (docId, key, value) {
usersDatabaseRemote
.get(docId)
.then(function (doc) {
doc[key] = value;
return usersDatabaseRemote.put(doc, docId, doc._rev);
})
.then(function () {
console.log('added field: ' + key + ' to doc ' + docId);
})
.catch(function (err) {
console.log("error from addToExistingUser:");
console.log(JSON.stringify(err));
});
}
where :
.factory('usersDatabaseRemote', [
'pouchDB',
function (pouchDB) {
'use strict';
var usersDatabaseRemote = pouchDB('https://id:pwd#id.cloudant.com/boardl_users');
return usersDatabaseRemote;
}
])
leads to :
{"status":409,"name":"conflict","message":"Document update conflict","error":true,"reason":"Document update conflict."}
But as you can see from the code I take the revision number rev from the remote document so I don't see why is there a problem with this.
Thanks
credit: #AlexisCôté
I was calling several times the async function that updates the remote doc
pouchDBservice.addToExistingUser(userr._id, 'weight',
pouchDBservice.addToExistingUser(userr._id, 'height', userHeight);
pouchDBservice.addToExistingUser(userr._id, 'technique', userTechnique);
and this was messing with the ._rev number.
So now I am doing all the parameters at the same time in an object :
pouchDBservice.addObjectToExistingUser(userr._id, objectToAdd);
with :
this.addObjectToExistingUser = function (docId, obj) {
usersDatabaseRemote
.get(docId)
.then(function (doc) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
console.log(key, obj[key])
doc[key] = obj[key];
}
return usersDatabaseRemote.put(doc);
})
.then(function () {
console.log('addObjectToExistingUser added object: ' + JSON.stringify(obj) + ' to doc ' + docId);
})
.catch(function (err) {
console.log("error from addObjectToExistingUser:");
console.log(JSON.stringify(err));
});
};
So I am looking to model our existing redis data into aerospike. One requirement that we have is to be able to get all the keys for a given user. For eg., say we have keys such as <id>:<timestamp>. Now, at some point in time, I need to get all keys for the given id, where I would require something like a prefix search across all keys in the aerospike namespace (which are indexed) to get the values for all <id>:<timestamp> keys. Would like to know if this is possible, and if yes, how.
You cannot do a query on key prefix directly. The server only stores the key digest, so the key value (<id>:<timestamp> in your case) doesn't get indexed.
The way to model this would be to add the <id> part of your key as a separate record bin. Then you can index that bin and run a query on it.
Here is a simple example - it's using the Aerospike Node.js client but the concept is the same no matter what client you prefer:
const Aerospike = require('aerospike')
const ns = 'test'
const set = 'demo'
// connect to cluster and create index on 'id' bin
var client = Aerospike.client()
client.connect((err) => {
assertOk(err, 'connecting to cluster')
createIndex('id', 'id_idx', Aerospike.indexDataType.STRING, () => {
// create a new sample record
var userId = 'user1'
var ts = new Date().getTime()
var key = new Aerospike.Key(ns, set, `${userId}:${ts}`)
var record = { id: userId, value: Math.random() }
client.put(key, record, (err) => {
assertOk(err, 'write record')
// query for records with matching 'id'
var query = client.query(ns, set)
query.where(Aerospike.filter.equal('id', userId))
var stream = query.foreach()
stream.on('error', (error) => assertOk(error, 'executing query'))
stream.on('end', () => client.close())
stream.on('data', (record, meta, key) => {
console.log(record)
})
})
})
})
function assertOk (err, message) {
if (err) {
console.error('ERROR: %s - %s', message, err)
process.quit()
}
}
function createIndex (bin, name, datatype, callback) {
var index = {
ns: ns,
set: set,
bin: bin,
index: name,
datatype: datatype
}
client.createIndex(index, (err, job) => {
assertOk(err, 'creating index')
job.waitUntilDone(100, (err) => {
assertOk(err, 'creating index')
callback()
})
})
}
Hope this helps!