在 heroku postgres 上创建自动增量主键列时出错

error when creating an auto increment primary key column on heroku postgres

尝试在 heroku 中设置我的 postgres table,当我尝试在 table

的主键中设置自动递增时出现此错误

user_id_seq relation does not exist

这是创建语句

CREATE TABLE "public"."user" (
    "id" INTEGER DEFAULT nextval('user_id_seq'::regclass) NOT NULL UNIQUE,
    "uname" CHARACTER VARYING( 255 ) COLLATE "pg_catalog"."default" UNIQUE,
    "description" CHARACTER VARYING( 2044 ) COLLATE "pg_catalog"."default",
    "country" CHARACTER( 3 ) COLLATE "pg_catalog"."default" DEFAULT 'USA'::bpchar NOT NULL,
 PRIMARY KEY ( "id" )
, CONSTRAINT "unique_uname" UNIQUE( "uname" ) );

该错误是什么意思,我是否必须以某种方式事先建立该关系?

你必须先 create the equence 像这样:

CREATE SEQUENCE user_id_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 1
  CACHE 1;`

或者将您的列 id 声明为 serial:

CREATE TABLE "public"."user" (
    "id" bigserial NOT NULL UNIQUE,
    "uname" CHARACTER VARYING( 255 ) COLLATE "pg_catalog"."default" UNIQUE,
    "description" CHARACTER VARYING( 2044 ) COLLATE "pg_catalog"."default",
    "country" CHARACTER( 3 ) COLLATE "pg_catalog"."default" DEFAULT     'USA'::bpchar NOT NULL,
 PRIMARY KEY ( "id" )
, CONSTRAINT "unique_uname" UNIQUE( "uname" ) );

相当于:

CREATE SEQUENCE user_id_seq;

CREATE TABLE "public"."user" (
    "id" bigint NOT NULL UNIQUE DEFAULT nextval('user_id_seq'),
    "uname" CHARACTER VARYING( 255 ) COLLATE "pg_catalog"."default" UNIQUE,
    "description" CHARACTER VARYING( 2044 ) COLLATE "pg_catalog"."default",
    "country" CHARACTER( 3 ) COLLATE "pg_catalog"."default" DEFAULT     'USA'::bpchar NOT NULL,
 PRIMARY KEY ( "id" )
, CONSTRAINT "unique_uname" UNIQUE( "uname" ) );


ALTER SEQUENCE user_id_seq OWNED BY public.user.id;