Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I connect to a database as another user?

Tags:

postgresql

Im currently creating an API for a school project and everything is working good. My setup is: Node v10, Postgres, Koa and so on...

I currently have this:

CREATE ROLE sa WITH LOGIN PASSWORD 'some-password.';
CREATE DATABASE master WITH OWNER sa;
\c master;

When the init script runs in the docker machine the output I get is this one:

CREATE ROLE
CREATE DATABASE
You are now connected to database "master" as user "postgres".

So I did change the file to something like this:

CREATE ROLE sa WITH LOGIN PASSWORD 'some-password.';
CREATE DATABASE master WITH OWNER sa;
CONNECT TO master AS main USER sa;

And I get a syntax error:

STATEMENT:  CONNECT TO master AS sa USER sa;
psql:/docker-entrypoint-initdb.d/init.sql:4: ERROR:  syntax error at or near "CONNECT"

I can't find anywhere in docs (or haven't look very good) how to connect from a .sql file to a database with an specific user.

How would I connect to 'master' with its owner, which is 'sa' from a .sql file?

like image 597
René Vidriales Trujillo Avatar asked May 04 '18 17:05

René Vidriales Trujillo


People also ask

How do I login as specific user in PostgreSQL?

There are two ways to login PostgreSQL: By running the "psql" command as a UNIX user which is also configured as PostgreSQL user using so-called IDENT/PEER authentication, e.g., " sudo -u postgres psql ". Via TCP/IP connection using PostgreSQL's own managed username/password (using so-called MD5 authentication).

What is command to switch to another database?

You can just enter use [dbName] to switch between databases without reentering your password.


1 Answers

You can do this via this command in psql:

\c db_name usr_name
like image 67
eng.mrgh Avatar answered Oct 06 '22 00:10

eng.mrgh