带有序列的 Postgres URI 生成?

Postgres URI generation with sequences?

所以我想在 postgres 数据库的 table 中创建一个列,自动递增一个数字并将其放在一些数据之后。又名

协议 table:

    name     |      uri      | 
_____________________________
someProtocol | /protocol/1
otherProt    | /protocol/2

有没有办法用其他数据创建某种序列?我对 postgres 列创建的了解相当有限

create table protocols (
  id serial primary key, -- creates a sequence int
  name text not null,
  uri text 
);

create or replace function protocols_set_uri() returns trigger as $$
begin
    new.uri = '/' || new.name || '/' || new.id; 
    return new;
end $$
language plpgsql;

create trigger protocols_set_uri 
  before insert or update on protocols 
  for each row execute procedure protocols_set_uri();

示例:

insert into protocols (name) values ('someProtocol');
select * from protocols;

结果:

id name          uri
--------------------------------
1  someProtocol  /someProtocol/1

您不需要更新任何冗余字段;你可以在需要的时候计算它们,就像下面的视图:

CREATE TABLE protocols (
  id SERIAL PRIMARY KEY -- creates a sequence int
  , name text not null
  );

INSERT INTO protocols(name) VALUES( 'DNS') ,( 'SMTP') ,( 'HTTP') ;

create VIEW fake_protocols AS
  SELECT id, name
  , '/protocol/' || id::text AS fake_uri
FROM protocols
        ;

SELECT * FROM fake_protocols;

输出:

CREATE TABLE
INSERT 0 3
CREATE VIEW
 id | name |  fake_uri   
----+------+-------------
  1 | DNS  | /protocol/1
  2 | SMTP | /protocol/2
  3 | HTTP | /protocol/3
(3 rows)