how to use IN parameter in where clause of select query of DB2 nodeJS - node.js

I am trying to use IN parameter in the WHERE clause of select query in IBM_DB2 of nodeJS.
I tried the following:
const conn = await ibmdb.open(connStr);
const query = 'SELECT NAMES FROM DB.TABLE WHERE SETUP_DATE > ? AND ID IN (?)';
const prepareSmt = await connection.prepare(query);
const result = await prepareSmt.execute(['230101', ['123','124','125']]);
const data = await result.fetchAllSync();
console.log("result = ", data);
when the above gets executed: I always get error:
Error: Wrong param format!
at /Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/odbc.js:1550:12
at SimpleQueue.next (/Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/simple-queue.js:34:5)
at SimpleQueue.maybeNext (/Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/simple-queue.js:22:10)
at SimpleQueue.push (/Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/simple-queue.js:15:8)
at ODBCStatement.odbc.ODBCStatement.execute (/Users/USERNAME/workspace/learning/ibmDB2/node_modules/ibm_db/lib/odbc.js:1524:14)
at main (/Users/USERNAME/workspace/learning/ibmDB2/index.js:14:29)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
The same query works when i use without IN parameter. Can someone please help me how to frame the query and pass the values when IN parameter used in the select query.
Using TOAD we are able to execute a query like this:
Select NAMES from DB.TABLE where SETUP_DATE > '230101' AND ID IN ('123','124','125')
And i am trying to execute the same from IBM_DB2 nodejs.
Thanks,
Naveen

Related

SQL.js use local file

I am currently using sql.js to view my database:
async function sqliteRun () { // eslint-disable-line
const SQL = await initSqlJs({
locateFile: () => 'misc/sql-wasm.wasm'
})
const db = new SQL.Database('public/misc/test.sqlite')
const stmt = db.prepare('SELECT * FROM test')
while (stmt.step()) { //
const row = stmt.getAsObject()
console.log('Here is a row: ' + JSON.stringify(row))
}
}
But then I am getting an error: "File is not a database". I double checked my file and it seems correct (I was able to view it in a sqlite file browser)
I also tried using .db and .sql, all give out the same error.
I prefer to load the file directly in the new SQL.Database() constructor. I wont be able to use fs. Any thoughts on how to do this?

How to update postgres jsonb with dynamic variables in nodejs? [duplicate]

I have following setup for my project, using the pg node-postgres package:
The simple table 'tmp' looks like this:
According to jsonORG and the postgres docs the object:
{"foo" : true}
is syntactically valid JSON, and when using the pgAdmin Query-tool with:
UPDATE tmp SET data = '{"foo": false}' WHERE id = '1'
works fine, but when i try updating my table through my express route using pg:
router.put('/updateTMP', (req, res) => {
// I use dummies in this case instead of req.body.someKey for testing purposes
let dummyJSON = {"foo":true};
let dummyID = 1;
pg.query(`UPDATE tmp SET data = '${dummyJSON}' WHERE id = '${dummyID}'`, (errUpdate, responseUpdate) => {
if (!errUpdate) { // NO ERROR
res.json({success: true, message: responseUpdate});
}
else { // ERROR
console.log(dummyJSON);
console.log(errUpdate);
res.json({success: false, message: errUpdate});
}
})
})
I get the following error from the database:
error: invalid input syntax for type json
I've tried the to_json function from postgresql and the to-json package from npm in the express route - all with the same negative result.
Am i missing some fundamental understanding or is it some formating/quoting-issue?
Thanks in advance for your ideas! ;)
ps: And yes - I've read through this, and that article..
I had the same problem. Try converting your JS object to string using JSON.stringify() before passing it into the query as pg won't always do that for you automatically.
See this issue on GitHub for more info.

How can I import a Cypher query to my Node.js logic?

I'm not a very experienced developer but I am looking too structure my project so it is easier to work on.
Lets say I have a function like this:
const x = async (tx, hobby) => {
const result = await tx.run(
"MATCH (a:Person) - [r] -> (b:$hobby) " +
"RETURN properties(a)",
{ hobby }
)
return result
}
Can I put my cypher query scripts in seperate files, and reference it? I have seen a similar pattern for SQL scripts.
This is what I'm thinking:
const CYPHER_SCRIPT = require('./folder/myCypherScript.cyp')
const x = async (tx, hobby) => {
const result = await tx.run(
CYPHER_SCRIPT,
{ hobby }
)
return result
}
..or will i need to stringify the contents of the .cyp file?
Thanks
You can use the #cybersam/require-cypher package (which I just created).
For example, if folder/myCypherScript.cyp contains this:
MATCH (a:Person)-->(:$hobby)
RETURN PROPERTIES(a)
then after the package is installed (npm i #cybersam/require-cypher), this code will output the contents of that file:
// Just require the package. You don't usually need to use the returned module directly.
// Handlers for files with extensions .cyp, .cql, and .cypher will be registered.
require('#cybersam/require-cypher');
// Now require() will return the string content of Cypher files
const CYPHER_SCRIPT = require('./folder/myCypherScript.cyp')
console.log(CYPHER_SCRIPT);

Gremlin Javascript order by function

I use gremlin-javascript (in aws Neptune) to traverse the remote graph and get a list of vertex. I want order the vertex by their createdAt date property. But since I have multiple order().by(), I want to group them by week.
const gremlin = require('gremlin')
const moment = require('moment')
const { Graph } = gremlin.structure
const { DriverRemoteConnection } = gremlin.driver
const __ = gremlin.process.statics
const { order } = gremlin.process
const getWeek = date => parseInt(moment(date).format('YYYYWW'), 10)
const graph = new Graph()
const dc = new DriverRemoteConnection(endpointNeptune)
const g = graph.traversal().withRemote(dc)
g.V().order().by(getWeek(__.values('createdAt')), order.decr)
But this throw an error: "Could not locate method: NeptuneGraphTraversal.by([202029, decr])"
Thank you in advance
Copying my earlier comment to an answer:
The by modulator is expecting a key name not a literal value. Something like
g.V().group().by('createdAt').order(local).by(keys,desc)
or perhaps depending on your data model
g.V().order().by('createdAt', order.desc)

Nodejs postgres pg syntax error

As the title says, I'm running into a syntax error using node-postgres. Here's what the code looks like
const {Pool, Client} = require('pg')
const pool = new Pool({
user: '<user>',
host: '<host>',
database: '<database>',
password: '<pw>',
port: <port>
})
let query = `SELECT * FROM user JOIN notifications ON user.user_id = notifications.user_id WHERE user_id=$1`
let values = ["123"]
pool.query(query, values)
.then(() => { /* do something */} )
.catch((err) => { console.log(err)} )
Based on this query, I get a syntax error with the message
syntax error at or near "."
Since the same query runs fine in pgAdmin, my guess is that it's module specific, but I haven't figured out what the problem is.
Any help much appreciated!
Edit: added missing bracket, thanks to Sreeragh A R
user is reserved word in postgresql you have to escape user using double quotes
let query = `SELECT * FROM "user" JOIN notifications ON "user".user_id = notifications.user_id WHERE "user".user_id=$1`

Resources