Using mariadb nodeJS connector with multiple queries - node.js

I've got a server running Node.js connecting to a MariaDb database. I'm using the Node.js connector and it's working fine for single queries. However, when I try to do multiple queries it's throwing this error:
{ Error: (conn=8439, no: 1064, SQLState: 42000) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT 2' at line 1
sql: SELECT 1; SELECT 2; - parameters:[]
at Object.module.exports.createError (\node_modules\mariadb\lib\misc\errors.js:55:10)
at Packet.readError (\node_modules\mariadb\lib\io\packet.js:506:19)
at Query.readResponsePacket (\node_modules\mariadb\lib\cmd\resultset.js:47:28)
at PacketInputStream.receivePacket (\node_modules\mariadb\lib\io\packet-input-stream.js:73:9)
at PacketInputStream.onData (\node_modules\mariadb\lib\io\packet-input-stream.js:129:20)
at Socket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
at Socket.Readable.push (_stream_readable.js:219:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
fatal: false,
errno: 1064,
sqlState: '42000',
code: 'ER_PARSE_ERROR' }
The current test code I'm using is:
conn = await pool.getConnection({multipleStatements: true});
conn.query({
multipleStatements: true,
sql: "SELECT 1; SELECT 2;"
}).then((data: any) => {
console.log(data);
conn.end();
});
The documentation suggests multipleStatements is an option, but looking through the GitHub Repo, the only places I've found it is under lib/config/connection-options.js and the GitHub documentation. I also noticed the batch option but that seems to be specifically for a load of inserts.
Is there a way to use the mariadb-connector-nodejs to run multiple queries in a single query call? If so, what else could I be doing wrong that only multi-statement queries are not working?
Versions:
- MariaDb: 10.1.34-MariaDB
- Node.js: v10.14.2
- mariadb-connector-nodejs: mariadb#2.0.2-rc

multipleStatements is the good option, but as #rolandstarke indicate, that is a connection option.
When using creating pool, you indicate pool + connection options, since pool will handle connection creation. see related documentation
Example:
const mariadb = require("mariadb");
const pool = mariadb.createPool({ multipleStatements: true });
pool.query("select 1; select 2")
.then(results => {
//select 1 results
console.log(results[0]); //{ '1': 1 }
//select 2 results
console.log(results[1]); //{ '2': 2 }
})
.catch(err => {
//handle error
});

Related

Type Error: Cannot read property 'hasListCollectionsCommand' of null

I'm trying to get all collection names in mongodb (v4.0.2) and using mongodb#3.1.10 nodejs driver. From the docs, I can see that listCollections might work, but running the following:
const Db = require('mongodb').Db
const Server = require('mongodb').Server
const db = new Db(dbName, new Server(host, port, options), {})
db.listCollections().toArray((error, collectionNames) => {
console.error(error)
console.log(JSON.stringify(collectionNames))
})
… leads to this error:
if (this.serverConfig.capabilities().hasListCollectionsCommand) {
TypeError: Cannot read property 'hasListCollectionsCommand' of null
at Db.listCollections ({path}/node_modules/mongodb/lib/db.js:493:39)
at db.createCollection ({path}/sampleMongoDB.js:19:8)
at err ({path}/node_modules/mongodb/lib/utils.js:415:14)
at executeCallback ({path}/node_modules/mongodb/lib/utils.js:404:25)
at executeOperation ({path}/node_modules/mongodb/lib/utils.js:422:7)
at Db. ({path}/node_modules/mongodb/lib/db.js:431:12)
at Db.deprecated [as createCollection] ({path}/node_modules/mongodb /lib/utils.js:661:17)
at Object.< anonymous > ({path}/sampleMongoDB.js:18:6)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
My questions are:
Is there a docs site for MongoDB NodeJs drivers where we can refer examples from?
If not, what's the correct way to query?
I was able to work it out. The MongoClient's instance returns a db instance, which inturn helps run mongodb.Db methods.
Here's a sample code that worked (Ref. to MongoDB guides)
const options = {
useNewUrlParser: true, // Add this, if you wish to avoid {https://stackoverflow.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars} issue
}
const client = new MongoClient(connectionUri, options)
return client.connect().then(() => {
const db = client.db(dbName)
return db.listCollections()
.toArray()
.then((collections) => {
// Collections array
})
})
#Community mods - if required, kindly close this question.

How to fix 'events.js :167 error Error: connect ECONNREFUSED 127.0.0.1:443' in Node.js when no other apps seems to be attempting to use the port?

I'm getting the error described below when running my node.js app after perfoming a few api calls.
The error does not always show in the exactly same place/line of code. But most of the times it is at the end of the api call.
events.js:167
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14)
Emitted 'error' event at:
at TLSSocket.socketErrorListener (_http_client.js:391:9)
at TLSSocket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
Based on similar questions here at SO my hypothesis is that a) there is something using 127.0.0.1:443 and therefore conflicting with my app or b) node is trying to use 127.0.0.1:443 but there is nothing there for it to use (my app is listening to localhost :3000).
Hyphothesis a) doesn't seem likely since after running netstat -ano | findstr 127.0.0.1:443 nothing shows up (when app is running and right after it terminates).
Also killed every node.exe and mongod.exeb using any port in my computer, closed the terminal and restarted the node app without success.
In case error is related with hypothesis b) I'm not sure how to address it.
api.post('/parsePOpdf', wagner.invoke(function(Pdfeq, Pdfdocspec, Product, User, Order){
return async function(req,res){
//... some code
pdfParser.on("pdfParser_dataError", errData => console.error(errData.parserError) );
pdfParser.on("pdfParser_dataReady", async function(pdfData) {
fs.writeFile("./test.json", JSON.stringify(pdfData), function(err){
console.log(err);
});
let pages = pdfData.formImage.Pages;
//console.log('pages 557', pages);
let order = {
orderDetails : {
supplier : [{
item : []
}]
}
};
for (const page of pages){
let value = await getItemsInPDF(page, productKeys, pdfParsingDetails, order, Product, customer, supplierLink, User);
//... more code
order = value;
}
return res.json(order);
});
pdfParser.loadPDF(pdfFile);
}
}));
I would expect the code to finish without throwing this error.
It turns out that the problem was in the api code: an http.get line to fetch a remote file was generating the conflict. This makes sense since the error was not present for other endpoints of the api.
So learning is that if the terminal reports no app using the suspected conflicting port (see question) answser should be within the same code and you need to go line by line to identify which one is causing the problem (instead of focusing on other apps trying to use the same port, like I was focusing on).

