Redshift data access from node jdbc - node.js

I am getting below error when I try to data from redshift with the below mentioned code
var jdbc = new ( require('jdbc') );
var config = {
libpath: 'C:/Users/ABCD/Desktop/jar/RedshiftJDBC41-1.1.6.1006.jar',
//libs: [__dirname + 'path/to/other/jars.jar'],
drivername: 'com.amazon.redshift.jdbc41.Driver',
url: 'jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/dev',
user: 'xxxx',
password: 'xxxxx'
};
jdbc.initialize(config, function(err, res) {
if (err) {
console.log(err);
}
});
var genericQueryHandler = function(err, results) {
if (err) {
console.log(err);
} else if (results) {
console.log(results);
}
jdbc.close(function(err) {
if(err) {
console.log(err);
} else {
console.log("Connection closed successfully!");
}
});
};
jdbc.open(function(err, conn) {
if (conn) {
// SELECT statements are called with executeQuery
jdbc.executeQuery("select * from information_schema.tables", genericQueryHandler);
}
});
Error:
C:\Users\ABCD> node redshift.js
C:\Users\ABCD\node_modules\jdbc\lib\jdbc.js:62>
if(this._props.getPropertySync('user') === undefined){>
^ TypeError: undefined is not a function
at JDBCConn.initialize
(C:\Users\ABCD\node_modules\jdbc\lib\jdbc.js:62:20)
at Object.<anonymous>
(C:\Users\ABCD\Desktop\AngularJS\redshift.js:15:6)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
Could you please let me know whether there is nay issue with the above mentioned node jdbc usage for redshift?

Please be aware that this answer applies to node-jdbc 0.0.15 and earlier only. It will not work for node-jdbc 0.1.1 or later, as the API has been completely reworked and is not backwards-compatible.
Try replacing the two lines in your configuration
user: 'xxxx',
password: 'xxxxx'
with
properties: [
['user', 'xxxx'],
['password', 'xxxxx']
]
I got the same error as you attempting to use Node to connect to a local Oracle XE database. After making the change above I was able to connect. I don't believe the error you are getting is specific to RedShift - I believe it affects all databases.
Note that the properties above have to be specified as an array of 2-element arrays. An object such as the following would seem the obvious way to specify the properties, but it doesn't work:
// Don't do this, it doesn't work.
properties: {
user: 'xxxx',
password: 'xxxxx'
}
To be honest, the fix I've proposed above is a workaround. I only found it by reading the source of the jdbc module. I can't say I'm terribly impressed with this module, what with the example code given in the documentation not working, and with a somewhat counter-intuitive and undocumented format for specifying custom properties.

Related

Connection to oracle database via nodeJS

I'm trying to establish an Oracle connection using NodeJS but while trying to connect i am receiving below error.
Error: Error: DPI-1047: Cannot locate a 64-bit Oracle Client library: "The specified module could not be found". See https://oracle.github.io/odpi/doc/installation.html#windows for help
Node-oracledb installation instructions: https://oracle.github.io/node-oracledb/INSTALL.html
You must have 64-bit Oracle client libraries in your PATH environment variable.
If you do not have Oracle Database on this computer, then install the Instant Client Basic or Basic Light package from
http://www.oracle.com/technetwork/topics/winx64soft-089540.html
A Microsoft Visual Studio Redistributable suitable for your Oracle client library version must be available.
at OracleDb.getConnection (C:\NodeCon\node_modules\oracledb\lib\oracledb.js:270:10)
at C:\NodeCon\node_modules\oracledb\lib\util.js:180:16
at new Promise (<anonymous>)
at OracleDb.getConnection (C:\NodeCon\node_modules\oracledb\lib\util.js:168:14)
at C:\NodeCon\server.js:41:32
at Object.<anonymous> (C:\NodeCon\server.js:58:3)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14) {
errorNum: 0,
offset: 0
I've downloaded and installed 64 bit Oracle Client Library but still below error appears.
Using Visual Studio Code v.1.36 as my editor.
NodeJS code i'm using is as below :
let connection;
var oracledb = require('oracledb');
(async function(){
try{
connection = await oracledb.getConnection({
user: 'Username',
password: 'Password',
connectString: 'hostname:portname/servicename'
});
console.log("Successfully connected");
} catch(err){
console.log("NOT connected");
}finally{
if(connection){
try{
await connection.close();
}catch(err){
console.log("Errror");
}
}
}
})()
Any help will be much appreciated. Thanks.
This got resolved by following code:
oracledb.getConnection({
user: 'username',
password: 'Password',
connectString: 'hostname:portname/servicename'
},
function(err, connection) {
if (err) throw err;
connection.execute(
//Your database query here.
//below code if you want to fetch data from database and show it on terminal
function(err,results){
var metaData = {};
var rows = {};
console.log("error")
if (err){
throw err
}
metaData.name1 = results.metaData[0].name;
metaData.name2 = results.metaData[1].name;
rows.row1 = results.rows[0][0];
rows.row2 = results.rows[0][1];
rows.row3 = results.rows[0][2];
console.log(metaData.name1+" : "+rows.row1)
console.log(metaData.name2+" : "+rows.row2)
console.log("Successfully connected");
);
}
And if you're connecting via VPN make sure to connect to the server first then run above.

SyntaxError: Unexpected token function in async function?

Hi everyone I'm beginner in Nodejs and mongoose.I have tried to insert and retrieve the data in mongoose.I'm using async await function to execute one by one (sequence).can anyone help me? Thanks in advance....
i.e: I want to execute (Async await)concept (SEQUENCE STEP)
1.connect the db
2.create the user
3.find the user.
I'm getting the error :
async function calltaskone(){
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
Code for your reference:
'use strict';
const mongoose=require('mongoose');
const calldbconnect=()=>{
return new Promise((resolve,reject)=>{
if(true){
mongoose.connect('mongodb://vdsd:vdwdwh12dw3,#ds11dwdw.mlab.com:1w5664/vorganisation',{useNewUrlParser:true},(err,db)=>{
if(err){
console.log(err);
reject('Db is not connected');
}
else{
resolve('Db is connected');
}
});
}
});
}
const schemadesign=new mongoose.Schema({
clientName:String,
clientId:Number,
clientAddress:String
});
const modeldata=mongoose.model('clientInfo',schemadesign);
const data=[{
clientName:'VIGNESH Mack',
clientId:4128,
clientAddress:'UK'
},{
clientName:'VIGNESH Tokyo',
clientId:4988,
clientAddress:'USA'
}];
function calldatasave(){
return new Promise((resolve,reject)=>{
modeldata.create(data,(err,a,b)=>{
if(err){
reject(`Error occured while data saved ${err}`);
}
else{
resolve('Data saved successfully');
}
});
});
}
const calldatafind=()=>{
return new Promise((resolve,reject)=>{
if(true){
console.log('try to find');
modeldata.find({'clientId':4988},(err,data)=>{
if(err){
reject(`Error occured while find data: ${err}`)
}
else{
console.log(data);
resolve('Data found');
}
});
}
});
}
async function calltaskone(){
const a=await calldbconnect();
console.log(a);
const b=await calldatasave();
console.log(b);
const c=await calldatafind();
console.log(c);
}
calltaskone();
I believe you're using a older version of Node. Async functions are not supported by Node versions older than version 7.6. You can check here.
If you want to use async/await then you need to transpile using Babel for your node version.
Edit:
As you said you are using v7.3, you can use (from v7.0 to v7.5) the --harmony flag to enable the experimental features. To know more about the flag, check this out: What does `node --harmony` do?

Mongorito: save(...).then is not a function

I tried something similar to the example given on the readme.md file:
var Mongorito = require('mongorito');
var Model = Mongorito.Model;
Mongorito.connect('mongodb://localhost:27017/cr-test');
class User extends Model {
collection() {
return 'users';
}
}
var user1 = new User({
name: "James Gosling",
email: "user1#gmail.com",
password: "changeme"
});
user1.save().then(() => {
console.log('User Created');
});
when I run node --harmony server.js I get this error:
user1.save().then(() => {
^
TypeError: user1.save(...).then is not a function
at Object.<anonymous> (...\app\server.js:24:14)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)
at startup (node.js:141:18)
at node.js:980:3
Could someone explain me how could I fix that?
The readme on GitHub is outdated, the project's website now states:
MongoDB ODM for Node.js based on ES6 generators.
No callbacks or promises.
It uses generators, which can find an example of on the getting started page:
'use strict';
function* saveUser () {
var user1 = new User({
name: "James Gosling",
email: "user1#gmail.com",
password: "changeme"
});
yield user1.save();
}
In order for generators to work, you must use 'use strict;' and the function* syntax. This GitHub project has additional examples.
Also, starting with Node v4, you no longer need the --harmony (now a synonym of --es_staging) flag for generators.
or you can do like this also ... but here you can execute just a single statement
user1.save().then(savedUser => console.log(`saved user: ${savedUser}`));

Using node.js to connect to impala via jdbc

I'm using the npm module jdbc to try to connect to Cloudera Impala.
I have tried both the apache hive-jdbc-0.13.1-cdh5.3.3.jar for hiveserver2
as well as the Cloudera JDBC ImpalaJDBC41.jar
var jdbc = new (require('jdbc'));
var config = {
libpath: '/home/ubuntu/downloads/impala_jdbc/hive-jdbc-0.13.1-cdh5.3.3.jar',
libs:'/home/ubuntu/downloads/impala_jdbc/lib/*.jar',
drivername: 'org.apache.hive.jdbc.HiveDriver',
url: 'jdbc:hive2://54.172.122.6:21050/;auth=noSasl' + process.argv[2]
};
//Initialize jdbc object
jdbc.initialize(config, function(err, res){ if (err){ console.log(err); } });
jdbc.open(function(err, conn) {
if (conn) {
//Run first query
jdbc.executeQuery('show databases', function(err, results){
if (err){ console.log(err); }
else if (results) { console.log(results); }
});
}else{
console.log('Connection object:' + conn);
console.log(err);
}
});
jdbc.close(function(err){
if(err) { console.log(err); }
else { console.log('Connection closed successfully!');}
});
whenever I run it (after correcting for each driver path)
I get the following
/home/ubuntu/PlayArea/ImpalaJDBC/node_modules/jdbc/lib/jdbc.js:22
java.classpath.push.apply(java.classpath, self._config.libs);
^
TypeError: Function.prototype.apply: Arguments list has wrong type
at JDBCConn.initialize (/home/ubuntu/PlayArea/ImpalaJDBC/node_modules/jdbc/lib/jdbc.js:22:24)
at Object.<anonymous> (/home/ubuntu/PlayArea/ImpalaJDBC/server.js:12:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:935:3
I'm assuming that my libs path is not finding all the jars needed.

Nodejs Cassandra Client [node-cassandra-client]

I tried connecting to my cassandra cluster [version 1.0.6] via nodejs using node-cassandra-client
This is my sample script
var Connection = require('cassandra-client').Connection;
var con = new Connection({host:'x.x.x.x', port:9160, keyspace:'Stats', timeout:10000});
console.log(con);
con.execute('UPDATE TestCF ?=? WHERE key=?', ['cola', '1', '20120132'], function(err) {
if (err) {
console.log("Failed");
} else {
console.log("success");
}
});
On executing the script
The "sys" module is now called "util". It should have a similar interface.
node-cassandra-client.driver: connecting x.x.x.x:9160 {}
{ validators: {},
client: null,
connectionInfo:
{ host: 'x.x.x.x',
port: 9160,
keyspace: 'Stats',
timeout: 10000 },
timeout: 10000 }
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot call method 'execute_cql_query' of null
at [object Object].execute (/home/tamil/workspace/TestProjects/node-cass/node_modules/cassandra-client/lib/driver.js:367:17)
at Object.<anonymous> (/home/tamil/workspace/TestProjects/node-cass/index.js:5:5)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
My nodetool stats
Address DC Rack Status State Load Owns Token
x.x.x.x datacenter1 rack1 Up Normal 1.03 MB 100.00% 0
What would be the error reason? and Need some help to fix this
the client inside your connection is null. You need to connect() first. Here's an example (ignores all errors):
var con = new Connection({host:'x.x.x.x', port:9160, keyspace:'Stats', timeout:10000});
con.connect(function(err) {
assert.ifError(err);
con.execute('SELECT COUNT(*) FROM TestCF', [], function(err, rows) {
con.close(function(err) {
// you're done now.
});
});
});
I recommend using async to handle the ordering of connct, query, close, etc.
Looks like some kind of problem with the node.js thrift driver. I've had more luck with Helenus.

Resources