0

Is it possible in PostgreSQL to grant all privileges on a schema of a database other than the one I'm currently connected to (and without using the \c command to switch first)?

For example, I'm connected as user postgres to the database postgres. Now I want to grant someuser all privileges on schema public:

GRANT ALL ON SCHEMA public TO someuser;

This executes successfully, but applies to schema public in the postgres database. What I really want is to apply the privileges on schema public of the other database. Something like this:

GRANT ALL ON SCHEMA <other>.public TO someuser;
2
  • 2
    No, you have to be connected to the database. Postgres does not do cross database references. Commented Sep 14, 2023 at 16:48
  • From the manual: When connecting to the database server, a client must specify the database name in its connection request. It is not possible to access more than one database per connection. See postgresql.org/docs/current/manage-ag-overview.html Commented Sep 14, 2023 at 17:27

1 Answer 1

1

It can be done through dblink extension, like this:

select dblink_exec('dbname=other_database user=remote_privileged_user password=password',
                   'grant all on schema public to someuser');

If your connected user has privileges in both databases, it's like this

select dblink_exec('dbname=other_database',
                   'grant all on schema public to someuser');

Which is better because, as pointed out in comments, could be a security breach for a password to be recorded in a transaction log.

Also the password could be retrieved from a file as shown in official docs for connection string construction since connecting and executing commands to remote PostgreSQL databases (self host or other hosts) has multiple uses.

Be sure that the dblink extension is installed in your local database with

select * from pg_extension;

If don't create it with

create extension dblink;

Official docs

Sign up to request clarification or add additional context in comments.

2 Comments

Your password could be written to the postgresql logfiles. Not sure if you want that. Using psql and just connecting to the correct target database, would be much cleaner.
@FrankHeikens, that's correct, added another example for that matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.