Node Cassandra driver just hangs on execute()

var cql = require('node-cassandra-cql');
var client = new cql.Client({hosts: ['*.*.*.*'], keyspace: '*',
username:'*', password: '*'});
console.log('connected to ' , client);
console.log('Querying....');
client.execute('select * from example where field1=?', [1],
function(err, result) {
console.log('inside', result);
if (err)
console.log('execute failed',err);
else
console.log('got chat ' + result.rows[0].field1);
client.shutdown();
}
);
I am using this code, the execute() callbacks aren't getting called . To test I used an incorrect IP address, it immediately responds and this line console.log('execute failed',err) logs what is below.
execute failed { [PoolConnectionError]
name: 'PoolConnectionError',
info: 'Represents a error while trying to connect the pool, all the connections failed.',
individualErrors:
[ { Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:79:26)
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: '*.*.*.*'
host: '*.*.*.*'
port: 9042 } ] }
If with right IP address nothing happens may because new cql.Client internally calls connect (asynchronously) before even connection is made execute is attempted ? All perfectly works in CQLSH, my servers are in AWS US west coast.
Any inputs welcome.
You are using the legacy Cassandra driver node-cassandra-cql, as the project readme states, it is no longer maintained:
node-cassandra-cql has graduated from community driver to being the
foundation of the official Datastax Node.js Driver for Apache Cassandra.
There will be no more development in this repository. I encourage
everyone to start migrating to the new driver as soon as you can, it's
got some great new features that you should try out, along with an
improved cql to javascript type mapping for prepared statements.
Use DataStax Node.js driver instead:
npm install cassandra-driver --save

