Ошибка нет доступа к отношению

I tried to run simple SQL command:

select * from site_adzone;

and I got this error

ERROR: permission denied for relation site_adzone

What could be the problem here?

I tried also to do select for other tables and got same issue. I also tried to do this:

GRANT ALL PRIVILEGES ON DATABASE jerry to tom;

but I got this response from console

WARNING: no privileges were granted for «jerry»

Does anyone have any idea what can be wrong?

Dale K's user avatar

Dale K

25.3k15 gold badges42 silver badges71 bronze badges

asked Mar 20, 2013 at 10:00

Bob's user avatar

5

GRANT on the database is not what you need. Grant on the tables directly.

Granting privileges on the database mostly is used to grant or revoke connect privileges. This allows you to specify who may do stuff in the database if they have sufficient other permissions.

You want instead:

 GRANT ALL PRIVILEGES ON TABLE side_adzone TO jerry;

This will take care of this issue.

answered Mar 20, 2013 at 11:41

Chris Travers's user avatar

Chris TraversChris Travers

25.5k6 gold badges66 silver badges183 bronze badges

15

Posting Ron E answer for grant privileges on all tables as it might be useful to others.

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;

3

Connect to the right database first, then run:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;

BrDaHa's user avatar

BrDaHa

5,1485 gold badges32 silver badges48 bronze badges

answered Jan 1, 2017 at 20:00

user2757813's user avatar

user2757813user2757813

1,3291 gold badge8 silver badges3 bronze badges

3

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to jerry;

answered Jul 18, 2018 at 10:36

Meirza's user avatar

MeirzaMeirza

1,31810 silver badges15 bronze badges

1

1st and important step is connect to your db:

psql -d yourDBName

2 step, grant privileges

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO userName;

answered May 2, 2018 at 13:05

zond's user avatar

zondzond

1,4731 gold badge21 silver badges34 bronze badges

0

To grant permissions to all of the existing tables in the schema use:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA <schema> TO <role>

To specify default permissions that will be applied to future tables use:

ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> 
  GRANT <privileges> ON TABLES TO <role>;

e.g.

ALTER DEFAULT PRIVILEGES IN SCHEMA public 
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO admin;

If you use SERIAL or BIGSERIAL columns then you will probably want to do the same for SEQUENCES, or else your INSERT will fail (Postgres 10’s IDENTITY doesn’t suffer from that problem, and is recommended over the SERIAL types), i.e.

ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> GRANT ALL ON SEQUENCES TO <role>;

See also my answer to PostgreSQL Permissions for Web App for more details and a reusable script.

Ref:

GRANT

ALTER DEFAULT PRIVILEGES

answered Oct 9, 2017 at 18:31

isapir's user avatar

isapirisapir

21.4k13 gold badges115 silver badges116 bronze badges

2

This frequently happens when you create a table as user postgres and then try to access it as an ordinary user.
In this case it is best to log in as the postgres user and change the ownership of the table with the command:

alter table <TABLE> owner to <USER>;

salvador's user avatar

answered May 22, 2018 at 4:13

Bruce's user avatar

BruceBruce

4514 silver badges7 bronze badges

1

Make sure you log into psql as the owner of the tables.
to find out who own the tables use \dt

psql -h CONNECTION_STRING DBNAME -U OWNER_OF_THE_TABLES

then you can run the GRANTS

answered May 15, 2018 at 17:30

Brian McCall's user avatar

Brian McCallBrian McCall

1,8411 gold badge18 silver badges33 bronze badges

You should:

  1. Connect to the database using DBeaver and user as postgres
  2. On the left tab open your database
  3. Open Roles tab/dropdown
  4. Select your user
  5. On the right tab press ‘Permissions tab’
  6. Press your schema tab
  7. Press tables tab/dropdown
  8. Select all tables
  9. Select all required permissions checkboxes (or press Grant All)
  10. Press Save

aakaasaraamanna's user avatar

answered Mar 19, 2020 at 8:03

happydmitry's user avatar

happydmitryhappydmitry

1112 silver badges5 bronze badges

As you are looking for select permissions, I would suggest you to grant only select rather than all privileges. You can do this by:

GRANT SELECT ON <table> TO <role>;

answered Jan 8, 2020 at 15:33

Sergi Ramón's user avatar

For PostgreSQL. On bash terminal, run this:

psql db_name -c "GRANT ALL ON ALL TABLES IN SCHEMA public to db_user;"
psql db_name -c "GRANT ALL ON ALL SEQUENCES IN SCHEMA public to db_user;"
psql db_name -c "GRANT ALL ON ALL FUNCTIONS IN SCHEMA public to db_user;"

answered Nov 18, 2022 at 11:00

Mateus Alves de Oliveira's user avatar

I ran into this after switching a user to another user that also needed to have the same rights, I kept getting the error: «must be owner of relation xx»

fix was to simply give all rights from old user to new user:

postgres-# Grant <old user> to <new user>;

answered Aug 20, 2021 at 19:02

Jens Timmerman's user avatar

Jens TimmermanJens Timmerman

9,3261 gold badge42 silver badges48 bronze badges

Перейти к контенту

Как решить проблему? и как посмотреть лог puma? не могу найти нигде.

Ситуация такая: хочу сделать staging для проекта.

1) сделал деплой проекта на тестовый сервер (raspberry).

2) Восстановил базу (postgresql) из бэкапа с продакшн. Миграции не накатывал, их 1000 и очень много отваливается, приходится лезть и комментировать код, да и это не вариант.

Использую nginx, который смотрит на puma.
Запускаю

bundle exec puma -e production -b unix:///home/ivanov/www/ivanov/current/apps/www/tmp/sockets/puma.sock

и вываливается ошибка:

DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /home/ivanov/www/ivanov/releases/20170622115720/apps/www/config/environment.rb:9)
/home/ivanov/www/ivanov/releases/20170622115720/apps/www/config/initializers/bypass_ssl_verification_for_open_uri.rb:1: warning: already initialized constant OpenSSL::SSL::VERIFY_PEER
/home/ivanov/.rvm/gems/ruby-2.0.0-p247@parts-script-new-admin/gems/actionpack-3.2.13/lib/action_dispatch/http/mime_type.rb:102: warning: already initialized constant Mime::PDF
/home/ivanov/.rvm/gems/ruby-2.0.0-p247@parts-script-new-admin/gems/actionpack-3.2.13/lib/action_dispatch/http/mime_type.rb:102: warning: previous definition of PDF was here
! Unable to load application: ActiveRecord::StatementInvalid: PG::Error: ОШИБКА:  нет доступа к отношению site_configs
: SELECT  "site_configs".* FROM "site_configs"  LIMIT 1
/home/ivanov/.rvm/gems/ruby-2.0.0-p247@parts-script-new-admin/gems/activerecord-3.2.13/lib/active_record/connection_adapters/postgresql_adapter.rb:1161:in `async_exec': PG::Error: ОШИБКА:  нет доступа к отношению site_configs (ActiveRecord::StatementInvalid)
: SELECT  "site_configs".* FROM "site_configs"  LIMIT 1

В database.yml указан owners таблицы, и у него стоит GRANT ALL privileges ON DATABASE

в логах приложения:

Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    !
    информация о разделе

    user posted image Данный раздел предназначается исключительно для обсуждения вопросов использования языка запросов SQL. Обсуждение общих вопросов, связанных с тематикой баз данных — обсуждаем в разделе «Базы данных: общие вопросы». Убедительная просьба — соблюдать «Правила форума» и не пренебрегать «Правильным оформлением своих тем». Прежде, чем создавать тему, имеет смысл заглянуть в раздел «Базы данных: FAQ», возможно там уже есть ответ.

    >
    разные пользователи и доступ
    , не могу разобраться с ролями

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему

      


    Сообщ.
    #1

    ,
    13.10.15, 19:17

      Senior Member

      ****

      Рейтинг (т): 13

      Здравствуйте, Господа!
      Сразу предупрежу: в PostgreSQL я пока еще совсем новичок.
      Опишу проблему на примере, думаю так станет понятнее.

      ExpandedWrap disabled

        #psql

        postgres=# CREATE USER user1 WITH password ‘password’;

        postgres=# CREATE DATABASE db1;

        postgres=# GRANT ALL PRIVILEGES ON DATABASE db1 TO user1;

        postgres=# CREATE USER user2 WITH password ‘password’;

        postgres=# GRANT ALL PRIVILEGES ON DATABASE db1 TO user2;

        postgres=# q

        #psql -U user1 db1

        db1=# CREATE SEQUENCE user_ids;

        db1=# CREATE TABLE users (id INTEGER PRIMARY KEY DEFAULT NEXTVAL(‘user_ids’), login CHAR(64), password CHAR(64));

        db1=# INSERT INTO users (login, password) VALUES («u1», «p1»);

        db1=# q

        #psql -U user2 db1

        db1=# INSERT INTO users (login, password) VALUES («u2», «p2»);

        ОШИБКА:  нет доступа к отношению users

      Вот тут я в растерянности. Оба пользователя ALL PRIVILEGES для db1, но второй, т.е. не создатель таблицы, добавлять записи не может.
      Как это побороть?


      grgdvo



      Сообщ.
      #2

      ,
      14.10.15, 12:36

        Member

        **

        Рейтинг (т): 21

        Опция ALL PRIVILEGES для DATABASE подразумевает CREATE, CONNECT и кажется TEMP привилегии для базы данных.
        Так вот CREATE позволяет создавать ТОЛЬКО схемы в рамках базы данных.
        А для схемы вы не предоставили прав, соответственно получили ошибку доступа.


        HighMan



        Сообщ.
        #3

        ,
        14.10.15, 14:57

          Senior Member

          ****

          Рейтинг (т): 13

          Цитата grgdvo @ 14.10.15, 12:36

          Опция ALL PRIVILEGES для DATABASE подразумевает CREATE, CONNECT и кажется TEMP привилегии для базы данных.
          Так вот CREATE позволяет создавать ТОЛЬКО схемы в рамках базы данных.
          А для схемы вы не предоставили прав, соответственно получили ошибку доступа.

          Простите бестолкового, а как для схем предоставить привилегии?
          Если, возможно, напишите запрос на основе моего примера.
          Спасибо!

          Сообщение отредактировано: HighMan — 14.10.15, 14:58


          grgdvo



          Сообщ.
          #4

          ,
          14.10.15, 20:28

            Member

            **

            Рейтинг (т): 21

            Цитата HighMan @ 14.10.15, 14:57

            Простите бестолкового, а как для схем предоставить привилегии?

            В конце я неправ, забываешь как оно работает, когда не пользуешься.
            Для схемы (как объекта) тоже будет недостаточно прав :(

            Нужны команды конкретно на таблицу или ALL TABLES IN SCHEMA.
            И права нужно раздавать после создания таблицы, либо умудриться использовать ALTER DEFAULT PRIVILEGES.

            Для вашего примера скорее всего правильный порядок будет такой

            ExpandedWrap disabled

              ~ # psql -U postgres

              postgres=# CREATE USER user1 WITH password ‘password’;

              postgres=# CREATE USER user2 WITH password ‘password’;

              postgres=# CREATE DATABASE db1;

              postgres=# q

            db1 создается со схемой public по умолчанию, в которой пользователи уже могут создавать таблицы (и т.д.), поэтому user1 и user2 смогут создать свои объекты базы

            ExpandedWrap disabled

              ~ # psql -U user1 db1

              db1=# CREATE SEQUENCE user_ids;

              db1=# CREATE TABLE users (id INTEGER PRIMARY KEY DEFAULT NEXTVAL(‘user_ids’), login CHAR(64), password CHAR(64));

              db1=# INSERT INTO users (login, password) VALUES (‘u1’, ‘p1’);

              db1=# q

            теперь к user_ids и users доступ имеет только user1, ибо он владелец этих объектов.
            Назначаем права user2

            ExpandedWrap disabled

              ~ # psql -U postgres db1

              db1=# GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO user2;

              db1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO user2;

            Теперь user2 имеет все привилегии на таблицы и последовательнсти, которые УЖЕ БЫЛИ СОЗДАНЫ на данный момент в схеме.

            ExpandedWrap disabled

              ~ # psql -U user2 db1

              db1=# INSERT INTO users (login, password) VALUES (‘u2’, ‘p2’);

            Сообщение отредактировано: grgdvo — 14.10.15, 20:28


            HighMan



            Сообщ.
            #5

            ,
            14.10.15, 20:30

              Senior Member

              ****

              Рейтинг (т): 13

              Цитата grgdvo @ 14.10.15, 20:28

              Цитата HighMan @ 14.10.15, 14:57

              Простите бестолкового, а как для схем предоставить привилегии?

              В конце я неправ, забываешь как оно работает, когда не пользуешься.
              Для схемы (как объекта) тоже будет недостаточно прав :(

              Нужны команды конкретно на таблицу или ALL TABLES IN SCHEMA.
              И права нужно раздавать после создания таблицы, либо умудриться использовать ALTER DEFAULT PRIVILEGES.

              Для вашего примера скорее всего правильный порядок будет такой

              ExpandedWrap disabled

                ~ # psql -U postgres

                postgres=# CREATE USER user1 WITH password ‘password’;

                postgres=# CREATE USER user2 WITH password ‘password’;

                postgres=# CREATE DATABASE db1;

                postgres=# q

              db1 создается со схемой public по умолчанию, в которой пользователи уже могут создавать таблицы (и т.д.), поэтому user1 и user2 смогут создать свои объекты базы

              ExpandedWrap disabled

                ~ # psql -U user1 db1

                db1=# CREATE SEQUENCE user_ids;

                db1=# CREATE TABLE users (id INTEGER PRIMARY KEY DEFAULT NEXTVAL(‘user_ids’), login CHAR(64), password CHAR(64));

                db1=# INSERT INTO users (login, password) VALUES (‘u1’, ‘p1’);

                db1=# q

              теперь к user_ids и users доступ имеет только user1, ибо он владелец этих объектов.
              Назначаем права user2

              ExpandedWrap disabled

                ~ # psql -U postgres db1

                db1=# GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO user2;

                db1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO user2;

              Теперь user2 имеет все привилегии на таблицы и последовательнсти, которые УЖЕ БЫЛИ СОЗДАНЫ на данный момент в схеме.

              ExpandedWrap disabled

                ~ # psql -U user2 db1

                db1=# INSERT INTO users (login, password) VALUES (‘u2’, ‘p2’);

              Спасибо большое!
              Постараюсь завтра проверить!

              0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

              0 пользователей:

              • Предыдущая тема
              • Базы данных: SQL
              • Следующая тема

              Рейтинг@Mail.ru

              [ Script execution time: 0,0299 ]   [ 15 queries used ]   [ Generated: 31.01.23, 05:32 GMT ]  

              5 ответов

              Вот полное решение для PostgreSQL 9+, недавно обновленное.

              CREATE USER readonly  WITH ENCRYPTED PASSWORD 'readonly';
              GRANT USAGE ON SCHEMA public to readonly;
              ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
              
              -- repeat code below for each database:
              
              GRANT CONNECT ON DATABASE foo to readonly;
              c foo
              ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO readonly; --- this grants privileges on new tables generated in new database "foo"
              GRANT USAGE ON SCHEMA public to readonly; 
              GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly;
              GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
              

              Благодаря http://jamie.curle.io/creating-a-read-only-user-in-postgres/ для нескольких важных аспектов

              Если кто-то найдет более короткий код и, желательно, тот, который способен выполнить это для всех существующих баз данных, добавляет дополнительные преимущества.

              sorin
              22 нояб. 2012, в 12:23

              Поделиться

              Попробуйте добавить

              GRANT USAGE ON SCHEMA public to readonly;
              

              Вероятно, вы пропустили, что у вас должны быть разрешения на использование схем в этой схеме.

              sufleR
              21 нояб. 2012, в 18:36

              Поделиться

              Это сработало для меня:

              Проверьте текущую роль, в которую вы вошли, используя:
              SELECT CURRENT_USER, SESSION_USER;

              Примечание. Он должен совпадать с владельцем схемы.

              Схема | Имя | Тип | Владелец
              ——— + ——— + ——- + ———-

              Если владелец отличается, то предоставите все гранты текущей роли пользователя из роли администратора:

              GRANT ‘ROLE_OWNER’ для «ТЕКУЩЕГО РОЛИНАМА»;

              Затем попробуйте выполнить запрос, он даст результат, так как теперь он имеет доступ ко всем отношениям.

              Dhwani Shah
              25 июнь 2015, в 01:01

              Поделиться

              Вы должны выполнить следующий запрос:

              GRANT ALL ON TABLE mytable TO myuser;
              

              Или, если ваша ошибка в представлении, возможно, у таблицы нет разрешения, поэтому вы должны выполнить следующий запрос:

              GRANT ALL ON TABLE tbm_grupo TO myuser;
              

              yesy
              27 окт. 2015, в 18:09

              Поделиться

              убедитесь, что ваш пользователь имеет атрибуты своей роли. например:

              postgres=# du
                                           List of roles
               Role name |                   Attributes                   | Member of 
              -----------+------------------------------------------------+-----------
               flux      |                                                | {}
               postgres  | Superuser, Create role, Create DB, Replication | {}
              

              после выполнения следующей команды:

              postgres=# ALTER ROLE flux WITH Superuser;
              ALTER ROLE
              postgres=# du
                                           List of roles
               Role name |                   Attributes                   | Member of 
              -----------+------------------------------------------------+-----------
               flux      | Superuser                                      | {}
              postgres  | Superuser, Create role, Create DB, Replication | {}
              

              он исправил проблему.

              см. учебник для ролей и всего здесь: https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps—2

              PuN1sh3r
              16 июль 2015, в 07:31

              Поделиться

              Ещё вопросы

              • 1Как безопасно загружать / инициализировать одни и те же дочерние компоненты повторно
              • 0Обоснуйте навигацию внутри Twitter Bootstrap 3
              • 0jquery mobile — динамически добавлять переключатель
              • 1Найти индекс в строке где count (символы) в левой половине = count (символы) в правой половине?
              • 1Можно ли узнать, когда HTTP-ответ поступил клиенту на сервере? (ASP.NET)
              • 0Полноэкранный слайдер li 100% высоты не работает
              • 1Один оператор foreach, который перебирает две коллекции
              • 1Как рассчитать высоту и ширину повернутого изображения IIIF
              • 1Android: панель с центрированным изображением и кнопками справа
              • 1Как указать аргументы SSL JVM для встроенных сертификатов?
              • 1Как реализовать паттерн наблюдателя с CDI Events?
              • 0Скобки в селекторах jQuery
              • 0Как отбросить в моем коде значения «0,000 *», но все остальное пропустить?
              • 1Я пытаюсь нажать на каждую ссылку, используя селен и питон
              • 0Передача объекта в качестве аргумента в конструктор класса
              • 0импортировать локальные подмодули в Android-проект JNI
              • 1Проблема с draw () в MapView ItemizedOverlay
              • 0Как дать условие для псевдонима столбца в SQL
              • 0Вызов функции JJuery AJAX внутри каждого
              • 1Как бы я назвал намерение и поместил его в свой вектор?
              • 1Выполнение работоспособных пакетов в нескольких потоках
              • 0Диалог jquery показывает данные из предыдущего запроса ajax
              • 1Вставка тройных кавычек внутри тройных кавычек в файле cson
              • 0Неопределенная переменная при инициализации в операторе switch?
              • 1Копирование файла с устройства Android?
              • 1Формат даты и времени / Шаблоны в классе Java / SimpleDateFormat
              • 1Как увидеть полную ошибку сборки муравья, которая обрезана
              • 0После вычитания 4 соседних пикселей всегда дают ноль
              • 1Python Matplotlib Heatmap Colorbar из прозрачного
              • 1Запуск и остановка услуг
              • 0Доступ к личным членам класса
              • 1WPF Animation останавливается самопроизвольно
              • 0хотите получить имя файла и его путь, который был загружен с помощью плагина jquery
              • 0easyui «Объект не поддерживает это свойство или метод» в т. е. 9
              • 1Как добавить внешние файлы JS в проект Zurb Foundation 6.4 (веб-пакет)?
              • 0facebook: Как я могу получить ссылки на оригинальные фотографии из сообщений публичной группы
              • 0Сохранение контекста при использовании jQuery.on
              • 0nginx PHP переписывает профиль пользователя
              • 1Android ThreadSafeClientConnManager Тайм-ауты?
              • 1Как использовать служебное свойство в маршруте?
              • 0Добавить Telerik Grid Control на HTML-странице
              • 0Как отобразить сгенерированные результаты системой в виде графика
              • 1изо всех сил, чтобы проверить флягу-танец / фляга-безопасность / фляга-sqlalchemy / pytest
              • 0Безопасное встраивание строки в C-код (Безопасная строка, Безопасный символ *)
              • 0Почему не работает preg replce в iframe?
              • 1Использование модуля XLRD для поиска строки в импортированном Excel-файле
              • 1Группировка данных в сборе в одном формате в другой
              • 1d3.js интерполяция не работает
              • 0Как загрузить изображения тоже phpmyadmin ASP.Net
              • 0Как сделать так, чтобы Basic jQuery Slider останавливался после 1 цикла

              I kept getting this error when using flyway to deploy database changes. I do some manual setup first, such as creating the database, so flyway wouldn’t need those super-admin permissions.

              My Fix

              I had to ensure that the database user that flyway job used had ownership rights to the public schema, so that the flyway user could then assign the right to use the schema to other roles.

              Additional setup Details

              I am using AWS RDS (both regular and Aurora), and they don’t allow super users in the databases. RDS reserves super users for use by AWS, only, so that consumers are unable to break the replication stuff that is built in. However, there’s a catch-22 that you must be an owner in postgres to be able to modify it.

              My solution was to create a role that acts as the owner (‘owner role’), and then assign both my admin user and the flyway user to the owner role, and use ALTER scripts for each object to assign the object’s owner to the owner role.

              I missed the public schema, since that was auto-created when I created the database script manually. The public schema defaulted to my admin role rather than the shared owner role. So when the flyway user tried to assign public schema permissions to other roles, it didn’t have the authority to do that. An error was not thrown during flyway execution, however.

              I kept getting this error when using flyway to deploy database changes. I do some manual setup first, such as creating the database, so flyway wouldn’t need those super-admin permissions.

              My Fix

              I had to ensure that the database user that flyway job used had ownership rights to the public schema, so that the flyway user could then assign the right to use the schema to other roles.

              Additional setup Details

              I am using AWS RDS (both regular and Aurora), and they don’t allow super users in the databases. RDS reserves super users for use by AWS, only, so that consumers are unable to break the replication stuff that is built in. However, there’s a catch-22 that you must be an owner in postgres to be able to modify it.

              My solution was to create a role that acts as the owner (‘owner role’), and then assign both my admin user and the flyway user to the owner role, and use ALTER scripts for each object to assign the object’s owner to the owner role.

              I missed the public schema, since that was auto-created when I created the database script manually. The public schema defaulted to my admin role rather than the shared owner role. So when the flyway user tried to assign public schema permissions to other roles, it didn’t have the authority to do that. An error was not thrown during flyway execution, however.

                msm.ru

                Нравится ресурс?

                Помоги проекту!

                !
                информация о разделе

                user posted image Данный раздел предназначается исключительно для обсуждения вопросов использования языка запросов SQL. Обсуждение общих вопросов, связанных с тематикой баз данных — обсуждаем в разделе «Базы данных: общие вопросы». Убедительная просьба — соблюдать «Правила форума» и не пренебрегать «Правильным оформлением своих тем». Прежде, чем создавать тему, имеет смысл заглянуть в раздел «Базы данных: FAQ», возможно там уже есть ответ.

                >
                разные пользователи и доступ
                , не могу разобраться с ролями

                • Подписаться на тему
                • Сообщить другу
                • Скачать/распечатать тему

                  


                Сообщ.
                #1

                ,

                  Senior Member

                  ****

                  Рейтинг (т): 13

                  Здравствуйте, Господа!
                  Сразу предупрежу: в PostgreSQL я пока еще совсем новичок.
                  Опишу проблему на примере, думаю так станет понятнее.

                  ExpandedWrap disabled

                    #psql

                    postgres=# CREATE USER user1 WITH password ‘password’;

                    postgres=# CREATE DATABASE db1;

                    postgres=# GRANT ALL PRIVILEGES ON DATABASE db1 TO user1;

                    postgres=# CREATE USER user2 WITH password ‘password’;

                    postgres=# GRANT ALL PRIVILEGES ON DATABASE db1 TO user2;

                    postgres=# \q

                    #psql -U user1 db1

                    db1=# CREATE SEQUENCE user_ids;

                    db1=# CREATE TABLE users (id INTEGER PRIMARY KEY DEFAULT NEXTVAL(‘user_ids’), login CHAR(64), password CHAR(64));

                    db1=# INSERT INTO users (login, password) VALUES («u1», «p1»);

                    db1=# \q

                    #psql -U user2 db1

                    db1=# INSERT INTO users (login, password) VALUES («u2», «p2»);

                    ОШИБКА:  нет доступа к отношению users

                  Вот тут я в растерянности. Оба пользователя ALL PRIVILEGES для db1, но второй, т.е. не создатель таблицы, добавлять записи не может.
                  Как это побороть?


                  grgdvo



                  Сообщ.
                  #2

                  ,

                    Member

                    **

                    Рейтинг (т): 21

                    Опция ALL PRIVILEGES для DATABASE подразумевает CREATE, CONNECT и кажется TEMP привилегии для базы данных.
                    Так вот CREATE позволяет создавать ТОЛЬКО схемы в рамках базы данных.
                    А для схемы вы не предоставили прав, соответственно получили ошибку доступа.


                    HighMan



                    Сообщ.
                    #3

                    ,

                      Senior Member

                      ****

                      Рейтинг (т): 13

                      Цитата grgdvo @

                      Опция ALL PRIVILEGES для DATABASE подразумевает CREATE, CONNECT и кажется TEMP привилегии для базы данных.
                      Так вот CREATE позволяет создавать ТОЛЬКО схемы в рамках базы данных.
                      А для схемы вы не предоставили прав, соответственно получили ошибку доступа.

                      Простите бестолкового, а как для схем предоставить привилегии?
                      Если, возможно, напишите запрос на основе моего примера.
                      Спасибо!

                      Сообщение отредактировано: HighMan


                      grgdvo



                      Сообщ.
                      #4

                      ,

                        Member

                        **

                        Рейтинг (т): 21

                        Цитата HighMan @

                        Простите бестолкового, а как для схем предоставить привилегии?

                        В конце я неправ, забываешь как оно работает, когда не пользуешься.
                        Для схемы (как объекта) тоже будет недостаточно прав :(

                        Нужны команды конкретно на таблицу или ALL TABLES IN SCHEMA.
                        И права нужно раздавать после создания таблицы, либо умудриться использовать ALTER DEFAULT PRIVILEGES.

                        Для вашего примера скорее всего правильный порядок будет такой

                        ExpandedWrap disabled

                          ~ # psql -U postgres

                          postgres=# CREATE USER user1 WITH password ‘password’;

                          postgres=# CREATE USER user2 WITH password ‘password’;

                          postgres=# CREATE DATABASE db1;

                          postgres=# \q

                        db1 создается со схемой public по умолчанию, в которой пользователи уже могут создавать таблицы (и т.д.), поэтому user1 и user2 смогут создать свои объекты базы

                        ExpandedWrap disabled

                          ~ # psql -U user1 db1

                          db1=# CREATE SEQUENCE user_ids;

                          db1=# CREATE TABLE users (id INTEGER PRIMARY KEY DEFAULT NEXTVAL(‘user_ids’), login CHAR(64), password CHAR(64));

                          db1=# INSERT INTO users (login, password) VALUES (‘u1’, ‘p1’);

                          db1=# \q

                        теперь к user_ids и users доступ имеет только user1, ибо он владелец этих объектов.
                        Назначаем права user2

                        ExpandedWrap disabled

                          ~ # psql -U postgres db1

                          db1=# GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO user2;

                          db1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO user2;

                        Теперь user2 имеет все привилегии на таблицы и последовательнсти, которые УЖЕ БЫЛИ СОЗДАНЫ на данный момент в схеме.

                        ExpandedWrap disabled

                          ~ # psql -U user2 db1

                          db1=# INSERT INTO users (login, password) VALUES (‘u2’, ‘p2’);

                        Сообщение отредактировано: grgdvo


                        HighMan



                        Сообщ.
                        #5

                        ,

                          Senior Member

                          ****

                          Рейтинг (т): 13

                          Цитата grgdvo @

                          Цитата HighMan @

                          Простите бестолкового, а как для схем предоставить привилегии?

                          В конце я неправ, забываешь как оно работает, когда не пользуешься.
                          Для схемы (как объекта) тоже будет недостаточно прав :(

                          Нужны команды конкретно на таблицу или ALL TABLES IN SCHEMA.
                          И права нужно раздавать после создания таблицы, либо умудриться использовать ALTER DEFAULT PRIVILEGES.

                          Для вашего примера скорее всего правильный порядок будет такой

                          ExpandedWrap disabled

                            ~ # psql -U postgres

                            postgres=# CREATE USER user1 WITH password ‘password’;

                            postgres=# CREATE USER user2 WITH password ‘password’;

                            postgres=# CREATE DATABASE db1;

                            postgres=# \q

                          db1 создается со схемой public по умолчанию, в которой пользователи уже могут создавать таблицы (и т.д.), поэтому user1 и user2 смогут создать свои объекты базы

                          ExpandedWrap disabled

                            ~ # psql -U user1 db1

                            db1=# CREATE SEQUENCE user_ids;

                            db1=# CREATE TABLE users (id INTEGER PRIMARY KEY DEFAULT NEXTVAL(‘user_ids’), login CHAR(64), password CHAR(64));

                            db1=# INSERT INTO users (login, password) VALUES (‘u1’, ‘p1’);

                            db1=# \q

                          теперь к user_ids и users доступ имеет только user1, ибо он владелец этих объектов.
                          Назначаем права user2

                          ExpandedWrap disabled

                            ~ # psql -U postgres db1

                            db1=# GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO user2;

                            db1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO user2;

                          Теперь user2 имеет все привилегии на таблицы и последовательнсти, которые УЖЕ БЫЛИ СОЗДАНЫ на данный момент в схеме.

                          ExpandedWrap disabled

                            ~ # psql -U user2 db1

                            db1=# INSERT INTO users (login, password) VALUES (‘u2’, ‘p2’);

                          Спасибо большое!
                          Постараюсь завтра проверить!

                          0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                          0 пользователей:

                          • Предыдущая тема
                          • Базы данных: SQL
                          • Следующая тема

                          Рейтинг@Mail.ru

                          [ Script execution time: 0,0329 ]   [ 15 queries used ]   [ Generated: 22.09.23, 15:56 GMT ]  

                          qaa-engineer.ru > Вопросы и ответы > PG::Error: ОШИБКА: нет доступа к отношению «название таблицы» (ActiveRecord::StatementInvalid)

                          PG::Error: ОШИБКА: нет доступа к отношению «название таблицы» (ActiveRecord::StatementInvalid)

                          В мире программирования ошибки в коде — обычное явление, с которым сталкиваются даже самые опытные разработчики. Однако некоторые ошибки могут доставить особенное раздражение — например, когда при выполнении запроса к БД вылезает ошибка «PG::Error: ОШИБКА: нет доступа к отношению ‘название таблицы'» (ActiveRecord::StatementInvalid).

                          В этой статье мы рассмотрим почему возникает данная ошибка, как её исправить и какие меры необходимо принимать, чтобы избежать её в будущем.

                          Почему появляется ошибка «PG::Error: ОШИБКА: нет доступа к отношению ‘название таблицы'»?

                          Данная ошибка возникает, когда в коде приложения происходит обращение к таблице в базе данных, к которой нет прав доступа у текущего пользователя. Это могут быть права на чтение (SELECT), изменение (UPDATE) и удаление (DELETE) данных.

                          Самым распространенным случаем возникновения этой ошибки является попытка выполнения запроса к таблице без указания схемы, если она отличается от схемы по умолчанию. При этом БД пытается найти таблицу в схеме по умолчанию, а не находит её там, что и приводит к ошибке.

                          Как исправить ошибку «PG::Error: ОШИБКА: нет доступа к отношению ‘название таблицы'»?

                          1. Проверьте права доступа к таблице

                          Первым шагом в исправлении ошибки нужно проверить, имеете ли вы права доступа к таблице. Для этого можно воспользоваться инструментами управления БД, например, консолью psql.

                          Для начала необходимо подключиться к БД:

                          psql -h HOST -p PORT -U USERNAME DATABASE
                          

                          Затем можно выполнить запрос на вывод списка таблиц в БД с указанием схемы:

                          SELECT table_name FROM information_schema.tables WHERE table_schema = 'SCHEMA_NAME';
                          

                          Если таблица отсутствует в списке, значит, вероятнее всего, у вас нет прав на её просмотр.

                          2. Уточните схему таблицы

                          Если таблица, к которой вы обращаетесь, находится в другой схеме, в которой у вас нет прав на просмотр, то нужно уточнить правильное имя таблицы с указанием схемы. Например, если таблица находится в схеме my_schema, то запрос к ней можно сформулировать следующим образом:

                          SELECT * FROM my_schema.my_table;
                          

                          3. Замените название таблицы на корректное

                          Если вы уверены в правах доступа к таблице и правильности имени схемы, то проверьте, правильно ли вы указали имя таблицы. Самый простой способ — скопировать имя таблицы из консоли psql, чтобы быть уверенным в правильности написания.

                          4. Проверьте подключение к БД

                          Если все вышеперечисленные пункты не помогли исправить ошибку, стоит проверить правильность подключения к БД. Возможно, вы используете не правильные учетные данные для подключения к БД.

                          Как избежать ошибки «PG::Error: ОШИБКА: нет доступа к отношению ‘название таблицы’»?

                          1. Задавайте явно схему при обращении к таблице

                          Чтобы избежать ошибок при обращении к таблицам в БД, необходимо явно указывать схему, в которой находится необходимая таблица. Например:

                          SELECT * FROM my_schema.my_table;
                          

                          2. Используйте ORM

                          Для более удобного доступа к БД можно воспользоваться ORM-библиотеками, такими как ActiveRecord для Ruby on Rails или Hibernate для Java. ORM позволяет работать с БД через модели данных и предоставляет удобный API для выполнения запросов.

                          3. Проверяйте права доступа пользователя к БД

                          Перед началом работы с БД необходимо проверить, на какие таблицы и запросы у пользователя имеются права. Если нужно дать дополнительные права, то они должны быть выданы администратором БД.

                          4. Не оставляйте доступ к БД по умолчанию

                          Для увеличения безопасности БД необходимо удалять лишние пользователей, которые не имеют доступа к БД, и не оставлять доступ к БД по умолчанию.

                          Вывод

                          Ошибка «PG::Error: ОШИБКА: нет доступа к отношению ‘название таблицы'» может доставить много хлопот при выполнении запросов к БД. Однако с её исправлением вам помогут наши рекомендации. Не забывайте также, что профилактические меры для избежания данной ошибки также очень важны.

                          I am trying to query a database table in postgresql, but every time I run the below query it gives me the INSUFFICIENT PRIVILEGE error. What possibly could be the reason for such permission denied error. Also, I am using pgadmin tool in windows to connect the database which is in Linux environment. Below is the query I am running

                          > > SELECT appid,hash 
                          >       FROM app
                          >       WHERE appid=1;
                          

                          While running the same query I am getting the below Error

                          ERROR:  permission denied for relation app
                          
                          ********** Error **********
                          
                          ERROR: permission denied for relation app
                          SQL state: 42501
                          

                          asked Aug 12, 2013 at 17:53

                          AKIWEB's user avatar

                          AKIWEBAKIWEB

                          18.8k66 gold badges179 silver badges293 bronze badges

                          1

                          The user running the query will need permissions to that table. You can grant them to that user with the GRANT statement. The below is an example that grants to PUBLIC

                          GRANT SELECT ON tablename TO PUBLIC;
                          

                          Also I have seen SELinux cause isses and places such as here mention it. I am not exactly sure of the command to turn SELinux off but you can see if it is running by using

                          selinuxenabled && echo enabled || echo disabled
                          

                          answered Aug 12, 2013 at 17:58

                          sealz's user avatar

                          sealzsealz

                          5,3485 gold badges40 silver badges70 bronze badges

                          3

                          It simply means that you have no permission to access app table. Request your root or database administrator to grant you the permission to access app table. if your are the root or have granting privilege you can use grant command to grant your self permission to use all sql statements on table or database
                          For Example:

                                         grant all privileges on database money to cashier;
                          

                          before that you have to login as root or user that have granting privileges

                          for more details on this command refer to
                          http://www.postgresql.org/docs/8.1/static/sql-grant.html

                          answered Aug 12, 2013 at 18:12

                          Himanshu Pandey's user avatar

                          If it’s DB2 then go to command console of DB2, select your respective Database and select Authorities option by right click on the Database then add your respective DB2 user and grant required access.

                          answered Aug 1, 2016 at 12:20

                          user6663265's user avatar

                          You need to make sure that the user with which you are connecting with also has the «USAGE» access on the schema you are trying to access with the user. I have recently faced an error where I got the dump restored into a database and then had some users to whom I was only supposed to provide the read-only access. I have followed the following steps —

                          CREATE ROLE myapp_readonly;
                          GRANT CONNECT ON DATABASE {database} TO myapp_readonly;
                          GRANT USAGE ON SCHEMA {schema} TO myapp_readonly;
                          GRANT SELECT ON TABLE {schema}.{table_name} TO myapp_readonly;
                          GRANT myapp_readonly TO {usre};
                          

                          After performing these steps when I tried to access the table, had received the following error —

                          SQL Error [42501]: ERROR: permission denied for schema {schema}
                          

                          In my case, my users were available already and the schemas and the database were restored recently. After I have provided the «USAGE» access to the schema to the user the error was resolved.

                          answered Jul 7, 2020 at 23:38

                          Shaounak Nasikkar's user avatar

                          I am very new to postgres so please my apologies in advance if I sound naive. I am still trying to learn. I am trying to create a readonly role and then create a role and assign readonly role to the user. I logged in as postgres user

                          CREATE ROLE readonly;
                          GRANT CONNECT ON DATABASE test_db TO readonly;
                          
                          GRANT USAGE ON SCHEMA public TO readonly;
                          GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
                          ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
                          
                          CREATE USER readonlyuser WITH PASSWORD 'read123';
                          grant readonly  to readonlyuser;
                          

                          Now I can login as user readonlyuser but I can’t read data from any tables. I get error SQL Error [42501]: ERROR: permission denied for table.

                          Any help would be appreciated.

                          a_horse_with_no_name's user avatar

                          asked Jan 14, 2021 at 6:39

                          SQLSERVERDAWG's user avatar

                          The ALTER DEFAULT PRIVILEGES statement you ran will only affect tables created by postgres. If a different user creator creates the tables, you need

                          ALTER DEFAULT PRIVILEGES FOR ROLE creator IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
                          

                          answered Jan 14, 2021 at 7:37

                          Laurenz Albe's user avatar

                          Laurenz AlbeLaurenz Albe

                          42.8k4 gold badges36 silver badges60 bronze badges

                             Login : sudo -u postgres psql
                              Select db : c yourDbName
                              View all table dt;
                              grant youUserName to postgres; 
                              (permission related error then use this command)
                              
                              GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO {serverName};
                          

                          answered Jul 6, 2022 at 12:37

                          Ajay Prajapati's user avatar

                          For me, the problem was that I was using the free tier of ElephantSql.com (a great website BTW), and I used (way) more than the allocated 20 MB free quota.

                          I was able to make a select query, but an insert one failed with the error permission denied for table.

                          answered Jan 25 at 1:13

                          A-S's user avatar

                          A last-minute website error is always frustrating.

                          PostgreSQL database queries often end up in errors with code 42501.

                          This PostgreSQL error 42501 usually occurs when an underprivileged user queries a database. This can be tricky to troubleshoot.

                          That’s why we often get requests to fix PostgreSQL errors as a part of our Server Management Services.

                          Today, let’s have a look into the error 42501 and see how our Support Engineers fix it for our customers.

                          When does PostgreSQL error 42501 occur?

                          Before moving on to the error 42501, let’s first see more about PostgreSQL.

                          PostgreSQL is one of the versatile database management systems. It comes handy for developers to build applications, server administrators to protect data and so on. In other words, PostgreSQL is a highly extensible database system.

                          The error code 42501 denotes insufficient privilege for the database user. But, there can be many reasons that lead to this error.

                          1. Insufficient privilege for the user

                          Usually, the 42501 error occurs when a PostgreSQL user with insufficient privileges makes a query on a database.

                          This indicates that the database user executed an operation, for which the user has no rights.

                          For database management, the user needs enough rights over the database.

                          When one of our customers was trying to query a database table in a PostgreSQL tool like pgAdmin, it ended up in error 42501.

                          The error message was

                          PostgreSQL error 42501 after database query by a user with insufficient privilege.

                          By default, in the PostgreSQL database, the user restoring the database will have the database ownership. For instance, when restoring a database as the root user, all objects will be under root ownership. And if another user is running any query on this database, it shows the 42501 error.

                          2. SELinux setting

                          Sometimes, the SELinux setting in the server can also cause an insufficient privilege error.

                          SELinux is a security architecture that is a part of Linux kernel. In SELinux, access and transition rights of a user, application, process, and file are all defined. Thus, if SELinux is enabled it affects the user privileges then the database query can end up in a 42501 error.

                          Fix for 42501 permission denied error

                          When our customers approach us with this error, our Support Team first checks the reasons that cause this error. The major reasons are insufficient user privilege and SELinux settings.

                          Now, let’s see how our Support Team fixes this error.

                          1.Granting Privilege to a user

                          First and foremost, when a customer approaches us with a 42501 error, we check the database user privileges already given.

                          If the user lacks enough permission, then we change it accordingly.

                          Mostly, the user does not have privileges over the requested tables.

                          In this case, we give privileges to the user over the requested tables using the command.

                          GRANT SELECT ON table_name TO PUBLIC;

                          This command gives all privileges over the table to the public, hence anyone can use it.

                          But, some customers prefer giving privileges only to a few users.

                          In this case, to give table access only to certain users, we use the command.

                          GRANT SELECT ON table_name TO user_name;

                          After giving privileges to the user, our Support Team executes the query once again. This ensures that the error is fixed.

                          Similarly, if the root user restored the dump file, this can cause insufficient privilege for the database user.

                          That is, if the root user restores the database using pg_dump --no-owner then the root user who restored the database will have all privileges.

                          So, we always restore the database using the login of the desired user. Then, this user will have all privileges over the database.

                          2. Disabling SELinux

                          In some cases, the user has enough privilege over the database and still the database query show 42501 error. Here, the SELinux can be the reason causing the error.

                          After considering other security settings, our Support Team disables this feature using the command.

                          selinuxenabled && echo enabled || echo disabled

                          [Still having trouble in fixing PostgreSQL errors? – We will fix it for you.]

                          Conclusion

                          In short, the PostgreSQL error 42501 occurs mainly due to insufficient privileges for database user for running query. We saw how our Support Engineers fixed this error for our customers.

                          PREVENT YOUR SERVER FROM CRASHING!

                          Never again lose customers to poor server speed! Let us help you.

                          Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

                          GET STARTED

                          var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

                          Перейти к контенту

                          The first comment nailed the most likely reason this is happening. Quoting the release announcement:

                          PostgreSQL 15 also revokes the CREATE permission from all users except a database owner from the public (or default) schema.

                          The reason your fix didn’t work is that all actions you took on database postgres in regards to user admin‘s privileges on schema public concern only that schema within the database postgres. Schema public on database postgres is not the same schema public as the one on newly created mydb.

                          Also, this:

                          GRANT ALL ON DATABASE mydb TO admin;
                          

                          grants privileges on the database itself, not things within the database. admin can now drop the database, for example, still without being able to create tables in schema public. My guess is that you wanted to make admin also the owner of mydb, in which case you need to add

                          ALTER DATABASE mydb OWNER TO admin;
                          

                          Or you need to repeat your GRANT USAGE, CREATE ON SCHEMA public TO admin; on mydb.

                          Here’s some more documentation on secure schema usage patterns the PostgreSQL 15 change was based on.

                          I kept getting this error when using flyway to deploy database changes. I do some manual setup first, such as creating the database, so flyway wouldn’t need those super-admin permissions.

                          My Fix

                          I had to ensure that the database user that flyway job used had ownership rights to the public schema, so that the flyway user could then assign the right to use the schema to other roles.

                          Additional setup Details

                          I am using AWS RDS (both regular and Aurora), and they don’t allow super users in the databases. RDS reserves super users for use by AWS, only, so that consumers are unable to break the replication stuff that is built in. However, there’s a catch-22 that you must be an owner in postgres to be able to modify it.

                          My solution was to create a role that acts as the owner (‘owner role’), and then assign both my admin user and the flyway user to the owner role, and use ALTER scripts for each object to assign the object’s owner to the owner role.

                          I missed the public schema, since that was auto-created when I created the database script manually. The public schema defaulted to my admin role rather than the shared owner role. So when the flyway user tried to assign public schema permissions to other roles, it didn’t have the authority to do that. An error was not thrown during flyway execution, however.

                          I kept getting this error when using flyway to deploy database changes. I do some manual setup first, such as creating the database, so flyway wouldn’t need those super-admin permissions.

                          My Fix

                          I had to ensure that the database user that flyway job used had ownership rights to the public schema, so that the flyway user could then assign the right to use the schema to other roles.

                          Additional setup Details

                          I am using AWS RDS (both regular and Aurora), and they don’t allow super users in the databases. RDS reserves super users for use by AWS, only, so that consumers are unable to break the replication stuff that is built in. However, there’s a catch-22 that you must be an owner in postgres to be able to modify it.

                          My solution was to create a role that acts as the owner (‘owner role’), and then assign both my admin user and the flyway user to the owner role, and use ALTER scripts for each object to assign the object’s owner to the owner role.

                          I missed the public schema, since that was auto-created when I created the database script manually. The public schema defaulted to my admin role rather than the shared owner role. So when the flyway user tried to assign public schema permissions to other roles, it didn’t have the authority to do that. An error was not thrown during flyway execution, however.

                          In Postgres I created the following table inside a db called testing:

                          CREATE TABLE category_google_taxonomy (
                              category_id integer references category ON UPDATE CASCADE ON DELETE CASCADE,
                              google_taxonomy_id integer references google_taxonomy ON UPDATE CASCADE ON DELETE     CASCADE
                          );
                          

                          When I try to populate the table:

                          INSERT INTO category_google_taxonomy (category_id, google_taxonomy_id) VALUES
                          (1,7),
                          (2,12);
                          

                          I get the following error:

                          ERROR:  permission denied for schema public
                          LINE 1: SELECT 1 FROM ONLY "public"."category" x WHERE "category_id"...
                                                 ^
                          QUERY:  SELECT 1 FROM ONLY "public"."category" x WHERE "category_id" OPERATOR(pg_catalog.=) $1 FOR SHARE OF x
                          

                          I read up a bit and eventually granted ALL PRIVILEGES out of exasperation, but it still doesn’t work:

                          testing=# GRANT ALL PRIVILEGES ON public.category TO testing;
                          GRANT
                          
                          testing=# dp category_google_taxonomy
                                                             Access privileges
                           Schema |           Name           | Type  |    Access privileges    | Column access privileges 
                          --------+--------------------------+-------+-------------------------+--------------------------
                           public | category_google_taxonomy | table | testing=arwdDxt/testing | 
                                                                     : super=arwdDxt/testing 
                          
                          
                          testing=# dp category
                                                     Access privileges
                           Schema |   Name   | Type  |   Access privileges    | Column access privileges 
                          --------+----------+-------+------------------------+--------------------------
                           public | category | table | testing=arwdDxt/super | category_id:
                                                                          :   testing=arwx/super
                          (1 row)
                          

                          On @Daniel’s suggestion I tried GRANT USAGE ON schema public TO super;, now when I run the INSERT command I get:

                          ERROR:  permission denied for relation category
                          CONTEXT:  SQL statement "SELECT 1 FROM ONLY "public"."category" x WHERE "category_id" OPERATOR(pg_catalog.=) $1 FOR SHARE OF x"
                          

                          Here is the relevant part of d:

                          public | category                               | table    | super
                          public | category_google_taxonomy               | table    | testing
                          

                          Я запускаю Postgres 10.4 и в настоящее время сбит с толку, поскольку не могу предоставить доступ к схеме другой роли.

                          Что я хочу сделать:

                          У меня одна роль с одной схемой, и я хочу получить доступ к схеме и ее таблицам из другой роли. Итак, я сделал как обычно (что работало с другими схемами):

                          grant usage on schema myschema to newuser;
                          
                          grant select on all tables in schema myschema to newuser;
                          

                          Оба этих оператора выполнялись как владелец схемы. При этом я не столкнулся с какими-либо ошибками.

                          Когда я вхожу в систему как новый пользователь и пытаюсь выбрать некоторые данные:

                          select * from myschema.table;
                          

                          Я получаю сообщение об ошибке:

                          SQL Error [42501]: ERROR: permission denied for schema myschema
                          

                          Я вижу, что у нового пользователя есть нужные привилегии в таблице «information_schema.role_table_grants»

                          Он также работал с другой ролью и другой схемой. Я невежественен.


                          Ответы
                          2

                          Это определенно работает, как указано в моем вопросе, проблема заключалась в том, что я не использовал владельца схемы.

                          Поэтому всегда убедитесь, что вы предоставляете доступ к схеме от роли владельца.

                          Шаг 1
                          GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA name_schema TO name_user;

                          Шаг 2
                          GRANT USAGE ON SCHEMA name_schema TO name_user;

                          Другие вопросы по теме

                          NataNov

                          0 / 0 / 0

                          Регистрация: 09.04.2021

                          Сообщений: 4

                          1

                          Создание пользователя с правами на таблицы в схеме

                          09.04.2021, 14:54. Показов 4679. Ответов 1

                          Метки нет (Все метки)



                          Добрый день!
                          Изучаю PostgreSql и не могу разобраться в следующем.
                          Хочу создать пользователя с правами выбора из всех таблиц некоторой схемы в БД.
                          Все дальнейшие действия делаю в утилите psql под суперпользователем postgres:

                          SQL
                          1
                          2
                          3
                          4
                          5
                          6
                          7
                          8
                          
                          CREATE DATABASE my_db;
                          c my_db
                          CREATE schema my_schema;
                          SET search_path TO my_schema,public;
                          CREATE TABLE my_table (f1 int2,f2 text);
                          INSERT INTO my_table VALUES (1,'aaa');
                          CREATE ROLE user1 login password 'user1';
                          GRANT SELECT ON ALL TABLES IN schema my_schema TO user1;

                          Затем подключаюсь к базе my_db под пользователем user1:

                          c my_db user1

                          До сих пор все шло прекрасно. Но дальше пытаюсь сделать select от имени пользователя user1:

                          SQL
                          1
                          
                          SELECT * FROM my_schema.my_table;

                          выходит ошибка — нет доступа к схеме my_schema

                          пытаюсь по другому:

                          SQL
                          1
                          2
                          
                          SET search_path TO my_schema,public;
                          SELECT * FROM my_table;

                          Ошибка — нет доступа к таблице my_table!

                          Что я делаю не так?!

                          __________________
                          Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

                          0

                          grgdvo

                          1184 / 914 / 367

                          Регистрация: 02.09.2012

                          Сообщений: 2,785

                          10.04.2021, 09:09

                          2

                          Лучший ответ Сообщение было отмечено NataNov как решение

                          Решение

                          Схема — такой же объект базы, как и таблицы.
                          Вы дали доступ на все таблицы в схеме, но не дали доступ к самой схеме.
                          См. что-то типа

                          SQL
                          1
                          
                          GRANT USAGE ON SCHEMA my_schema TO user1;

                          1

                          Допустим, я сделал эту «простую» реализацию БД в Postgres.

                          postgres=# CREATE ROLE my_role;
                                     CREATE DATABASE my_db;
                                     GRANT ALL ON DATABASE my_db TO my_role;
                                     CREATE SCHEMA my_schm AUTHORIZATION my_role;
                          

                          А потом я хочу сделать таблицу:

                          postgres=#CREATE TABLE IF NOT EXIST my_db.my_schm.table(...);
                          

                          И получил следующую ошибку: cross-database references are not implemented: "my_db.my_schm.table"

                          После этого я попытался создать таблицу, подключенную к базе данных (т.е. c my_db), и получил следующую ошибку:

                          schema "my_schm"does not exist
                          

                          Итак, я не понимаю поведения этих ошибок. Предполагается, что роль имеет все разрешения для базы данных (и да, я также пробовал использовать SET ROLE my_role;), но когда я прошу показать схемы в my_db действительно my_schm не существует, но в Postgres он есть. Может кто-нибудь объяснить мне, пожалуйста, почему это происходит? А также как сгруппировать таблицы в my_schm?

                          1 ответ

                          Лучший ответ

                          Схемы существуют только в одной базе данных и создаются в текущей базе данных: вы создали свою схему в базе данных postgres, а не в mydb.

                          Вам необходимо сначала подключиться к базе данных mydb, чтобы создать схему в базе данных mydb.


                          3

                          pifor
                          24 Май 2020 в 10:56

                            msm.ru

                            Нравится ресурс?

                            Помоги проекту!

                            !
                            информация о разделе

                            user posted image Данный раздел предназначается исключительно для обсуждения вопросов использования языка запросов SQL. Обсуждение общих вопросов, связанных с тематикой баз данных — обсуждаем в разделе «Базы данных: общие вопросы». Убедительная просьба — соблюдать «Правила форума» и не пренебрегать «Правильным оформлением своих тем». Прежде, чем создавать тему, имеет смысл заглянуть в раздел «Базы данных: FAQ», возможно там уже есть ответ.

                            >
                            разные пользователи и доступ
                            , не могу разобраться с ролями

                            • Подписаться на тему
                            • Сообщить другу
                            • Скачать/распечатать тему

                              


                            Сообщ.
                            #1

                            ,
                            13.10.15, 19:17

                              Senior Member

                              ****

                              Рейтинг (т): 13

                              Здравствуйте, Господа!
                              Сразу предупрежу: в PostgreSQL я пока еще совсем новичок.
                              Опишу проблему на примере, думаю так станет понятнее.

                              ExpandedWrap disabled

                                #psql

                                postgres=# CREATE USER user1 WITH password ‘password’;

                                postgres=# CREATE DATABASE db1;

                                postgres=# GRANT ALL PRIVILEGES ON DATABASE db1 TO user1;

                                postgres=# CREATE USER user2 WITH password ‘password’;

                                postgres=# GRANT ALL PRIVILEGES ON DATABASE db1 TO user2;

                                postgres=# q

                                #psql -U user1 db1

                                db1=# CREATE SEQUENCE user_ids;

                                db1=# CREATE TABLE users (id INTEGER PRIMARY KEY DEFAULT NEXTVAL(‘user_ids’), login CHAR(64), password CHAR(64));

                                db1=# INSERT INTO users (login, password) VALUES («u1», «p1»);

                                db1=# q

                                #psql -U user2 db1

                                db1=# INSERT INTO users (login, password) VALUES («u2», «p2»);

                                ОШИБКА:  нет доступа к отношению users

                              Вот тут я в растерянности. Оба пользователя ALL PRIVILEGES для db1, но второй, т.е. не создатель таблицы, добавлять записи не может.
                              Как это побороть?


                              grgdvo



                              Сообщ.
                              #2

                              ,
                              14.10.15, 12:36

                                Member

                                **

                                Рейтинг (т): 21

                                Опция ALL PRIVILEGES для DATABASE подразумевает CREATE, CONNECT и кажется TEMP привилегии для базы данных.
                                Так вот CREATE позволяет создавать ТОЛЬКО схемы в рамках базы данных.
                                А для схемы вы не предоставили прав, соответственно получили ошибку доступа.


                                HighMan



                                Сообщ.
                                #3

                                ,
                                14.10.15, 14:57

                                  Senior Member

                                  ****

                                  Рейтинг (т): 13

                                  Цитата grgdvo @ 14.10.15, 12:36

                                  Опция ALL PRIVILEGES для DATABASE подразумевает CREATE, CONNECT и кажется TEMP привилегии для базы данных.
                                  Так вот CREATE позволяет создавать ТОЛЬКО схемы в рамках базы данных.
                                  А для схемы вы не предоставили прав, соответственно получили ошибку доступа.

                                  Простите бестолкового, а как для схем предоставить привилегии?
                                  Если, возможно, напишите запрос на основе моего примера.
                                  Спасибо!

                                  Сообщение отредактировано: HighMan — 14.10.15, 14:58


                                  grgdvo



                                  Сообщ.
                                  #4

                                  ,
                                  14.10.15, 20:28

                                    Member

                                    **

                                    Рейтинг (т): 21

                                    Цитата HighMan @ 14.10.15, 14:57

                                    Простите бестолкового, а как для схем предоставить привилегии?

                                    В конце я неправ, забываешь как оно работает, когда не пользуешься.
                                    Для схемы (как объекта) тоже будет недостаточно прав :(

                                    Нужны команды конкретно на таблицу или ALL TABLES IN SCHEMA.
                                    И права нужно раздавать после создания таблицы, либо умудриться использовать ALTER DEFAULT PRIVILEGES.

                                    Для вашего примера скорее всего правильный порядок будет такой

                                    ExpandedWrap disabled

                                      ~ # psql -U postgres

                                      postgres=# CREATE USER user1 WITH password ‘password’;

                                      postgres=# CREATE USER user2 WITH password ‘password’;

                                      postgres=# CREATE DATABASE db1;

                                      postgres=# q

                                    db1 создается со схемой public по умолчанию, в которой пользователи уже могут создавать таблицы (и т.д.), поэтому user1 и user2 смогут создать свои объекты базы

                                    ExpandedWrap disabled

                                      ~ # psql -U user1 db1

                                      db1=# CREATE SEQUENCE user_ids;

                                      db1=# CREATE TABLE users (id INTEGER PRIMARY KEY DEFAULT NEXTVAL(‘user_ids’), login CHAR(64), password CHAR(64));

                                      db1=# INSERT INTO users (login, password) VALUES (‘u1’, ‘p1’);

                                      db1=# q

                                    теперь к user_ids и users доступ имеет только user1, ибо он владелец этих объектов.
                                    Назначаем права user2

                                    ExpandedWrap disabled

                                      ~ # psql -U postgres db1

                                      db1=# GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO user2;

                                      db1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO user2;

                                    Теперь user2 имеет все привилегии на таблицы и последовательнсти, которые УЖЕ БЫЛИ СОЗДАНЫ на данный момент в схеме.

                                    ExpandedWrap disabled

                                      ~ # psql -U user2 db1

                                      db1=# INSERT INTO users (login, password) VALUES (‘u2’, ‘p2’);

                                    Сообщение отредактировано: grgdvo — 14.10.15, 20:28


                                    HighMan



                                    Сообщ.
                                    #5

                                    ,
                                    14.10.15, 20:30

                                      Senior Member

                                      ****

                                      Рейтинг (т): 13

                                      Цитата grgdvo @ 14.10.15, 20:28

                                      Цитата HighMan @ 14.10.15, 14:57

                                      Простите бестолкового, а как для схем предоставить привилегии?

                                      В конце я неправ, забываешь как оно работает, когда не пользуешься.
                                      Для схемы (как объекта) тоже будет недостаточно прав :(

                                      Нужны команды конкретно на таблицу или ALL TABLES IN SCHEMA.
                                      И права нужно раздавать после создания таблицы, либо умудриться использовать ALTER DEFAULT PRIVILEGES.

                                      Для вашего примера скорее всего правильный порядок будет такой

                                      ExpandedWrap disabled

                                        ~ # psql -U postgres

                                        postgres=# CREATE USER user1 WITH password ‘password’;

                                        postgres=# CREATE USER user2 WITH password ‘password’;

                                        postgres=# CREATE DATABASE db1;

                                        postgres=# q

                                      db1 создается со схемой public по умолчанию, в которой пользователи уже могут создавать таблицы (и т.д.), поэтому user1 и user2 смогут создать свои объекты базы

                                      ExpandedWrap disabled

                                        ~ # psql -U user1 db1

                                        db1=# CREATE SEQUENCE user_ids;

                                        db1=# CREATE TABLE users (id INTEGER PRIMARY KEY DEFAULT NEXTVAL(‘user_ids’), login CHAR(64), password CHAR(64));

                                        db1=# INSERT INTO users (login, password) VALUES (‘u1’, ‘p1’);

                                        db1=# q

                                      теперь к user_ids и users доступ имеет только user1, ибо он владелец этих объектов.
                                      Назначаем права user2

                                      ExpandedWrap disabled

                                        ~ # psql -U postgres db1

                                        db1=# GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO user2;

                                        db1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO user2;

                                      Теперь user2 имеет все привилегии на таблицы и последовательнсти, которые УЖЕ БЫЛИ СОЗДАНЫ на данный момент в схеме.

                                      ExpandedWrap disabled

                                        ~ # psql -U user2 db1

                                        db1=# INSERT INTO users (login, password) VALUES (‘u2’, ‘p2’);

                                      Спасибо большое!
                                      Постараюсь завтра проверить!

                                      0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                                      0 пользователей:

                                      • Предыдущая тема
                                      • Базы данных: SQL
                                      • Следующая тема

                                      Рейтинг@Mail.ru

                                      [ Script execution time: 0,0347 ]   [ 15 queries used ]   [ Generated: 30.01.23, 08:58 GMT ]  

                                      Subscribe to RSS feed 

                                      Follow @jackvamvas - Twitter

                                      *Use the Comments section for questions

                                      Daily & Exclusive Content

                                      Dba_db2_button

                                      Sqlserver_dba_button

                                      [ Script execution time: 0,0347 ]   [ 15 queries used ]   [ Generated: 30.01.23, 08:58 GMT ]  

                                      Понравилась статья? Поделить с друзьями:

                                      Интересное по теме:

                                    • Ошибка ноль при отправке смс
                                    • Ошибка ниссан теана 0335
                                    • Ошибка нет доступа к локальному диску
                                    • Ошибка ноль на триколор тв что означает
                                    • Ошибка ниссан серена 1320

                                    • Добавить комментарий

                                      ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: