Execute psql query in bash - bash

I have a problem with executing a psql-query in a bash script.
Below is my code.
run_sql(){
sql_sel="$1;";#sql select
table=$2;#table name
for i in "${!GP_SERVER_NAMES[#]}"
do
logmsg "Executing [$sql_sel] on "${GP_SERVER_NAMES[$i]}": " $loglvl;
result_host[$i]=`${PSQL_HOST[$i]}${sql_sel}`;
#result_host[$i]=cleanresult "`$(${PSQL_HOST[$i]} "$tx_fix $sql_sel" 2>&1`");
if [[ `checkresult "${result_host[$i]}"` != 'true' ]]; then
logmsg "Error occured during sql select: Result for "${GP_SERVER_NAMES[$i]}" '${table}': ${result_host[$i]};" '1' '1';
raise_alarm "${GP_SYNC_SQL_ERR}" "${i}" "${table}" "${result_host}";
fi
logmsg "Result for" ${GP_SERVER_NAMES[$i]} " '${table}': ${result_host[$i]}";
done
final_result='true';
for i in "${!result_host[#]}"
do
if [[ `checkresult "${result_host[$i]}"` = 'true' ]]; then
final_result='false';
I am trying to executing the query on many different servers, with the following command
result_host[$i]=${PSQL_HOST[$i]}${sql_sel};
The above variables have the following meaning:
1. result_host[$i] : is an array that holds the i-th result of the sql query.
2. PSQL_HOST[$i] : is the command line psql-statement, including the IP address which is of the form
psql -t -q -h -U password -d database -c
3. $sql_sel : is the sql_statement
When I run the script, I get the following output.
scriptname.sh: line 168: SELECT: command not found
ERROR: syntax error at end of input
LINE 1: SELECT
^
Why is that? Any help, comments or suggestions would be appreciated.

Related

Check if a role exists in PostgreSQL using psql

I need in a bash script a IF condition on the existence of a role in a PostgreSQL database. I have found solutions in SQL code [1, 2], but I need something I can use directly in bash, I assume with the help of psql. In [2] there are also psql solutions, but I don't manage to adapt it in a IF statement.
I have tried this unsuccessfully (I am a PostgreSQL and bash newbie):
psql_USER=my
if [ "$( psql -h db -U postgres --no-psqlrc --single-transaction --pset=pager=off --tuples-only --set=ON_ERROR_STOP=1 -tc "SELECT 1 FROM pg_user WHERE usename = $psql_USER" | grep -q 1 )" == '1' ] > /dev/null 2> /dev/null; then
echo "HOURRA !"
fi;
Result is:
Password for user postgres:
ERROR: column « my » does not exist
LINE 1: SELECT 1 FROM pg_user WHERE usename = my
^
I would avoid the quoting problem like this:
if psql -Atq -c "SELECT '#' || usename || '#' FROM pg_user" | grep -q '#'"$psql_USER"'#'
then
echo yes
fi
The psql invocation selects a list of all usernames, prefixed and suffixed with #. The grep has return code 0 if psql_USER contains one of these user names, else 1. The then branch of if is only taken if the return code of the pipeline is 0, that is, if the user exists in the database.

Shell Script: Hive query is not returning the value/result

I've the below code which I'm using to retrieve the hive result, storing it in a variable, doing the comparison and then accordingly printing the message using shell script.
count_students=`/usr/bin/hive -e 'select count(*) from student_records.fresher;'`
echo $count_students
if [ $count_students -gt 0 ]; then
echo "There are students to be grouped."
exit 1
else
echo "There are no students to be grouped."
fi
echo "Student count to check for Freshers is completed."
But the code is not returning anything i.e.:
Actual O/P:
-bash: line 2: [: -ge: unary operator expected
There are no students to be grouped.
Also the echo $count_students is not printing anything.
The hive query gives the result as:
admin$ select count(*) from student_records.fresher;
179
Not getting why the hive is not able to return the result. Bcz of that the query is prompting wrong message. Any help/ suggestion will be really helpful. Thanks to the community.

How can I disable * expansion in a script?

I have a strange problem - possibly I'm just going blind. I have this short script, which replaces the string #qry# in the here-document with a select statement in a file and then pipes it to mysql:
#!/bin/bash
if [[ "$1" == "-h" ]]
then
echo "sqljob [sqlfile] [procnm] [host] [database] [config file]"
echo " sqlfile: text file containing an SQL statement"
echo " procnm: name that will given to the new, stored procedure"
echo " host: hostname of IP address of the database server"
echo " database: the procedure will be created here"
echo " config file: default configuration file with username and password"
exit
fi
infile=$1
procnm=$2
hn=$3
pn=$4
db=$5
mycfg=$6
{
set -o noglob
sed -e "s/#qry#/$(echo $(cat $infile))/g" <<!
drop procedure if exists $procnm;
delete from jobs where jobname="$procnm";
insert into jobs
set
notes="SQL job $procnm",
jobname="$procnm",
parm_tmpl='int';
delimiter //
create procedure $procnm(vqid int)
begin
call joblogmsg(vqid,0,"$procnm","","Executing #qry#");
drop table if exists ${procnm}_res;
create table ${procnm}_res as
#qry#
end//
delimiter ;
!
} | mysql --defaults-file=$mycfg -h $hn -P $pn $db
However, when the select contains *, it expands to whatever is in the directory even though I use noglob. However, it works from the command line:
$ set -o noglob
$ ls *
What am I doing wrong?
Edit
Block Comments in a Shell Script has been suggested as a duplicate, but as you will notice, I need to expand ${procnm} in the here-doc; I just need to avoid the same happening to select *.
I suspect it is because the construct echo (cat). The echo command gets the * from the cat command and the shell in which it runs expands it. In that shell set noglob is not active.
Try leaving the echo away: /$(cat $infile)/, in the end that is the data you need; then there is no extra glob expansion by a shell.

Delimiter Warning in shell Script with psql

I get a Delimter Error in a Shell Script:
#!/bin/sh
result=`psql -d databasename -t -A <<EOF
SELECT COUNT(*) FROM schema.table
WHERE "column_name_x" = 'specific_value_x'
AND "column_name_y" = 'specific_value_y'
AND ("column_name_z" LIKE 'specific_z%' OR "column_name_za" LIKE 'specific_za%')
;`
EOF
echo $result
#EOF
The result of the Script is fine. But I get two warnings:
./filename.sh: line 13: warning: here-document at line 8 delimited by end-of-file (wanted `EOF')
./filename.sh: line 9: EOF: command not found
What is the problems here? Thank you!
You have the start of your here-doc inside of your command, but the EOF is outside of your command.
result=`psql -d databasename -t -A <<EOF
SELECT COUNT(*) FROM schema.table
WHERE "column_name_x" = 'specific_value_x'
AND "column_name_y" = 'specific_value_y'
AND ("column_name_z" LIKE 'specific_z%' OR "column_name_za" LIKE 'specific_za%')
EOF
`
The ; seems wrong here too (at least it threw an error for me).

unix shell script to check result of sql query

I have the code like this
v_use_xref_result=`sqlplus -s $UP <
Select Code_Desc
From Code_Detail
Where Code='UXLOC'
and CODE_TYPE='UXRF'
EOF`
if [ "$v_use_xref_result" == "Y" ]; then
echo "s" else
echo "n"
fi
when I query the same in sql developer I am getting the result as Y for this query Select Code_Desc From Code_Detail Where Code='UXLOC' and CODE_TYPE='UXRF' the datatype of Code_Desc is varchar
but I am unable to check in if condition. i am getting "n" as result for this script.
can anyone help me how to check it in if condition.
As written, the heredoc syntax in your script doesn't seem to be correct. Try saying:
v_use_xref_result=$(sqlplus -s $UP <<EOF
Select Code_Desc
From Code_Detail
Where Code='UXLOC'
and CODE_TYPE='UXRF'
EOF
)

Resources