Dynamické generování SQL příkazů v bashi a jejich vykonávání v db
Skočit na navigaci
Skočit na vyhledávání
- dropne vygenerované tabulky
(echo "begin;"
for i in $(seq 1 10000);
do
echo "DROP TABLE IF EXISTS xxx$i;"
done
echo "commit; " ) | psql postgres > /dev/null
- nainstaluje chybějící extenzi
#!/bin/sh
for db in `psql $port $host postgres -A -t -l -c \
"select datname, quote_literal(datname).
from pg_database.
where not datistemplate and datallowconn"`
do
BIFS=$IFS
IFS="|"
dbn=($db)
if [ -n "`psql ${dbn[$quoted]} --field-separator="|" -q -A -t -c \
"select current_catalog
where not exists(select * from pg_proc where proname = 'mtime')" `" ]; then
psql ${dbn[$quoted]} -c "create extension last_access"
fi
IFS=$BIFS
done;
jiný způsob - s využitím while:
psql postgres -A -t --field-separator=" " \
-c "copy (select 1,'Ahoj Svete', i
from generate_series(1,3) g(i))
to stdout delimiter ' '" | \
while read var1 var2 var3;
do
echo "a=$var1,b=$var2,c=$var3 ";
done
další varianta:
SQL=$(cat <<EOF SELECT datname, pg_catalog.pg_get_userbyid(d.datdba) FROM pg_database d WHERE pg_catalog.pg_get_userbyid(d.datdba) LIKE :'owner' EOF ) echo $SQL | psql postgres -q -t -A -v owner=$1 -F $'\x1f'| \ while IFS=$'\x1f' read -r a b; do echo -e "datname='$a'\towner='$b'"; done
Komplikovanější příklad COPY:
exec 3<d.csv
while : ; do
rm -f pipe
mkfifo pipe
( psql postgres < pipe )&
PGPID=$!
i=0
stop=true;
first=true;
while read -u 3 -r line ; do
if $first ; then
echo "START COPY";
echo "\COPY fo FROM stdin" > pipe
first=false
fi
echo $line > pipe
i=$(($i+1))
if [[ $i == 3 ]];
then
stop=false
break
fi
done
if [ $first = false ] ; then
echo "STOP COPY"
echo "\." > pipe
fi
rm pipe
wait $PGPID
if $stop ; then
break
fi
done
# Close fd # 3
exec 3<&-
echo "done"