How can I use SSL with a node-mysql pooled connection? - mysql

I'm using node-mysql by felixge to make database connections via Node.JS. I'm making lots of connections, so I thought it would be a good idea to use a connection pool:
var mysql = require('mysql');
function createPool() {
var pool = mysql.createPool({
dateStrings : true,
host : '***',
user : '***',
password : '***',
database : '***'
});
return pool;
}
However, while node-mysql makes it very simple to use SSL for a normal connection:
var connection = mysql.createConnection({
host : 'localhost',
ssl : {
ca : fs.readFileSync(__dirname + '/mysql-ca.crt')
}
});
It doesn't seem to show in the documentation that the SSL options are available when utilizing a connection pool.
How can I use SSL with a node-mysql pooled connection? or rather, can it be done at all?

I re-read the docs and noticed this line:
Pools accept all the same options as a connection.
Sorry about that. Anyway, the answer is that it accepts the same options as a normal connection.

var mysql = require('mysql');
function createPool() {
var pool = mysql.createPool({
dateStrings : true,
host : '***',
user : '***',
password : '***',
database : '***',
ssl : {
ca : fs.readFileSync(__dirname + '/mysql-ca.crt')
}
});
return pool;
}

Related

Query a Google cloud SQL instance in Node.js from a GKE pod with cloud sql proxy running as sidecar

I am tasked with adding a MySql database to a microservice application for work. I am the only person on this task and don't really have anyone to turn too for advice so I am reaching out to the internets for help. I have succesfully deployed a pod that is running a small test application and the cloud-sql-proxy. I have scoured the documentation trying to figure out how to connect to the db and perform a query and this is what I have come up with (but it doesn't work).
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const cors = require('cors');
const axios = require('axios');
const app = express();
app.use(bodyParser.json());
app.use(cors())
app.enable('trust proxy');
// Automatically parse request body as form data.
app.use(express.urlencoded({extended: false}));
// This middleware is available in Express v4.16.0 onwards
app.use(express.json());
// [START cloud_sql_mysql_mysql_create_tcp]
const createTcpPool = async config => {
// Extract host and port from socket address
const dbSocketAddr = process.env.DB_HOST.split(':');
// Establish a connection to the database
return mysql.createPool({
user: process.env.DB_USER, // e.g. 'my-db-user'
password: process.env.DB_PASS, // e.g. 'my-db-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: dbSocketAddr[0], // e.g. '127.0.0.1'
port: dbSocketAddr[1], // e.g. '3306'
// ... Specify additional properties here.
...config,
});
};
// [END cloud_sql_mysql_mysql_create_tcp]
var pool = createTcpPool();
const stuff = pool.query('SELECT * FROM entries');
function getQuery() {
console.log(stuff);
}
getQuery()
Here is a picture of the error I get when I deploy the pod and the logs from the proxy to verify it's running
I'm pretty new to MySql and GKE and trying to figure this out has been a huge struggle. I just want to know how I can actually query the db and would greatly appreciate some assistance or code sample to point me in the right direction, thanks internets.
As mentioned in the thread1 ,
Handling such functions can be done through following example :
const mysql = require('mysql');
const pool = mysql.createPool({ connectionLimit : 1, socketPath: '/cloudsql/' + '$PROJECT_ID:$REGION:$SPANNER_INSTANCE_NAME',
user: '$USER', p
assword: '$PASS',
database: '$DATABASE' });
exports.handler = function handler(req, res)
{ //using pool instead of creating connection with function call
pool.query(`SELECT * FROM table where id = ?`,
req.body.id, function (e, results) {
//made reply here
}); };
For more information you can refer to the documentation related to TCP connection when using Node js.
const createTcpPool = async config => {
// Extract host and port from socket address
const dbSocketAddr = process.env.DB_HOST.split(':');
// Establish a connection to the database
return mysql.createPool({
user: process.env.DB_USER, // e.g. 'my-db-user'
password: process.env.DB_PASS, // e.g. 'my-db-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: dbSocketAddr[0], // e.g. '127.0.0.1'
port: dbSocketAddr[1], // e.g. '3306'
// ... Specify additional properties here.
...config,
});
};
So trying to create a pool by calling createTcpPool seems to have been the issue. I changed it to
let pool = mysql.createPool({
user: process.env.DB_USER, // e.g. 'my-db-user'
password: process.env.DB_PASS, // e.g. 'my-db-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: '127.0.0.1', // e.g. '127.0.0.1'
port: '3306'
});
and got a succesful return from my db.

