简体   繁体   English

postgreSQL 中的复制约束使用(使用 GIST 和或 EXCLUDE)

[英]Duplication constraint in postgreSQL using (using GIST and or EXCLUDE)

How to write a constraint (table level unique, using GIST and or EXCLUDE ) to perform duplication record validation using the following rule:如何编写约束(表级唯一,使用 GIST 和或 EXCLUDE )以使用以下规则执行重复记录验证:

  1. Entered from_date and to_date values should not be equal or within the range, and输入的 from_date 和 to_date 值不应相等或在该范围内,并且
  2. Employee_id should not be equal, and Employee_id 不应该相等,并且
  3. status = 'pending'状态 = '待定'

After the validation, an error message should be return saying 'Duplicate Entry'.验证后,应返回一条错误消息,指出“重复条目”。 This is in postgreSQL.这是在 postgreSQL 中。

Note: I am new to postgreSQL (worked in MS SQL Server and MySQL).注意:我是 postgreSQL 的新手(在 MS SQL Server 和 MySQL 中工作过)。

Thanks in advance.提前致谢。

As stated by @Laurenz Albe, it sounds like impossible to do with a constraint.正如@Laurenz Albe 所说,使用约束听起来似乎是不可能的。 You can implement either a trigger function or a rule instead :您可以改为实现trigger functionrule

Trigger function :触发功能:

CREATE OR REPLACE FUNCTION test_insert_table()
RETURNS trigger LANGUAGE plpgsql IMMUTABLE AS
$$
BEGIN
IF NEW.status = 'pending'
AND EXISTS
  ( SELECT 1
      FROM your_table
     WHERE Employee_id = NEW.Employee_id
       AND range @> daterange(NEW.from_date, NEW.to_date)
  )
THEN
  RAISE EXCEPTION 'Duplicate Entry' ;
  RETURN NULL ;
ELSE
  RETURN NEW ;
END IF ;
END ;
$$

CREATE OR REPLACE TRIGGER test_insert_table 
BEFORE INSERT ON your_table
FOR EACH ROW EXECUTE FUNCTION test_insert_table() ;

Rule :规则 :

CREATE OR REPLACE RULE test_insert AS
    ON INSERT TO your_table
 WHERE NEW.status = 'pending'
   AND EXISTS
       ( SELECT 1
           FROM your_table
          WHERE Employee_id = NEW.Employee_id
            AND range @> daterange(NEW.from_date, NEW.to_date)
       )
    DO INSTEAD NOTHING ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM