Postgres date overlapping constraint

前端 未结 4 1136
鱼传尺愫
鱼传尺愫 2020-12-14 08:22

I have a table like this:

date_start    date_end     account_id    product_id
2001-01-01    2001-01-31   1             1
2001-02-01    2001-02-20   1                 


        
4条回答
  •  再見小時候
    2020-12-14 08:59

    Ok i ended up doing this :

    CREATE TABLE test (
        from_ts TIMESTAMPTZ,
        to_ts TIMESTAMPTZ,
        account_id INTEGER DEFAULT 1,
        product_id INTEGER DEFAULT 1,
        CHECK ( from_ts < to_ts ),
        CONSTRAINT overlapping_times EXCLUDE USING GIST (
            account_id WITH =,
            product_id WITH =,
            period(from_ts, CASE WHEN to_ts IS NULL THEN 'infinity' ELSE to_ts END) WITH &&
        )
    );
    

    Works perfectly with infinity, transaction proof.

    I just had to install temporal extension which is going to be native in postgres 9.2 and btree_gist available as an extension in 9.1 CREATE EXTENSION btree_gist;

    nb : if you don't have null timestamp there is no need to use the temporal extension you could go with the box method as specified in my question.

提交回复
热议问题