I have a postgresql database, schema and username:password.
If i run:
sequelize db:migrate --config=./dist/options/db.options.js --migrations-path=./dist/migrations --env=main
...then i catch error:
CREATE SCHEMA IF NOT EXISTS my_schema;
**ERROR**: permission denied for database my_database
My user cannot create schema, but this schema already exists.
How i can to disable this step on sequelize migrations options?
It is my sequelize config:
const CONNECTION: any = {
dialect: 'postgres',
host: process.env.PG_HOST,
port: parseInt(process.env.PG_PORT, 10),
database: process.env.PG_DATABASE,
username: process.env.PG_USERNAME,
password: process.env.PG_PASSWORD,
models: [
...
],
autoLoadModels: true,
sync: false,
migrationStorage: "sequelize",
migrationStorageTableName: genTableName('migrations'),
migrationStorageTableSchema: process.env.PG_SCHEMA,
logging: (...msg) => console.log(msg)
};
Google couldn't help me...
I found answer on my question. In my situation need to remove key migrationStorageTableSchema from config.
Related
Of the several ways of connecting to a database offered by TypeORM (json, env, yml...) I choose to set my Connection Options programatically within my project's code using a regular TypeScript file as follows:
// src/database/createConnection.ts
import { createConnection } from 'typeorm';
const connectionOptions = {
type: 'postgres',
host: POSTGRES_HOST_PROD,
port: Number(POSTGRES_PORT),
username: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: POSTGRES_DB,
entities: ['build/entities/**/typeDef.js'],
migrations: ['build/database/migrations/*.js'],
cli: {
migrationsDir: 'src/database/migrations/'
}
};
await createConnection(connectionOptions);
With the values fed by a regular .env file.
My problem is that when trying to create migration files through npx typeorm migration:generate -n initial I get an error as the command expects a specific orm configuration file to be present (ormconfig.env, ormconfig.json, etc).
As I already have my connection options set, this is not only redundant, it would also be processed instead of the configuration I have already set in the .ts file, and the only solution I see would be to rename the variables in my (non-typeorm-specific) .env file to match the specific TypeORM variable names, which I'd prefer not to do.
TL:DR Is there a way of generating TypeORM migrations without creating a dedicated orm config file?
Oh, turns out TypeORM already has a built-in option for this which does not require an extra ormconfig file, one can just add the property migrationsRun: true to the Connection Options (making sure synchronize is set to false).
For instance:
import { createConnection } from 'typeorm';
const connectionOptions = {
type: 'postgres',
host: POSTGRES_HOST_PROD,
port: Number(POSTGRES_PORT),
username: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: POSTGRES_DB,
migrationsRun: true,
entities: ['build/entities/**/typeDef.js'],
migrations: ['build/database/migrations/*.js'],
cli: {
migrationsDir: 'src/database/migrations/'
}
};
await createConnection(connectionOptions);
I am trying to use Sequelize (v 5.21.13) to connect to my SQL Server database in my Expressjs app.
dbconfig.js
var dbConfig = {
server: process.env.DB_HOST,
authentication: {
type: 'default',
options: {
userName: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD
}
},
options: {
database: process.env.DB_NAME
}
};
module.exports = dbConfig;
index.js:
const dbConfig = require('./dbConfig');
const Sequelize = require('sequelize');
const connection = new Sequelize(
dbConfig.options.database,
dbConfig.authentication.options.userName,
dbConfig.authentication.options.password,
{
host: dbConfig.server,
dialect: 'mssql',
}
);
connection.sync().then(() => {
console.log('Connected!');
}).catch((e) => {
console.log('Error:\n', e);
});
Now the thing is that each time I run the server, I get this error
AccessDeniedError [SequelizeAccessDeniedError]: Login failed for user 'master'.
I have also tried adding additional properties to the new Sequelize() like the following with no luck.
dialectOptions: {
instanceName: 'instance',
options: {
encrypt: true,
trustServerCertificate: true,
requestTimeout: 30000
}
}
I even tried changing the password to a very simple one with no special characters, connection with Datagrip works after changing but not using Sequelize.
Everything on the dbconfig object is correct so I don't see what the issue might be.
Solved it. I was putting the the db instance id as the database name, I realized that the database name was different. Changed it and I'm now connected through Sequelize.
I've come across several posts for this question however, none of them seem to have an actual answer. Several ideas, yet none of them work.
After digging around both the Sequelize and Tedious packages and watching my config get passed down correctly, I'm at a loss.
I am trying to run migrations against a new database in MSSQL. I have no problem connecting to it with the same creds I'm using here so I know that's not the issue.
I have my config.js that is pulling env vars. With the exception of my custom console statements, this file was auto generated from sequelize and is correctly referenced in my sequelizerc
require('dotenv').config()
console.log('[+] Loading database config...')
if (process.env.NODE_ENV === 'production') {
console.log(`[+] Using database: ${process.env.PROD_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'development') {
console.log(`[+] Using database: ${process.env.DEV_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'test') {
console.log(`[+] Using database: ${process.env.TEST_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'local') {
console.log(`[+] Using database: ${process.env.LOCAL_DB_DATABASE}`)
} else {
console.log(`[-] CANNOT LOAD DATABASE FROM ENV: ${process.env.NODE_ENV}`)
process.exit()
}
module.exports = {
production: {
database: process.env.PROD_DB_DATABASE,
username: process.env.PROD_DB_USERNAME,
password: process.env.PROD_DB_PASSWORD,
host: process.env.PROD_DB_HOST,
port: process.env.PROD_DB_PORT,
dialect: process.env.PROD_DB_DIALECT,
storage: process.env.PROD_DB_STORAGE,
logging: false,
dialectOptions: {
instanceName: process.env.PROD_INSTANCE_NAME
},
pool: {
min: 5,
max: 1,
acquire: 6000,
idle: 6000
}
},
development: {
database: process.env.DEV_DB_DATABASE,
username: process.env.DEV_DB_USERNAME,
password: process.env.DEV_DB_PASSWORD,
host: process.env.DEV_DB_HOST,
port: process.env.DEV_DB_PORT,
dialect: process.env.DEV_DB_DIALECT,
storage: process.env.DEV_DB_STORAGE,
logging: console.log,
dialectOptions: {
instanceName: process.env.DEV_INSTANCE_NAME,
debug: true
},
pool: {
min: 5,
max: 1,
acquire: 6000,
idle: 6000
}
},
test: {
database: process.env.TEST_DB_DATABASE,
username: process.env.TEST_DB_USERNAME,
password: process.env.TEST_DB_PASSWORD,
host: process.env.TEST_DB_HOST,
port: process.env.TEST_DB_PORT,
dialect: process.env.TEST_DB_DIALECT,
storage: process.env.TEST_DB_STORAGE,
logging: false
},
local: {
database: process.env.LOCAL_DB_DATABASE,
username: process.env.LOCAL_DB_USERNAME,
password: process.env.LOCAL_DB_PASSWORD,
host: process.env.LOCAL_DB_HOST,
port: process.env.LOCAL_DB_PORT,
dialect: process.env.LOCAL_DB_DIALECT,
storage: process.env.LOCAL_DB_STORAGE,
logging: false
}
}
When i run my migration i get the error:
> node_modules/.bin/sequelize db:migrate
// ERROR: Login failed for user ''.
As mentioned above I dug through sequelize and tedious and my config is getting passed properly through both so i know it's not an env var issue or a NODE_ENV issue.
Anyone have any ideas here? I'm about to smash my face into my keyboard.
More for older versions:
If you are using sequelize#4, then it seems there is a hidden requirement that you must use tedious#<=5.
Which version of Sequelize are you using? If it's v5,
According to Sequelize v5's document:
Sequelize now works with tedious >= 6.0.0
However, in its package.json, it does not depend on tedious at all.
Since your program still runs, I guess you manually installed an older version of tedious before, which caused this strange problem.
Manually installing tedious of version>=6 should solve this problem, just like stated in its Getting started document page:
You'll also have to manually install the driver for your database of choice:
# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
const Sequelize = require('sequelize');
const sequelize = new Sequelize(
process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
dialect: 'mssql',
host: process.env.DB_HOST, //This is an IP
dialectOptions: {
options: {
instanceName: process.env.DB_INSTANCE_NAME,
trustServerCertificate: true
},
}
}
);
module.exports = {
sequelize,
Sequelize
};
Here is another solution, it's working for me.
I was getting the same error. The reason was due to explicitly mentioning the name of the DB in the sequelize config file and it did not exist. The reason could be different in your case but a quick look at SQL Server error logs will give you the reason for the failure.
Login failed for user 'user'. Reason: Failed to open the explicitly specified database 'dbo'. [CLIENT: XX.XX.XX.XX]
This happens even when the DB user specified in .env file is different. For the record "ankitj" is also the username of my system. I don't understand why this is happening.
Here's the error:
Unhandled rejection SequelizeConnectionError: password authentication failed for user "ankitj"
at connection.connect.err (/home/ankitj/Desktop/skillbee/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:128:24)
at Connection.connectingErrorHandler (/home/ankitj/Desktop/skillbee/node_modules/pg/lib/client.js:140:14)
at Connection.emit (events.js:160:13)
at Socket.<anonymous> (/home/ankitj/Desktop/skillbee/node_modules/pg/lib/connection.js:124:12)
at Socket.emit (events.js:160:13)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at Socket.Readable.push (_stream_readable.js:213:10)
at TCP.onread (net.js:599:20)
I'm assuming that you're getting this error using Sequelize with Node.js. I ran into the same error when I had the following:
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.DATABASE_USER,
process.env.DATABASE_PASSWORD,
{
dialect: 'postgres',
}
)
I was able to solve the issue by replacing it with a connection ur:
const sequelize = new Sequelize("postgres://postgres:postgres#localhost/gql", {
dialect: 'postgres'
// anything else you want to pass
})
where gql is the name of DATABASE in my .env file.
The user "ankitj" executes the command to run the Node script, so the script is trying to connect as that user. I first tried to solve this on the Postgres end by adding a user and granting permissions, but was unable to get that to work--I'd be interested in seeing that solution--but specifying a connection url worked for me.
I had the same issue when I was using the default password for the PostgreSQL. Try to change it from the command line as follows.
psql
\password
Then Enter a new password and update your .env files and that should Work.
Instead of using the process.env variables I put the actual names but wrapped in quotes (" ") and it's worked.
I have faced the same issue when I connect with NodeJS and Postgres SQL. I found a solution. We need to check db.config.js file(database config file) and index.js(where u called the const sequelize = new Sequelize(.......) properties name is matching or not.
// db.config.js
module.exports = {
user: '******',
host: 'localhost',
database: '***********',
password: '***',
port: 5432,
dialect: "postgres", // we need to implement
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
const Sequelize = require("sequelize");
const dbConfig = require("../config/db.config.js");
const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
host: dbConfig.host,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
},
})
Mentioned the above params line as (dbConfig.database, dbConfig.user, dbConfig.password) we need to check with db.config.js file
Note: please add dialect properties on the db.config.js file.
Now Problem is solved...Thanks
Console verbiage log
I also had the same error but I solved it by using template strings
const sequelize = new Sequelize(`${process.env.DB_NAME}`, `${process.env.DB_USER}`, `${process.env.DB_PASSWORD}`, {
host: process.env.DB_HOST,
dialect: 'postgres'
});
I've got a nodejs application that uses Sequelize as it's ORM. I've successfully got Sequelize connected to the database, but I haven't found anything in the documentation that explains how to set the application name. To clarify I'm looking to set a unique Application Name attribute for my app's connection string. That way when a DBA is looking at traffic they can pick out my application's queries from the rest.
Is this something that Sequelize can even do? Or does this need to be done at the tedious level? Failing that, is there a way in nodejs to specify connection string attributes?
Tedious allows setting the app name with the appName config param. You should be able to set this via the dialectOptions object when creating your Sequelize connection:
var conn = new Sequelize('my_db', 'my_user', 'my_pass', {
host: 'my_server',
dialect: 'mssql',
dialectOptions: {
appName: 'my_app_name'
}
});
For those finding this when they're looking for how to set the name for Postgres, you use application_name in the dialectOptions, eg
{
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
host: DB_HOST,
dialect: 'postgresql',
dialectOptions: {
application_name: 'My Node App',
},
},