9

Postgres comes with a nice feature called Range Types that provides useful range functionality (overlaps, contains, etc).

I am looking to use the daterange type, however I think the type was implemented with an awkward choice: the upper bound of the daterange is excluded. That means that if I defined my value as 2014/01/01 - 2014/01/31, this is displayed as [2014/01/01, 2014/01/31) and the 31st of January is excluded from the range!

I think this was the wrong default choice here. I cannot think of any application or reference in real life that assumes that the end date of a date range is excluded. At least not to my experience.

I want to implement a range type for dates with both lower and upper bounds included, but I am hitting the Postgres documentation wall: References on how to create a new discrete range type are cryptic and lack any examples (taken from the documentation: Creating a canonical function is a bit tricky, since it must be defined before the range type can be declared).

Can someone provide some help on this? Or even directly the implementation itself; it should be 5-10 lines of code, but putting these 5-10 lines together is a serious research effort.

EDIT: Clarification: I am looking for information on how to create the proper type so that inserting [2014/01/01, 2014/01/31] results in a upper(daterange) = '2014/01/31'. With the existing daterange type this value is "converted" to a [2014/01/01, 2014/02/01) and gives a upper(daterange) = '2014/02/01'

7
  • 1
    Postgres range types are always converted to a canonical form [). If you need to present [A,B], then process the value before presenting it to the user. Apr 29, 2016 at 12:44
  • Correct. Postgres also says you can define range types whose canonical form is not the default [), but whichever you wish. I was looking for the type that alleviates my application having to do that processing, which I now have to do both when querying and when inserting data.
    – dtheodor
    May 5, 2016 at 15:33
  • I can't think of a single application or reference in real life that the end date is included. If I'm making a booking at a hotel, I'm not staying on the end date but I am on the arrive date, so the end date isn't included. That's why it's the default.
    – dalore
    Sep 10, 2020 at 11:55
  • 1
    Bookings are a good counter example to what I am saying indeed. Think of any kind of interactive report though. You are looking at a company's sales report for example, and there's a daterange dropdown that allows you to filter on specific dates. You click on a start and an end date, and you always mean to include both of them. The application I was working on when I wrote this had users enter specific data for dateranges they selected, and selecting the end date always meant to include it.
    – dtheodor
    Sep 11, 2020 at 10:29
  • @MatthewSchinckel's answer is correct. The output canonical form is [) for date range. For example select daterange('20200101' , '20201220' , []) as range1 returns output of [2020-01-01, 2020-12-21) and select daterange('20200101' , '20201220' , () ) as range2 returns output of [2020-01-02, 2020-12-21)
    – RKA
    Oct 8, 2021 at 4:31

4 Answers 4

13

Notice the third constructor parameter:

select daterange('2014/01/01', '2014/01/31', '[]');
        daterange        
-------------------------
 [2014-01-01,2014-02-01)

Or a direct cast with the upper bound included:

select '[2014/01/01, 2014/01/31]'::daterange;
        daterange        
-------------------------
 [2014-01-01,2014-02-01)

Edit

Not a new type (wrong approach IMHO) but a proper function:

create function inclusive_upper_daterange(dtr daterange)
returns date as $$

    select upper(dtr) - 1;

$$ language sql immutable;

select inclusive_upper_daterange('[2014/01/01, 2014/01/31]'::daterange);
 inclusive_upper_daterange 
---------------------------
 2014-01-31
5
  • 1
    Right, I could do that. Still gives the [2014-01-01,2014-02-01) output when browsing the tables, and a upper(daterange) returns 2014-02-01. I already implement all these kinds of workarounds in my application. Constructing the proper type that does not need any such workarounds is the answer I am looking for.
    – dtheodor
    Apr 27, 2015 at 13:09
  • Also I just realized, you edited my question's title which alters its meaning and then you answered that altered meaning.
    – dtheodor
    Apr 27, 2015 at 13:14
  • @dtheodor Sorry about the edit. I understood that was what you was looking for in the first place. You are mixing data presentation with meaning which should be dealt with in different layers. Apr 27, 2015 at 13:26
  • I tried to clarify with a new edit, hope it is more clear now
    – dtheodor
    Apr 27, 2015 at 13:30
  • Sorry, I was really looking for information on how to declare a new discrete range type, not other workarounds. I went through the effort to figure it out myself and accepted my own answer.
    – dtheodor
    Apr 29, 2015 at 12:45
0

Following the instructions on Postgres documentation I came up with the following code to create the type I need. However it won't work (read on).

CREATE TYPE daterange_;

CREATE FUNCTION date_minus(date1 date, date2 date) RETURNS float AS $$
    SELECT cast(date1 - date2 as float);
$$ LANGUAGE sql immutable;

CREATE FUNCTION dr_canonical(dr daterange_) RETURNS daterange_ AS $$
BEGIN
    IF NOT lower_inc(dr) THEN
        dr := daterange_(lower(dr) + 1, upper(dr), '[]');
    END IF;
    IF NOT upper_inc(dr) THEN
        dr := daterange_(lower(dr), upper(dr) - 1, '[]');
    END IF;
    RETURN dr;
END;
$$ LANGUAGE plpgsql;

CREATE TYPE daterange_ AS RANGE (
    SUBTYPE = date,
    SUBTYPE_DIFF = date_minus,
    CANONICAL = dr_canonical    
);

As far as I can tell, this definition follows the specification exactly. However it fails at declaring the dr_canonical function with ERROR: SQL function cannot accept shell type daterange_.

It looks like (code also) it is impossible to declare a canonical function using any language other than C! So it is practically impossible to declare a new discrete range type, especially if you use a Postgres cloud service that gives no access to the machine running it. Well played Postgres.

0

Using PostgresSQL 11 you can solve presentation part using upper_inc function, example:

select
    WHEN upper_inc(mydaterange) THEN upper(mydaterange)
    ELSE date(upper(mydaterange)- INTERVAL '1 day')
 END 
-2

I managed to create a custom type for the date range:

    CREATE or replace FUNCTION to_timestamptz(arg1 timestamptz, arg2 timestamptz) RETURNS float8 AS
    'select extract(epoch from (arg2 - arg1));' LANGUAGE sql STRICT
                                                             IMMUTABLE;
    ;
    create type tsrangetz AS RANGE
    (
      subtype = timestamptz,
      subtype_diff =
      to_timestamptz
    )
    ;
    select tsrangetz(current_date, current_date + 1)
    --["2020-10-05 00:00:00+07","2020-10-06 00:00:00+07")
    ;
1
  • 2
    Please translate the comment into English like I managed to create a custom type for the date range and add some description/clarification about your code which seems to be fine. Oct 5, 2020 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.