授予了我的 PostGres table 的所有权限,但在尝试 insert/select 时仍然收到 "Permission denied" 错误

Granted all privileges on my PostGres table, but still am getting a "Permission denied" error when attempting to insert/select

我正在使用 PostGres 9.5。我无法将数据插入我刚创建的 table。尽管向数据库用户授予了所有权限,但我仍收到 "permission denied" 错误。见下文...

localhost:myapp davea$ psql -Upostgres
Password for user postgres:
psql (9.5.0, server 9.5.1)
Type "help" for help.

postgres=# GRANT ALL ON schema public TO myapp;
GRANT

localhost:myapp davea$ psql -Upostgres
Password for user postgres:
psql (9.5.0, server 9.5.1)
Type "help" for help.

postgres=# GRANT USAGE ON schema public TO myapp;
GRANT
postgres=# \q
localhost:myapp davea$ myapp
psql (9.5.0, server 9.5.1)
Type "help" for help.

myapp=> insert into search_codes (id, code, address_id) values (1, 'atlanta', 'GA');
ERROR:  permission denied for relation search_codes
myapp=> select * FROM search_codes;
ERROR:  permission denied for relation search_codes
myapp=> \d search_codes;
                                Table "public.search_codes"
   Column   |       Type        |                         Modifiers
------------+-------------------+-----------------------------------------------------------
 id         | integer           | not null default nextval('search_codes_id_seq'::regclass)
 code       | character varying |
 address_id | character varying |
Indexes:
    "search_codes_pkey" PRIMARY KEY, btree (id)
    "index_search_codes_on_code" UNIQUE, btree (code)
    "index_search_codes_on_address_id" btree (address_id)

授予权限的正确方法是什么,以便我的用户可以从 table 插入和 select?

您在 postgres 数据库而不是 myapp 数据库中授予权限。

将第一个 PSQL 命令更改为

psql -Upostgres myapp

然后发放补助金

看看https://dba.stackexchange.com/questions/33943/granting-access-to-all-tables-for-a-user

我认为您的问题是 GRANT 对于数据库、架构和表是不同的,因此您需要明确地设置对表的权限。

您的第一个命令使您能够列出 table(您可以只知道存在)

GRANT USAGE ON SCHEMA public TO myapp

然后您必须将 SELECT、INSERT 等授予模式 public

中的所有 table
GRANT SELECT, UPDATE, INSERT, DELETE ON ALL TABLES IN SCHEMA public TO myapp

我建议不要将所有权限授予特定应用。

如果你有序列:

 GRANT SELECT, UPDATE, USAGE ON ALL SEQUENCES IN SCHEMA public to myapp

如果你有函数:

GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO myapp

那么你的例子就可以了。

但是如果你想让创建的 futur table 能够被访问,你仍然需要应用一些命令:

ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, UPDATE, INSERT, DELETE, TRIGGER ON TABLES TO myapp

Postgresql 有一个非常奇怪的机制,我花了一段时间才理解它!

首先你必须使用 postgres 用户登录你的新数据库

psql your_db_name -U postgres -h your_host_name

赋予列出的能力table

GRANT USAGE ON SCHEMA public TO your_user_name

然后您必须授予架构 public

中所有 table 的权限
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO your_user_name

如果您有序列,请给予许可

GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO your_user_name