I want to use the same pattern for destructuring query results, but seems I cannot. In the following code:
var {rows} = await client.query("SELECT id FROM mytable;");
var Id = rows[0].id; //destructured here as expected
if I then follow that with:
rows = await client.query('SELECT max(id) as id FROM table2;');
The only way I can access the value is like this:
rows.rows[0].id;
Shouldn't I be able to access as in the first instance, like this?
rows[0].id;
Do I need to somehow reset {rows}?
Very new to JS so finding my way.
You still need to restructure the variable. Simply assign to rows will just get the full response object assigned to the variable, as you've seen.
Destructuring to the same variable has a couple gotchas because you can't do this:
let {rows} = await client.query("SELECT id FROM mytable;");
// Error: unexpected token without declaration
{rows} = await client.query('SELECT max(id) as id FROM table2;');
// Error: Identifier 'rows' has already been declared
let {rows} = await client.query('SELECT max(id) as id FROM table2;');
You can declare var multiple times:
var {rows} = await client.query("SELECT id FROM mytable;");
// no problemo
var {rows} = await client.query('SELECT max(id) as id FROM table2;');
If you want to declare with let then you need to do something like:
let {rows} = await client.query("SELECT id FROM mytable;");
// this works too…
({rows} = await client.query('SELECT max(id) as id FROM table2;'));
Related
I handle my SQL queries like this (which works):
const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
database: "MyDatabase",
server: "localhost\\SQLEXPRESS",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
async function runSQLQuery(insertReq, query) {
try {
await conn.connect();
var result = await insertReq.query(query);
await conn.close();
return result;
} catch (ex) {
console.log(ex);
return undefined;
} finally {
if (conn.connected)
conn.close();
}
}
and create the querys like this (which also works):
exports.getClientByID = async function (ID) {
var insertReq = conn.request();
insertReq.input("ID", sql.UniqueIdentifier, ID);
const request = await runSQLQuery(insertReq, `SELECT TOP (1) * FROM ${ClientTabel} WHERE ID = #ID`);
return request.recordset[0]
};
But now I want to add an Array as Parameter like this (and this doesn't work):
exports.getUsersWithProperty = async function (properties) {
var insertReq = conn.request();
insertReq.input("properties", sql.NVarChar, properties);
const request = await runSQLQuery(insertReq, `SELECT * FROM ${ClientTabel} WHERE Property IN #properties`);
return request.recordset;
};
But with this I only get a
Request Error" Wrong Syntax near "#properties".
I guess the type sql.NVarChar is wrong but I don't know what the right type is. Whats the solution for this?
OK, for a start, you need to add brackets around the values.
An IN clause is like this:
WHERE somecolumn IN ('value1','value2','value3')
you'll also have to make sure that after your #properties string replacement is done, you end up with a statement that looks like the clause above, with the quotes and commas in the right places.
Alternately, if #properties is a string like Value1,Value2,Value3 and so on, you could pass it to a T-SQL table-valued function that returns a table like this:
WHERE somecolumn IN dbo.ExtractStringList(#StringList)
Does any one know - how we can specify autoincrement for two columns in indexeddb.
I know - we can specify autoincremnt for one column while creating table like this -
var objectStore = thisDb.createObjectStore("note", { keyPath: "id", autoIncrement:true });
but not able to find how we can do the same for multiple columns. Also as far as i know - we cant get the value of autoincrement. The value will be autoincremented & added when we will insert the data. So if i can get the autoincrement value somehow, that would the solution too.
You cannot create two auto-incremented properties in a store. That feature is only available for the property defined as the key path.
You can easily get the auto-incremented value. The value is provided as the result of the put or add request that inserted a new object.
For example:
function addThing(db, thing) {
return new Promise((resolve, reject) => {
let id = undefined;
const transaction = db.transaction('things', 'readwrite');
const store = transaction.objectStore('things');
// wait to resolve the promise until the transaction is completed
// so that we do not prematurely pretend the operation succeeded. resolve
// to the value of the new id
transaction.oncomplete = event => resolve(id);
transaction.onerror = event => reject(event.target.error);
// store.add also works here
const request = store.put(thing);
// listen for the add event and grab the value of the new id
// that indexedDB generated and store it in the id variable
request.onsuccess = event => id = event.target.result;
});
}
async function doSomething() {
const something = {bar: 'baz'};
const db = await open(...);
const id = await addThing(db, something);
db.close();
something.id = id;
console.log(something);
}
I am trying to use the unique id that firebase gives to get the data value from the child. I can get the data value from the child by hardcoding the unique id. But the database will have multiples stored and I want to get newest stored data.
I have tried to use the pushId but it makes the child come back null
function handler(agent){
const db = firebase.database();
// const numberParam = agent.parameters.checknumber;
const ref = db.ref('/cnumber/transaction/{pushId}/');
return ref.once('value')
.then((datashot) =>{
const number = datashot.child('cnumber').val();
agent.add('The number is' + number);
console.log(number);
});
}
If you're trying to retrieve the latest child node:
function handler(agent){
const db = firebase.database();
const ref = db.ref('/cnumber/transaction');
return ref.orderByKey().limitToLast(1).once('child_added').then((datashot) =>{
const number = datashot.child('cnumber').val();
agent.add('The number is' + number);
return number;
});
}
I am very new to PostgreSQL please bear with me.
I need to read records from the table using select query with where condition.
Eg: select * from switch where switchId=10;
QueryFactory.js
let queryMap = {
“getSwitchInfo”: ‘select * from switch where switchId=?’
}
module.exports=queryMap;
Controller.js
let client = require(rootdir+’dao/postgresSQL’);
let queryFactory = require(rootdir+’/dao/QueryFactory’);
let query = queryFactory.getQuery(“getSwitchInfo”);
let switchId = req.query.switchId;
client.query(query, function(err, res){
if(err){
}
});
Please see:- this switchId value 10 I get from client and using query parameter I am getting it in my node backend layer.
Kindly suggest how can I pass switchId to the query as a parameterized value.
I found solution myself for this issue. Added params to an array and passed this array as a second param to client.query method and in the query where condition I added $1. It is working fine now
QueryFactory.js
let queryMap = {
“getSwitchInfo”: ‘select * from switch where switchId=$1’
}
module.exports=queryMap;
Controller.js
let params = [req.query.switchId];
client.query(query, params, function(err, res){
if(err){
}
});
i am using sequelize.js in node app to fetch data from a query and then run another sequelize raw query for each result element. but dude to callbacks i am not getting results.
my code:
var raw_query1 = "select id,name,has_results from users";
sequelize.query(raw_query1).then(function(results) {
var outputArray = []; // to store use results with additional results
for(i=0;i<results.length;i++){
outputArray[i].name = results[i].name;
var raw_query2 = "select * from meta where user_id = "+resulsts[i].id;
sequelize.query(raw_query2).then(function(meta_results) {
outputArray[i].meta = meta_results;
}
}
return res.json(outputArray); //Returning parsed results
});
i think we need to use promise here but i am a newbie from php and dont know how to proceed thanks in advance.
You need to use bluebird.map.
var raw_query1 = "select id,name,has_results from users";
sequelize.query(raw_query1).then(function(results) {
return bluebird.map(results, function(user){
var raw_query2 = "select * from meta where user_id = "+user.id;
return sequelize.query(raw_query2)
})
.then(function(metas){
return res.json(metas);
});
});