Nodejs mysql2 not throwing connection or query error

I am trying to capture connection error on nodejs while using mysql or mysql2 node module.
My code is
console.log("Connecting to database")
try{
var connection = mysql.createConnection({
host : process.env.DB_HOST,
user : process.env.DB_USERNAME,
password : process.env.DB_PASSWORD,
database : process.env.DB_NAME
});
connection.connect();
console.log("Connected")
}
catch(exce)
{
console.log(exce)
}
The mysql server is not running and all details are wrong here. I am expecting this code to throw a connection error but this does not happen. Instead, I am receiving the following console output.
Connecting to database
Connected
I don`t know why there is no connection error thrown by mysql module.
The following solution suggested by #Anatoly worked for me.
var mysql=require("mysql2/promise")
var connected=true
console.log("Connecting to database")
try{
var connection =await mysql.createConnection({
host : process.env.DB_HOST,
user : process.env.DB_USERNAME,
password : process.env.DB_PASSWORD,
database : process.env.DB_NAME
});
// connection.connect();
console.log("Connected")
}
catch(exce)
{
console.log(exce)
connected=false
}
```

Connecting to MariaDB with nodejs over ssl with clear text password

I am trying to connect to mariadb instance over ssl,
var mysql = require('mysql');
var conn = mysql.createConnection({
user: 'user',
password: 'password',
debug: true,
port: '3306',
host: "host",
ssl: {
"ca": ca
}
});
conn.connect();
the ca is an array of cerificates. I am getting the following error.
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MariaDB client
I am able to connect to the db using python with mysql.connector.
After setting it on debug mode, I can see the client is trying to use mysql_native_password authentication. I need to use mysql_clear_password.
if your server supports plugin based auth and auth switch request, you can try following code:
var mysql = require('mysql2');
var conn = mysql.createConnection({
user: 'user',
password: 'password',
debug: true,
port: '3306',
host: "host",
ssl: {
"ca": ca
},
authSwitchHandler: (data, cb) => {
if (data.pluginName === 'mysql_clear_password') {
// https://dev.mysql.com/doc/internals/en/clear-text-authentication.html
var password = 'password\0';
var buffer = Buffer.from(password);
cb(null, buffer);
}
});
unfortunately initial auth type is always mysql_native with node-mysql2 ( I hope to fix this soon ), so you need both auth_plugin and auth_switch support enabled on server
Edit: Syntax

NodeJS MySQL - How to know connection is release or not

I am developing NodeJS + MySQL web API.
I am using mysql npm module.
I want know connection is release or not is there any function or variable.
Like
if(!connection.isRelease() OR !connection.isClose() OR !connection.end()) {
connection.release();
}
Is there any specific function to know connection is release or not?
I am getting error like "connection already release"
You can check if the connection is in the pool to see if it was released. The index in the free connections will be -1 if the connection is not released. Here is an example.
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : ''
});
pool.getConnection(function(err, connection) {
connection.query( 'SELECT something FROM sometable', function(err, rows) {
console.log(pool._freeConnections.indexOf(connection)); // -1
connection.release();
console.log(pool._freeConnections.indexOf(connection)); // 0
});
});
Just in case you don't have access to the pool you can also do this:
connection._pool._freeConnections.indexOf(connection)
This will give you the same answer as the accepted answer.

What does connection.connect() do in node-mysql?

What does the connection.connect() do in node-mysql library?
My code looks like this
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'ap-cdbr-azure-east-a.cloudapp.net',
user : '<user>',
password : '<password>',
database : '<database>',
});
connection.connect();
Later I run the query.
Even if I remove connection.connect() the code works as is. Some examples have it, some don't. What is the specific purpose for connect() ?
The recommended way to establish a connection is this:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
});
However, a connection can also be implicitly established by invoking a query:
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function(err, rows) {
// connected! (unless `err` is set)
});
Depending on how you like to handle your errors, either method may be appropriate. Any type of connection error (handshake or network) is considered a fatal error.
Courtesy: https://github.com/felixge/node-mysql