Following tutorial to connect postgres db to node project - failing at running script to create table

i am following a guide on how to use postgres + node. I have gotten to the point of creating table creation script.
here is the code I am using from the tutorial:
var pg = require('pg');
var connectionString = process.env.DATABASE_URL || 'postgres://postgres:postgres#localhost:5432/todo';
var client = new pg.Client(connectionString);
client.connect();
var query = client.query('CREATE TABLE items(id SERIAL PRIMARY KEY, text VARCHAR(40) not null, complete BOOLEAN)');
query.on('end', function() { client.end(); });
However, when I do the step of node models/database.js, I receive the following error:
ram#ram-windows-xp-ubuntu:~/Development/Web/Projects/node-postgres$ node models/database.js
events.js:85
throw er; // Unhandled 'error' event
^
error: password authentication failed for user "postgres"
at Connection.parseE (/home/ram/Development/Web/Projects/node-postgres/node_modules/pg/lib/connection.js:539:11)
at Connection.parseMessage (/home/ram/Development/Web/Projects/node-postgres/node_modules/pg/lib/connection.js:366:17)
at Socket.<anonymous> (/home/ram/Development/Web/Projects/node-postgres/node_modules/pg/lib/connection.js:105:22)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
I am new to using the ubuntu and I tried to follow the steps from this guide but confused. Sorry for the bother friends please if you can do the needful I will be humbled.

Count method throws syntax error when used with where clause in loopback

I am using loopback/strong loop in node.js.
I am trying to use where clause in count method for paginition purpose. Whenever I try to use where clause, it gives me a mysql syntax error for as simple query as below.
Ride.count({
where:{"id":20}
},function(err,totalCount){
if (err) {
log.info("Total error ", err);
fn(err);
}else {
log.info("Total count ", totalCount);
}
});
this is the error I get.
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '20' at line 1\n at Query.Sequence._packetToError (D:\Code\liftee\rest-services\node_modules\loopback-connector-mysql\node_modules\mysql\lib\protocol\sequences\Sequence.js:48:14)\n at Query.ErrorPacket (D:\Code\liftee\rest-services\node_modules\loopback-connector-mysql\node_modules\mysql\lib\protocol\sequences\Query.js:83:18)\n at Protocol._parsePacket (D:\Code\liftee\rest-services\node_modules\loopback-connector-mysql\node_modules\mysql\lib\protocol\Protocol.js:271:23)\n at Parser.write (D:\Code\liftee\rest-services\node_modules\loopback-connector-mysql\node_modules\mysql\lib\protocol\Parser.js:77:12)\n at Protocol.write (D:\Code\liftee\rest-services\node_modules\loopback-connector-mysql\node_modules\mysql\lib\protocol\Protocol.js:39:16)\n at Socket. (D:\Code\liftee\rest-services\node_modules\loopback-connector-mysql\node_modules\mysql\lib\Connection.js:92:28)\n at Socket.emit (events.js:107:17)\n at readableAddChunk (_stream_readable.js:163:16)\n at Socket.Readable.push (_stream_readable.js:126:10)\n at TCP.onread (net.js:529:20)\n --------------------\n at Protocol._enqueue (D:\Code\liftee\rest-services\node_modules\loopback-co
Try without using where clause. I have tested this on my model and it works.
Ride.count(
{"id":20},
function(err,totalCount){
if (err) {
log.info("Total error ", err);
fn(err);
}else {
log.info("Total count ", totalCount);
}
}
);
Have a look at the strongloop API explorer. You only need to pass value to count function.

Resources