Postgresql:违反检查约束。失败的行包含

Postgresql: Violates check constraint. Failing row contains

我尝试使用 postgresql 在数据库中插入一些数据,但仍然显示相同的消息:

ERROR: new row for relation "empleados" violates check constraint "ck_empleados_documento" DETAIL: Failing row contains (13, 22222222, f, Lopez, Ana, Colon 123, 1, 2, casado , 1990-10-10).

我不知道错误出在哪里或什么,也没有找到解决此问题的任何方法。这是我尝试插入的内容:

insert into empleados (documento, sexo, apellido, nombre, domicilio, idSecc, cantidadhijos, estadocivil, fechaingreso) values('22222222','f','Lopez','Ana','Colon 123',1,2,'casado','1990-10-10');

这是table的结构:

CREATE TABLE public.empleados
(
  idempleado integer NOT NULL DEFAULT nextval('empleados_idempleado_seq'::regclass),
  documento character(8),
  sexo character(1),
  apellido character varying(20),
  nombre character varying(20),
  domicilio character varying(30),
  idsecc smallint NOT NULL,
  cantidadhijos smallint,
  estadocivil character(10),
  fechaingreso date,
  CONSTRAINT pk_empleados PRIMARY KEY (idempleado),
  CONSTRAINT fk_empleados_idsecc FOREIGN KEY (idsecc)
      REFERENCES public.puestos (idpuesto) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE NO ACTION,
  CONSTRAINT uq_empleados_documento UNIQUE (documento),
  CONSTRAINT ck_empleados_documento CHECK (documento ~~ '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'::text),
  CONSTRAINT ck_empleados_estadocivil CHECK (estadocivil = ANY (ARRAY['casado'::bpchar, 'divorciado'::bpchar, 'soltero'::bpchar, 'viudo'::bpchar])),
  CONSTRAINT ck_empleados_hijos CHECK (cantidadhijos >= 0),
  CONSTRAINT ck_empleados_sexo CHECK (sexo = ANY (ARRAY['f'::bpchar, 'm'::bpchar]))
)

我觉得你的ck_empleados_documento应该这样写:

CONSTRAINT ck_empleados_documento CHECK (documento ~ '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'::text),

解释:根据Postgres Documentation

The operator ~~ is equivalent to LIKE

如果你想要模式匹配,你需要使用运算符:

~       Matches regular expression, case sensitive
~*  Matches regular expression, case insensitive
!~  Does not match regular expression, case sensitive
!~*     Does not match regular expression, case insensitive

错误消息显示您所在的行 violates check constraint "ck_empleados_documento"

ck_empleados_documento 定义为

CONSTRAINT ck_empleados_documento CHECK (documento ~~ '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'::text)

根据https://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-LIKE

The operator ~~ is equivalent to LIKE

所以你的限制真的意味着

documento LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'::text

来自同一页面:

stringLIKEpattern

If pattern does not contain percent signs or underscores, then the pattern only represents the string itself

您的模式不包含 %_,因此它等同于

documento = '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'

这不可能是真的,因为 documento 只有 8 个字符长。


您可能想这样做:

documento SIMILAR TO '[0-9]{8}'

SIMILAR TO 使用 SQL 正则表达式并理解 类 字符,例如 [0-9].