escaping quotes in psql command for fabric script escaping quotes in psql command for fabric script shell shell

escaping quotes in psql command for fabric script


Use pipes.quote() to quote something that goes to the shell.

import pipesdef delete_tables():    the_command = "SELECT string_agg(table_name, ',') FROM information_schema.tables WHERE table_schema='public'"    run("TABLES=`psql -U db_user -d db_name $PGDB -t --command %s`" % pipes.quote(the_command))


Don't shell out for this kind of task. Use psycopg instead:

import psycopg2conn = psycopg2.connect(database='db_name', user='db_user')cur  = conn.cursor()cur.execute("SELECT string_agg(table_name, ',') FROM ...;")for record in cur:    print record


This should work without the need for any other imports:

def delete_tables():run('''psql -U db_user -d db_name $PGDB -t -c "SELECT string_agg(table_name, ',') FROM information_schema.tables WHERE table_schema='public';"''')