0

How do I properly quote this string this postgres sql syntax within my python script which uses psycopg2's cur.execute ("SELECT .. ")

Postgres sql:

SELECT 'ALTER TABLE RENAME ' || tablename || ' TO ' || 
  REGEXP_REPLACE ( tablename, '_foo$', '_bar' ) || ';'
FROM pg_tables
WHERE tablename LIKE '%_foo';

Within my python script:

  cur.execute("SELECT 'ALTER TABLE RENAME ' || tablename || ' TO ' ||
                REGEXP_REPLACE ( tablename, '_foo$', '_bar' ) || ';'
                FROM pg_tables
                WHERE tablename LIKE '%_foo'")

1 Answer 1

1

Simply, add line breaks:

cur.execute("SELECT 'ALTER TABLE RENAME ' || tablename || ' TO ' || \
             REGEXP_REPLACE ( tablename, '_foo$', '_bar' ) || ';' \
             FROM pg_tables \
             WHERE tablename LIKE '%_foo'")
Sign up to request clarification or add additional context in comments.

1 Comment

Better yet, use triple quotes (""") to avoid backslash escapes for multiline strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.