dictSession.getSchema is not a function (Node.js/MySQL/xdevapi) - mysql

I have started using xdevapi for Node.js as mysql connector. By following this guide (https://dev.mysql.com/doc/x-devapi-userguide/en/connecting-to-a-single-mysqld-node-setup.html):
var mysqlx = require('#mysql/xdevapi');
var dictSession = mysqlx.getSession( {
host: 'localhost', 'port': 33060,
user: 'root', password: '' } )
var db1 = dictSession.getSchema('test')
I got an error:
dictSession.getSchema is not a function

You are using synchronous JavaScript syntax that only works in the MySQL Shell (as depicted in the link you point to). Unfortunately, that guide does not seem to include a proper snippet for the Connector/Node.js version where the getSession() method is asynchronous and returns a Promise, which means you need to attach a proper then() handler, in which dictSession will eventually be resolved.
mysqlx.getSession({ host: 'localhost', 'port': 33060, user: 'root', password: '' })
.then(function (dictSession) {
var db1 = dictSession.getSchema('test')
});
or you can use the async/await flavour:
var dictSession = await mysqlx.getSession({ host: 'localhost', 'port': 33060, user: 'root', password: '' })
var db1 = dictSession.getSchema('test')
I'll make sure the guide will include a proper example.
Disclaimer: I'm the X DevAPI Node.js connector lead dev.

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 / MariaDB Connector -- createConnection() does not return proper connection object

Node.js is installed in the following version on my Ubuntu 18/04 machine:
node -v
v14.16.0
The following modules are installed:
sudo npm list -g --depth=0
/usr/lib
├── mariadb#2.5.3
└── npm#6.14.11
The required package
The relevant code in my app file maria.js looks like this:
const mariadb = require('mariadb');
let conn = mariadb.createConnection({
host: 'localhost',
database: 'db1',
user:'dbuser1',
password: 'dbpwd',
port: 3306
});
conn.connect(function(err){
if(err){
console.log('Database connection error');
}else{
console.log('Database connection successful');
}
});
The required package 'mariadb' is satisfied and createConnection() does not return an error.
However, getting to the connect() statement, NodeJS returns the following:
conn.connect(function(err){
^
TypeError: conn.connect is not a function
at Object.<anonymous> (/home/juerg/bin/node/maria.js:12:6)
So looks like that createConnection() returns an empty JS object. Any other Connection class method won't work either, and I can't discover an error in this short code fragment.
mariadb.createConnection returns a promise so you would have to await for it to return the connection, like:
let conn = await mariadb.createConnection({
host: 'localhost',
database: 'db1',
user:'dbuser1',
password: 'dbpwd',
port: 3306
});
Also there might not be a need to call conn.connect() separately since it is already done in createConnection: Source Code
Or if you do not want to make your function async then you can do something like:
mariadb.createConnection({
host: 'localhost',
database: 'db1',
user:'dbuser1',
password: 'dbpwd',
port: 3306
}).then((conn) => {
// Do here what you want to do with MySQL connection...
});
As per the MariaDB connector documentation there are two available API's, Promise and Callback, Promise is the default API which you require and use in the following manner.
const mariadb = require("mariadb");
mariadb.createConnection({
host: 'localhost',
database: 'database',
user:'username',
password: 'password',
port: 3306
}).then(conn => {
// Execute a query/do whatever you need with the connection object here.
});
Alternatively, you can use the Callback API (which to note, is for compatibility with the mysql and mysql2 modules) by modifiyig the require statement and then connecting as follows:
const mariadb = require("mariadb/callback");
const conn = mariadb.createConnection({
host: 'localhost',
database: 'database',
user:'username',
password: 'password',
port: 3306
});
conn.connect(err => {
if (err) return console.log("Failed to connect");
console.log(`Successfully connected to mariadb server: ${conn.serverVersion()}`);
});
// Execute a query/do whatever you need with the connection object here.

Ignoring invalid configuration option passed to Connection: root

I am getting started with mysql database for my NODEJS application
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
root: 'root',
database:'node-complete',
password: 'Pratik#123'
})
My root password is the one coded above.
I am getting this error:-
Ignoring invalid configuration option passed to Connection: root.
This is currently a warning, but in future versions of MySQL2, an error will be thrown if you pass an invalid configuration option to a Connection
Can some help me to fix this issue?
module.exports = pool.promise()
the property in connection options must be named user, not root
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database:'node-complete',
password: 'Pratik#123'
});
I was getting the same problem, i used
const pool = mysql.createPool({
host: 'localhost',
username: 'root',
database: 'node-complete',
password: '24GM#L#PM+AU',
port: '3306'
});
its not supposed to say "username" but instead just "user" like below
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'node-complete',
password: '24GM#L#PM+AU',
port: '3306'
});
it works when you change username to user:
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user : 'root',
database : 'node-complete',
password : 'node-complete'
});
PS: I watch the same lecture as you do ( database : 'node-complete', ) gave it away :D
you have to change the connection property root as user
const pool = mysql.createPool({
host:'localhost',
user:'root',
password:'admin',
database:'node-complete'
})

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

bug with angular2-meteor app :failed connection to mysql via meteor

i'm trying to connect to mysql database with meteor using nodets:mysql and i'm facing this error :
Unhandled rejection Error: No infromation can be fetched by your database, please check your permissions
this is my part of code :
Meteor.startup(function() {
//Start of changes
var connectionSettings = {
host: '127.0.0.1',
user: 'root',
password: '',
database: 'test'
};
var db = Mysql.connect(connectionSettings);
})
i need to add the port of mysql
Meteor.startup(function() {
//Start of changes
var connectionSettings = {
host: '127.0.0.1',
port : (mysqlport),
user: 'root',
password: '',
database: 'test'
};
var db = Mysql.connect(connectionSettings);
})