Question

I want to do exactly what cursor.mogrify does, but in a production appropriate way.

I'm updating some legacy Python code that builds queries by concatenating strings. I need to change this to escape safely.

The queries are long and built on a different server than they are run, so the normal process of using cursor.execute to escape is unattractive for both code clarity and practical viability reasons.

I would use mogrify, but I understand that it is intended for debugging purposes only.

I've looked around and can't seem to find a good answer to this. What do you suggest?

Was it helpful?

Solution

Don't use a tuple. Use a dictionary

d = {'p1': val1, 'p2': val2}
cur.execute("""
    select *
    from t
    where col1 = %(p1)s and col2 = %(p2)s
    """, d
)

If there are optional parameters pass then as null

d = {'p1': None, 'p2': val2}
cur.execute("""
    select *
    from t
    where
        (%(p1)s is null or col1 = %(p1)s)
        and
        (%(p2)s is null or col2 = %(p2)s)
    """, d
)

Establish an ssh connection to the server and connect through it.

ssh -L 5432:localhost:5432 remotehost.com
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top