Re: \if, \elseif, \else, \endif (was Re: PSQL commands: \quit_if, \quit_unless)

From: Fabien COELHO <coelho(at)cri(dot)ensmp(dot)fr>
To: Corey Huinker <corey(dot)huinker(at)gmail(dot)com>
Cc: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>, Greg Stark <stark(at)mit(dot)edu>, Erik Rijkers <er(at)xs4all(dot)nl>, Robert Haas <robertmhaas(at)gmail(dot)com>, Daniel Verite <daniel(at)manitou-mail(dot)org>, Jim Nasby <Jim(dot)Nasby(at)bluetreble(dot)com>, PostgreSQL <pgsql-hackers(at)postgresql(dot)org>, pgsql-hackers-owner(at)postgresql(dot)org
Subject: Re: \if, \elseif, \else, \endif (was Re: PSQL commands: \quit_if, \quit_unless)
Date: 2017-03-02 10:04:51
Message-ID: alpine.DEB.2.20.1703021042470.21981@lancre
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers


Hello Corey,

> Tom was pretty adamant that invalid commands are not executed. So in a case
> like this, with ON_ERROR_STOP off:
>
> \if false
> \echo 'a'
> \elif true
> \echo 'b'
> \elif invalid
> \echo 'c'
> \endif
>
> Both 'b' and 'c' should print, because "\elif invalid" should not execute.
> The code I had before was simpler, but it missed that.

Hmmm. You can still have it with one switch, by repeating the evaluation
under true and ignore, even if the value is not used:

switch(state)
{
case NONE: error;
case ELSE_TRUE: error;
case ELSE_FALSE: error;
case IF_TRUE:
if (eval())
...
else error;
break;
case IF_FALSE:
if (eval())
...
else error;
break;
case IGNORE:
if (eval())
...
else error;
break;
}

> Ok, so here's one idea I tossed around, maybe this will strike the right
> balance for you. If I create a function like this: [...]
>
> Does that handle your objections?

For me, it is only slightly better: I think that for helping understanding
and maintenance, the automaton state transitions should be all clear and
loud in just one place, so I would really like to see a single common
structure:

if (is "if") switch on all states;
else if (is "elif") switch on all states;
else if (is "else") switch on all states;
else if (is "endif") switch on all states;

And minimal necessary error handling around that.

Your suggestion does not achieve this, although I agree that the code
structure would be cleaner thanks to the function.

> p.s. do we try to avoid constructs like if (success = my_function(var1,
> var2)) ?

I think it is allowed because I found some of them with grep (libpq, ecpg,
postmaster, pg_dump, pg_upgrade...). They require added parentheses around
the assignment:

if ((success = eval())) ...

--
Fabien.

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Robert Haas 2017-03-02 10:20:48 Re: Enabling parallelism for queries coming from SQL or other PL functions
Previous Message Robert Haas 2017-03-02 10:01:25 Re: [Doc fix] Wrong explanation about tsquery_phrase