Why is testing a sequelize connection to MySQL causing timeout? - mysql

New to node and making a generic express application that connects to MySQL db using sequelize. Doing some unit tests on the db connection with jasmine-node and I keep getting timeouts when i try to connect with sequelize.
// Test the MySQL connection
describe("MySQL", function() {
it("is connectable", function(next) {
var mysql = require('mysql');
var dbconfig = require('../config/database');
var connection = mysql.createConnection(dbconfig.connection);
connection.connect(
function(err, db) {
expect(err).toBe(null);
connection.end();
next();
}
);
});
it("is connectable using sequelize", function(next){
var dbconfig = require('../config/database');
var Sequelize = require('sequelize');
var sequelize = new Sequelize(dbconfig.connection.database, dbconfig.connection.user, null,
function(err, db){
expect(err).toBe(null);
sequelize.close();
next();
}
);
});
});
Of the two tests above, the first passes fine, but the test for sequelize times out. Here is the what I get on the console.
Failures:
1) MySQL is connectable using sequelize
Message:
timeout: timed out after 5000 msec waiting for spec to complete
Stacktrace:
undefined
Finished in 6.267 seconds
Here is the database config file.
// config/database.js
module.exports = {
'connection': {
'dialect': 'mysql',
'user': 'root',
'password': '',
'host': 'localhost',
'port' : '3306',
'database': 'my_node_db'
}
};

Related

Sequelize Error: Error: Dialect needs to be explicitly supplied as of v4.0.0

While prepping an application for deployment, an error:
Error: Dialect needs to be explicitly supplied as of v4.0.0
started popping up whenever i run npm run develop. i'm using a .env file for my environmental variables. The connection.js code is :
const Sequelize = require('sequelize');
require('dotenv').config({path: '../.env'});
let sequelize;
if (process.env.JAWSDB_URL) {
sequelize = new Sequelize(process.env.JAWSDB_URL);
} else {
sequelize = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
dialect: 'mysql',
host: 'localhost',
port: 3306
}
);
}
module.exports = sequelize;
The server.js file is:
const path = require('path');
const express = require("express");
const cors = require("cors");
const routes = require("./routes");
const sequelize = require("./config/connection");
const app = express();
const PORT = process.env.PORT || 8080;
var corsOptions = {
//for online use
// origin: "https://operations-limit-database.herokuapp.com"
//first trying this without credentials to see how it works
// credentials: true,
//for local use
origin: "http://localhost:3000"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// turn on routes
app.use(routes);
// simple route
//the below two are for deployed builds
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../client/build')));
}
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../client/build/index.html'));
});
//this is for local build only
// app.get("/", (req, res) => {
// res.json({ message: "Welcome to Homeschool's Op Limit Database" });
// });
// turn on connection to db and server
//{ force: false } to drop tables and recreate
sequelize.sync().then(() => {
app.listen(PORT, () => console.log(`Server is running on port ${PORT}.`));
});
And the .env file looks like below:
DB_NAME= 'xxxx'
DB_USER= 'yyyy'
DB_PASSWORD= 'zzzz'
DB_SECRET='aaaa'
Not sure what I.m missing, it was up and running over the weekend and then just stopped. Anything i can try would be appreciated.
So far i've tried reordering the .env, changing databases, and rebuilding the app, all to no avail.
This happens when you dont pass dialect to sequelize properly, make sure that you are passing the string and the environment variables are getting passed, usually it is the case.
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mysql',
dialectOptions: {
// Your mysql2 options here
}
})
Documentation

pool.querty is not a function. Trying to connect google-cloud mysql instance from local machine

When trying to connect to the mysql instance on gcloud using nodejs and express. I'm getting the error "pool.query" is not a function. Bear with me since this the first time using gcloud and nodejs, i may be missing something obvious. I have already authorized my local ip,
This is my config
const config = {
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'
socketPath: '/cloudsql/'+ process.env.INSTANCE_UNIX_SOCKET, // e.g. '/cloudsql/project:region:instance'
connectionLimit: 5,
connectTimeout: 10000, // 10 seconds
waitForConnections: true, // Default: true
queueLimit: 0, // Default: 0
};
module.exports = config;
This is my pool creation method
//dotenv
require('dotenv').config();
// import mysql2
const mysql = require('mysql2/promise');
// get config
const config = require("./config");
// Connect to database
// createUnixSocketPool initializes a Unix socket connection pool for
// a Cloud SQL instance of MySQL.
async function createUnixSocketPool() {
return mysql.createPool({...config,});
};
module.exports = {createUnixSocketPool};
And lastly my code for connecting
const path = require('path');
const express = require('express');
const { createUnixSocketPool } = require("./db");
const app = express();
// create mysql pool
const pool = createUnixSocketPool();
app.get('/',async (req,res) => {
console.log(await pool.query("show tables;"));
res.send("test");
});
// Listening
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log('App is listening on port '+ PORT));
For some reason this says that pool.query doesn't exist? I'm very new to node.js and javascript in general, what am i missing?

Express taking forever to load mySQL query?

I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.

Woking with node.js and mysql

// So I am using mysql with node and express framework and the first time I created a test example everything worked fine. But then I tried to create a second project and now the routing seems to not being read.
And the respond back I get is:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server started on port 8000
mysql connected...
//I am also supposed to get the result back:
OkPackege{...
...
...
...
}
//But I am not getting it. Any Ideas...? thanks.
The scrips that i have are as follow:
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'LEoking1987'
//database : 'nodesql'
});
db.connect((err) => {
if(err){
throw err;
}
console.log('mysql connected...');
});
const app = express();
// Creates satabase if it does not exist yet.
app.get('/createdb',(req,res) => {
let sql = 'CREATE DATABASE nodesql';
db.query(sql, (err, result) => {
if(err) throw err;
console.log(result);
res.send('Database created...');
});
});
app.listen('8000',()=>{
console.log('Server started on port 8000');
});
add debug: true in your mysql connection params like
mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'LEoking1987'
database: 'nodesql'
debug: true,
})

NodeJS - Connecting to a local Mysql Database

I am trying to create a mysql database connection for my node app and ran sequelize.authenticate().then(function(errors) { console.log(errors) }); to test if the connection worked. The response that is logged to my console is Executing (default): SELECT 1+1 AS result undefined The undefined portion makes me think that the connection either didn't work or that there isn't any database found. I can't seem to figure that out. I thought by creating a database through Sequel Pro and connecting to localhost via the Socket, I can use the same credentials for connecting with my Node app. Do I need to create a file within my app for the database and not use the Sequel Pro database?
Controller file (where the connection is created):
var Sequelize = require('sequelize');
var sequelize = new Sequelize('synotate', 'root', '', {
host:'localhost',
port:'3306',
dialect: 'mysql'
});
sequelize.authenticate().then(function(errors) { console.log(errors) });
var db = {}
db.Annotation = sequelize.import(__dirname + "/ann-model");
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
ann-model.js (where my table is being defined):
module.exports = function(sequelize, DataTypes) {
var Ann = sequelize.define('annotations', {
ann_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
ann_date: DataTypes.DATE,
}, {
freezeTableName: true
});
return Ann;
}
Try this one, Executing (default): SELECT 1+1 AS result means that everything okay
sequelize
.authenticate()
.then(function(err) {
if (!!err) {
console.log('Unable to connect to the database:', err)
} else {
console.log('Connection has been established successfully.')
}
});
But i didn't know where you get undefined