Search code examples
pythonplpython

how to parameter-ize a query's WHERE clause within pl/python?


Friends:

Have been trying to parameter-ize into a query in pl/python - and am surely missing something simple here; I've tried % and $ prepends to the variable name, with no luck.

(also haven't been able to pass a result variable into the python log - but this is a diff problem! I do have the log set up - can sent literal strings to it - but have cut out lots of code for clarity here)

CREATE OR REPLACE FUNCTION footest0 (param_key integer) RETURNS text AS $$

# 1) SELECT from record based on parameter param_key:

rv = plpy.execute("SELECT name_key,address_key FROM file WHERE foreign_key = param_key)

name = rv[0]["name"]
address = rv[0]["address"]

# how to put results into the log?:
logging.info('  record: %(case)s')

$$ LANGUAGE plpythonu;

Solution

  • Use the $n notation:

    st = "SELECT name_key,address_key FROM file WHERE foreign_key = $1"
    pst = plpy.prepare(st, [ "integer" ])
    rv = plpy.execute(pst, [ param_key ])