2

I know there a lot of similar questions to this, but I haven't found one that helped me.

I am using Python and psycopg2 to interface with a PostGresQL database. Here is my code:

conn = psycopg2.connect(dbname=db_name, user=user_name)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
cursor = conn.cursor()
add_query = 'CREATE ROLE %s WITH CREATEDB LOGIN PASSWORD \'%s\''
add_data = (user_name, password)
cursor.execute(add_query, add_data)

I keep getting this error:

psycopg2.ProgrammingError: syntax error at or near "'foo'" LINE 1: CREATE ROLE 'foo' WITH CREATEDB LOGIN PASSWORD ''bar''

I thought this was an issue with escaping quotes, but I have every combination of slashes and quotes that I can think of with no luck.

1 Answer 1

3

AsIs

from psycopg2.extensions import AsIs

add_query = "CREATE ROLE %s WITH CREATEDB LOGIN PASSWORD %s"
add_data = (AsIs(user), password)

The role name is an identifier so no single quotes. It can be wrapped in double quotes if illegal characters are expected, but a bad idea otherwise.

The password is a string so let Psycopg adapt and escape it.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this will subject the role name to case folding. If you want to avoid that you need to identifier-quote it. Unfortunately psycopg2 does not offer an identifer-quoting variant of psycopg2.extensions.QuotedString so you have to write one or just manually double any double quotes.

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.