Re: Script checking to see what database it's connected to

From: Ron <ronljohnsonjr(at)gmail(dot)com>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Script checking to see what database it's connected to
Date: 2021-02-22 00:42:50
Message-ID: e3b70f2b-3ab9-a855-6ed9-68d0868e6eac@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 2/21/21 5:26 PM, Rob Sargent wrote:
>
>
> On 2/21/21 4:18 PM, Ron wrote:
>>
>> Postgresql 12.5
>>
>> I've got scripts which can run on multiple database (dev, test, QA,
>> Integration, Training, etc, etc), so of course I've got to run them like
>> "psql my_db_name -f script.sql".
>>
>> Of course, I sometimes forget to specify the database name, and so it fails.
>>
>> Thus, I want to add a bit to the top of the script, something like this:
>>
>> \if :DBNAME = postgres
>>      echo "must not run in postgres"
>>      exit
>> \endif
>>
>> However, I can't seem to find the magic sauce.
>>
>> This is what I've tried so far:
>>
>> postgres=# \if :DBNAME == postgres
>> unrecognized value "postgres == postgres" for "\if expression": Boolean
>> expected
>> postgres(at)#
>>
>> postgres=# \if ':DBNAME' == postgres
>> unrecognized value ":DBNAME == postgres" for "\if expression": Boolean
>> expected
>> postgres(at)#
>>
>> postgres=# \if :DBNAME == 'postgres'
>> unrecognized value "postgres == postgres" for "\if expression": Boolean
>> expected
>> postgres(at)#
>>
>> postgres=# \if ':DBNAME' == 'postgres'
>> unrecognized value ":DBNAME == postgres" for "\if expression": Boolean
>> expected
>> postgres(at)#
>>
>>
>
> Take it up a notch?  Write a script which takes the dbname and the script
> name:
>
> /pcode/
>
> #!/bin/bash -e
> if [[ $# -ne 2 ]]; then echo "missing arg(s)"; exit 2; fi
> dbn=$1; shift;
> sql=$1; shift;
> psql --dbname $dbn --file $sql
>
> /pcode/

I thought of that, yet so earnestly want avoid Yet Another Tiny Script.

--
Angular momentum makes the world go 'round.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Rob Sargent 2021-02-22 00:49:33 Re: Script checking to see what database it's connected to
Previous Message David G. Johnston 2021-02-21 23:41:38 Re: How to determine server's own IP address? inet_server_addr not working