Saturday, January 27, 2007

Invoking psql -c from bash for command to run in postgres

made some pretty neat bash shell scripts that interact with postgresql database just from using psql

#!/bin/sh

#variable for common things postgresql needs
PSQL="/usr/bin/psql -q -t -h 192.168.1.4 -U thein -c ";

function log_mail() {
ip="${1}";
get_country "${ip}";
timestamp="`date +"%Y-%m-%d %H:%M:%S"`";
result="`${PSQL} "set search_path=net; select ip_block_log_save('${timestamp}', '${ip}', '${country}', false);"`";
}
so this is a crusty old example, but i am doing a psql call to invoke ip_block_log_save() stored procedure, from inside a bash shell
there are other goodies there too
but the general idea is it is part of my incoming SMTP email server, and it compares the from address to a blacklist in a postgresql database.
psql -q -t -h thehost -U theuser -c "select command here";
that type of command line parameters supress the formatting of psql output;
so it is a low level basic way to have shell scripts to work with databases, by using the psql command with -c "command to run" option

No comments: