Better way to process boolean query result in shell-like situations?

From: Tim Landscheidt <tim(at)tim-landscheidt(dot)de>
To: pgsql-general(at)postgresql(dot)org
Subject: Better way to process boolean query result in shell-like situations?
Date: 2015-10-29 02:42:00
Message-ID: 87ziz2l7k7.fsf@passepartout.tim-landscheidt.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi,

I regularly run into the problem that I want to query a
PostgreSQL database in a script/program and depending on a
boolean result do one thing or the other. A typical example
would be a Puppet Exec that creates a user only if it does
not exist yet.

But unfortunately psql always returns with the exit code 0
if the query was run without errors. In a shell script I
can use a query that returns an empty string for failure and
something else for success and then test that à la:

| if [ -n "$(psql -Atc "[…]") ]; then echo Success.; fi

but for example in Puppet this requires putting around
'/bin/bash -c "[…]"' with yet another level of quoting.

The best idea I had so far was to cause a runtime error
(here with the logic reversed: If the user exists, psql re-
turns failure, otherwise success):

| [tim(at)passepartout ~]$ psql -c "SELECT usename::INT FROM pg_user WHERE usename = 'tim';"; echo $?
| FEHLER: ungültige Eingabesyntax für ganze Zahl: »tim«
| 1
| [tim(at)passepartout ~]$ psql -c "SELECT usename::INT FROM pg_user WHERE usename = 'does-not-exist';"; echo $?
| usename
| ---------
| (0 rows)

| 0
| [tim(at)passepartout ~]$

But this (in theory) could fail if usename could be con-
verted to a number, and for example 'a'::INT will fail al-
ways.

Are there better ways? The environment I am most interested
in is 9.3 on Ubuntu Trusty.

Tim

P. S.: I /can/ write providers or inline templates for Pup-
pet in Ruby to deal with these questions; but here I
am only looking for a solution that is more "univer-
sal" and relies solely on psql or another utility
that is already installed.

Responses

Browse pgsql-general by date

  From Date Subject
Next Message David G. Johnston 2015-10-29 02:59:15 Re: Better way to process boolean query result in shell-like situations?
Previous Message Yves Dorfsman 2015-10-28 23:57:11 Re: does pg_dump get delayed if I have a loop that does continuous insertions