Can Sequelize be used to connect to a new database? - node.js

In designing a simple node.js project, I tried using Sequelize to connect to a mysql server using the following configuration parameters:
{ dbname: users
username: jimmy
password: users
params:
host: localhost
port: 3306
dialect: mysql }
though the 'users' database didn't exist yet.
I got a server error:
InternalServerError: {"name":"SequelizeConnectionError","parent":{"code":"ER_BAD_DB_ERROR","errno":1049,"sqlState":"42000","sqlMessage":"Unknown database 'users'"},"original":{"code":"ER_BAD_DB_ERROR","errno":1049,"sqlState":"42000","sqlMessage":"Unknown database 'users'"}}
But the Sequelize docs: Manual | Sequelize indicate that Sequelize can connect to a new database. Please, how can Sequelize be used to connect to a
new(non-existing) database?

You should read the documentation again carefully (because the wording is indeed confusing!).
New databases versus existing databases
If you are starting a project from scratch, and your database does not exist yet, Sequelize
can be used since the beginning in order to automate the creation of
every table in your database.
Also, if you want to use Sequelize to connect to a database that is
already filled with tables and data, that works as well! Sequelize has
got you covered in both cases.
It will connect only to an existing DB, it can help you by creating the tables if they do not exist yet but the DB has to be there in order for sequelize to connect with it.
Following this question, I wrote this PR to update the documentation to be less confusing. Hope it help!

Found a similar problem on SO, and an answer by osifo:
//create the sequelize instance omitting the database-name arg
const sequelize = new Sequelize("", "<db_user>", "<db_password>", {
dialect: "<dialect>"
});
return sequelize.query("CREATE DATABASE `<database_name>`;").then(data
=> {
// code to run after successful creation.
});
So, I was able to implement it in my own code:
var SQUser;
var sequlz;
async function connectDB() {
sequlz =
new Sequelize("", "jimmy", "users", {host: "localhost", port: 3306, dialect: "mysql"});
await sequlz.query("CREATE DATABASE users;");
await sequlz.query("Use users;");
SQUser = sequlz.define('Table',
{
// define table schema
});
return SQUser.sync();
};
//use sequelize to populate the table
async function create() {
const SQUser = await connectDB();
return SQUser.create(
//values
);
}

Related

not able to replace sqllite connection with mysql

I have a small nodejs app that I need to run on MySQL, but as a nodeJS newbie I am having a hard time getting my head around some of the concepts.
Today there is a method (database.js):
async function getLatestHeight() {
return (
await util.promisify(db.get.bind(db))(`SELECT MAX(height) FROM utxos`)
)["MAX(height)"];
}
Which is called like this in app.js:
let height = await db.getLatestHeight();
In database.js I have replaced the connection to sqllite with mysql:
const config = {
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
port: 3306,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DB,
};
dbConnection = mysql.createConnection(config);
dbConnection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
But how do I rewrite the getLatestHeight to send the same query to MySQL? The API seems to work so differently that I am not able to have MySQL return data the same way.
I tried:
return (
await util.promisify(dbConnection.query("SELECT MAX(height) FROM utxos"))
)["MAX(height)"];
But that returns a different type so I get an error TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type function. Received an instance of Query
This is probably a Node newbie issue, so happy for any hjelp. Hard to get my head out of OO and procedural coding styles...

Sync Sequelize Databases on Serverless app

I am using sequelize with MySQL on the Serverless offline app.
I am not sure how to sync all models on serverless start?
I am tried to do this
import Sequelize from "sequelize";
import mysql2 from 'mysql2';
const sequelize = new Sequelize('database', 'root', '', {
dialect: 'mysql',
dialectModule: mysql2,
host: 'localhost',
});
const getSequelize = () => {
sequelize.sync({ force: false })
.then(() => {
console.log(`Database & tables synchronised!`)
});
return sequelize;
}
export default getSequelize();
This approach syncs models that are imported into controller, so the only way in this case to sync all models is to include all models in every controller.
This does not look like a good example.
Do you have any idea?
Use sequelize.sync only for development purposes. Use sequelize migrations for production.
There must be some way to run console command db:migrate in your environment. When you push all the migration code use that command to update your database to the last version.

difference between Tedious and sequelize

i am new in Backend, i started learning node, i found the ORM sequelize and it's a good to handle with database but also find tedious . i did not understand the relation between them , can i use sequelize only in my project without tedious ? i found lot of people work with the two but i did not understqand why , i mean if we can use sequelize and interact with db why we have to use tedious at the same time ?
var Connection = require('tedious').Connection;
var config = {
server: "192.168.1.210",
options: {},
authentication: {
type: "default",
options: {
userName: "test",
password: "test",
}
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
if(err) {
console.log('Error: ', err)
}
// If no error, then good to go...
executeStatement();
});
const Sequelize = require('sequelize')
module.exports = new Sequelize('db', 'user', 'password', {
host: '',
dialect: 'mssql',
pool: {
max: 50,
min: 2,
idle: 10000
},
});
Ofcourse you can work with only sequelize. As I can see in the documentation.
Tedious is a pure-Javascript implementation of the TDS protocol, which is used to interact with instances of Microsoft's SQL Server. It is intended to be a fairly slim implementation of the protocol, with not too much additional functionality.
But sequelize will work will all db.
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

PostgreSQL error when trying to connect from node application

FATAL: no PostgreSQL user name specified in startup packet
Logs from my postgreSQL instance in my kubernetes cluster when trying to connect to it by doing the following:
const { POSTGRES_DATABASE, POSTGRES_USERNAME, POSTGRES_PASSWORD } = require('../config/config');
const Sequelize = require('sequelize');
const conn = new Sequelize(POSTGRES_DATABASE, {
username: POSTGRES_USERNAME,
password: POSTGRES_PASSWORD
});
config/config.js
const config = {
POSTGRES_DATABASE: 'postgres://postgres/postgresdb',
POSTGRES_USERNAME: 'postgresadmin',
POSTGRES_PASSWORD: 'admin123',
SERVER_PORT: '5000'
}
module.exports = config;
I am using SequelizeJS in nodeJS.
http://docs.sequelizejs.com/
It seems like the requests are connecting alright due to seeing the attempts in the postgreSQL logs. However something goes wrong and I wonder if it's wrong with permissions in postgres or the node service.
Appreciate some help or ideas
According to the Sequelize documentation that you linked, the args to creating a new connection are db, username, password. Your code did db, and then an object with username and password keys. This object is not correct and caused it to not find the username or password. Try this instead:
const { POSTGRES_DATABASE, POSTGRES_USERNAME, POSTGRES_PASSWORD } = require('../config/config');
const Sequelize = require('sequelize');
const conn = new Sequelize(POSTGRES_DATABASE, POSTGRES_USERNAME, POSTGRES_PASSWORD);
Sequelize does allow for an optional options object as the last argument, but the username and password are not expected to be in there.
This page of the documentation feels confusing to me.
http://docs.sequelizejs.com/manual/installation/usage.html
I believe what it says is that you either need to define everything in the object, or do the database, username, and password as separate arguments, but I don’t see it supporting database in the arguments and username / password in the object.
It seems like this should work as well:
const conn = new Sequelize({
database: POSTGRES_DATABASE,
username: POSTGRES_USERNAME,
password: POSTGRES_PASSWORD
});

Is it possible to "CREATE DATABASE ..." with pg-promise and PostgreSQL (9.5)?

Question is:
1) Can pg-promise be used to create a new database (schemas, et. al.)?
Using node package 'pg-promise' I can't seem to figure out if it's possible to create a new database. I can connect to an existing database and have no issue there. However, when I run without a database name I get an error:
This is what I am trying:
host = host || '127.0.0.1'
port = port || '5432'
const pgp = require('pg-promise')(pgpInitOptions)
// database connection details
const pgConnectionOptions = {
host: host,
port: port,
user: user,
password: pass
}
// database instance
const localDB = pgp(pgConnectionOptions)
let escapedDbName = dbName.replace(/\"/g, '""');
let sql = 'CREATE DATABASE "' + escapedDbName + '"';
localDB
.any(sql)
.then((results) => {
console.log('creation of database successful', results)
})
.catch((error) => {
console.error('creation of database failed', error)
})
Then, I get this error:
creation of database failed
Error: database "jeff" does not exist
"jeff" is my ubuntu login name.
First, you need to connect to an existing database, using an admin account which has the right to create new databases.
Then you can create new databases via a regular query...
const pgp = require('pg-promise')(/* initialization options */);
const db = pgp({
database: 'any-existing-db',
port: 5432,
user: 'postgres', // any admin user
password: 'admin-password'
});
await db.none('CREATE DATABASE $1:name', ['my_database']);
I am running such code locally, and it works fine.

Resources