Assigning values to a range in Pgsql and inclusive / exclusive bounds

From: Ron Clarke <rclarkeai(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Assigning values to a range in Pgsql and inclusive / exclusive bounds
Date: 2020-06-12 18:45:26
Message-ID: CAGVf-sO0E-5qM2fm_oJ=FnS4E_sqBGneofwNFe2fnoVXEDGm=w@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi,

I've got a simple problem, but I'm convinced that there must be an
elegant solution. I'm a refugee from the world of MSSQL, so I'm still
finding some aspects of PostgreSQL alien.

I'm trying to use the *tstzrange *datatype. My issue is correctly setting
the bound types when assigning values to a range in code (PGSQL).

So if i declare this : e.g.

*declare tx tstzrange := '[today, tomorrow)' ;*

I get the variable tx as expected with the Inclusive '[' lower bound and
exclusive upper ')' bound.

But if I attempt to reassign the value in code within pgsql I can do this
simply, only with '(' syntax for the lower bound i.e. with an exclusive
lower bound, e.g so this works:-

*tx= (Timestamptz 'today', timestamptz 'now' + interval '1 hour');*

but if I try
* tx= [Timestamptz 'today', timestamptz 'now' + interval '1
hour'); *

this will have syntax errors - as the hidden 'select [' upsets the parser.
I've tried to include a '[)' in variations of the expression, but just get
various syntax errors..

I've tried many combinations and I can get it to work using casts and
concatenations, e.g. :-

* tx = CONCAT('[', 'today'::Timestamptz,',',('now' ::Timestamptz + interval
'1 hour'):: timestamptz , ')'):: tstzrange ;*

works but I can't help thinking that I'm missing something much simpler and
more elegant.
How should this actually be done?

Thanks in advance for your advice.

Ron
Stay safe everyone.

here's an example script to show what I mean:-

*do*
*$$*
*DECLARE*

*tx tstzrange := '[today, tomorrow)' ;*

* answer text;*

*BEGIN*

* RAISE NOTICE 'Start %', tx;*

* answer = tx @> 'today'::Timestamptz;*

* RAISE NOTICE 'today %', answer;*

* answer = tx @> 'tomorrow'::Timestamptz;*

* RAISE NOTICE 'tomorrow %', answer;*

*-- ( works-- tx= (Timestamptz 'today', timestamptz 'now' + interval '1
hour');*-- [ doesn't work
-- tx= [Timestamptz 'today', timestamptz 'now' + interval '1 hour');
-- working around the parser??
*tx = CONCAT('[', 'today'::Timestamptz,',',('now' ::Timestamptz + interval
'1 hour'):: *timestamptz , ')'):: tstzrange ;

*RAISE NOTICE 'reassign %', tx;*

* answer = tx @> 'today'::Timestamptz;*

* RAISE NOTICE 'today %', answer;*

* answer = tx @> 'now'::Timestamptz;*

* RAISE NOTICE 'now %', answer;*

*END;*
*$$ *

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2020-06-12 18:55:24 Re: Assigning values to a range in Pgsql and inclusive / exclusive bounds
Previous Message George Dimopoulos 2020-06-12 13:32:51 RE: ora2pg error : DBD::Oracle::db prepare failed: ORA-28110