错误:使用Postgres拒绝序列cities_id_seq的权限

我是新的postgres(所有数据库信息系统)。 我在我的数据库上运行下面的SQL脚本:

create table cities ( id serial primary key, name text not null ); create table reports ( id serial primary key, cityid integer not null references cities(id), reportdate date not null, reporttext text not null ); create user www with password 'www'; grant select on cities to www; grant insert on cities to www; grant delete on cities to www; grant select on reports to www; grant insert on reports to www; grant delete on reports to www; grant select on cities_id_seq to www; grant insert on cities_id_seq to www; grant delete on cities_id_seq to www; grant select on reports_id_seq to www; grant insert on reports_id_seq to www; grant delete on reports_id_seq to www; 

当用户www,试图:

 insert into cities (name) values ('London'); 

我得到以下错误:

 ERROR: permission denied for sequence cities_id_seq 

我得到的问题在于串行types。 这就是为什么我授予select,插入和删除* _id_seq到www的权利。 但是这并不能解决我的问题。 我错过了什么?

从PostgreSQL 8.2开始,你必须使用:

 GRANT USAGE, SELECT ON SEQUENCE cities_id_seq TO www; 

授予使用 – 对于序列,这个权限允许使用currval和nextval函数。

也正如@epic_fil在注释中指出的那样,您可以通过以下方式将权限授予模式中的所有序列:

 GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO www; 

由于@Phil有一个评论得到了很多upvotes可能不会被注意到,我使用他的语法添加一个答案,将权限授予用户在架构中的所有序列(假设您的架构是默认的“公共” )

 GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public to www; 

@Tom_Gerken,@epic_fil和@kupson对他们的声明是非常正确的,赋予权限与现有序列一起工作。 但是,用户将不会获得将来创build的序列的访问权限。 为此,您必须将GRANT语句与ALTER DEFAULT PRIVILEGES语句组合起来,如下所示:

 GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO www; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO www; 

当然,这只适用于PostgreSQL 9+。

这将附加到现有的默认权限,而不是覆盖它们,所以在这方面是非常安全的。