0

I tried searching for the answer, closest question i got was Sequelize CLI Not Finding Env Variables. I compared my code and it was exactly like the answer provided, then just to debug i edited config file to set values manually instead of reading from .env but sequelize-cli still gives same error

ERROR: SequelizeDatabaseError: Access denied for user ''@'localhost' to database 'dbname'
    at Query.formatError (/home/name/Documents/nodejs/project/db/node_modules/sequelize/lib/dialects/mysql/query.js:265:16)
    at Query.run (/home/name/Documents/nodejs/project/db/node_modules/sequelize/lib/dialects/mysql/query.js:77:18)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async /home/name/Documents/nodejs/project/db/node_modules/sequelize/lib/sequelize.js:619:16
    at async Object.exports.handler (/home/name/Documents/nodejs/project/db/node_modules/sequelize-cli/lib/commands/database.js:49:7)

Here is my config.js file

require("dotenv").config();
console.log(process.env.NODE_ENV, "it is being loaded correctly");
const config = {
  development: {
    username: "mysql",
    password: "",
    database: "dbname",
    host: "localhost",
    port: "3306",
    dialect: "mysql",
    dialectOptions: {
      charset: "utf8mb4",
    },
  },
  production: {
    username: "mysql",
    password: "",
    database: "dbname",
    host: "localhost",
    port: "3306",
    dialect: "mysql",
    dialect: "mysql",
    dialectOptions: {
      charset: "utf8mb4",
    },
  },
};
console.log(config);
module.exports = config;

and lastly here is .sequelizerc file

const path = require('path');

module.exports = {
  'config': path.resolve('config', 'config.js')
}

Funny thing is this project was working perfectly on my last computer (macos) and my server(ubuntu) but i am facing this issue with ubuntu desktop. AFAIK it should not be an operating system problem.

here is models/index.js

"use strict";
require("dotenv").config();
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV;
console.log(env);
const config = require(__dirname + "/../config/config")[env];
const db = {};
console.log("config check", config);
let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(
    config.database,
    config.username,
    config.password,
    config
  );
}

fs.readdirSync(__dirname)
  .filter((file) => {
    return (
      file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
    );
  })
  .forEach((file) => {
    const model = require(path.join(__dirname, file))(
      sequelize,
      Sequelize.DataTypes
    );
    db[model.name] = model;
  });

Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

UPDATE 1:

I have tried to connect to database programmatically and get same error.

  original: Error: Access denied for user ''@'localhost' to database 'dbname'
      at Packet.asError (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/packets/packet.js:712:17)
      at ClientHandshake.execute (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/commands/command.js:28:26)
      at Connection.handlePacket (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/connection.js:425:32)
      at PacketParser.onPacket (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/connection.js:75:12)
      at PacketParser.executeStart (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/packet_parser.js:75:16)
      at Socket.<anonymous> (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/connection.js:82:25)
      at Socket.emit (events.js:400:28)
      at addChunk (internal/streams/readable.js:290:12)
      at readableAddChunk (internal/streams/readable.js:265:9)
      at Socket.Readable.push (internal/streams/readable.js:204:10) {
    code: 'ER_DBACCESS_DENIED_ERROR',
    errno: 1044,
    sqlState: '42000',
    sqlMessage: "Access denied for user ''@'localhost' to database 'dbname'"
Faizan Ul Haq
  • 454
  • 2
  • 7
  • 23
  • Have you included the package mysql2? This could be something else than what you think it is. Have you spelled userName correctly? Should it be "user" instead of "userName", maybe? It turns out as undefined/null in the error message (''@'localhost'), seems like it can't find the username. If you show the rest of your code, like the server/db.js it's easier to help. – anatolhiman Aug 14 '21 at 01:16
  • @anatolhiman Yes mysql2 is installed and included in dependencies as well 2. https://sequelize.org/master/manual/migrations.html official docs mention username in all config files 3. i am adding models/index.js although it is not used when running migrations. – Faizan Ul Haq Aug 14 '21 at 01:22
  • 1
    I wrote an answer below, with some ideas, check them out. – anatolhiman Aug 14 '21 at 01:30

1 Answers1

0

A couple of shots in the dark: If you try to connect with a blank password you need to set the password param to null in the connection configuration:

const sequelize = new Sequelize('database', 'username', null, {
  dialect: 'mysql'
})

Also, as mentioned in a comment, it looks like it can't set your username correctly, so it turns out as an empty string ('') in the error msg.

Maybe you have switched around username and password in the config object for Sequelize so the empty password becomes the username?

Will update this answer if I get better ideas when you show the connection code :)

EDIT 1:

Seems to be something fishy about your config in new Sequelize(process.env[config.use_env_variable], config);

It should have four parameters, here you have added the username and password into the config object. There should be three string params (or null) and one config object, four in total.

anatolhiman
  • 1,762
  • 2
  • 14
  • 23
  • tried with null no luck and Seems to be something fishy about your config in new Sequelize(process.env[config.use_env_variable], config); this code is autogenerated by sequelize-cli. – Faizan Ul Haq Aug 14 '21 at 01:36
  • `use_env_variable` doesn't seem to point to anything. If it's undefined then that's a problem. The config in the else clause could work if it wasn't for the fact that it will include username/password/db twice, both in the initial three parameters, and in the full config object. You have to remove user/pass/db from the config object and follow the convention Sequelize docs gives you. Try without the env. vars first, just hardcode the details like in mye example above and you'll see if it works or not. – anatolhiman Aug 14 '21 at 01:52