0

I have this assignment in plpythonu in PostgreSQL function:

result=plpy.execute("select  value from table  where doctitle like '%%%s%%'"%projectname)
if result:
    final = result[0]["value"]

The query can return 1 text result or nothing.

The issue is that if the query returned nothing the if result: condition is still true (Cuz it contains the value column)... I want the assignment to final happen only if there is actual value in value column. How do I check for that?

1
  • The cursor does not return the column header , but it does return an empty array ( list i think) so this will always be true. Use count len instead Commented Mar 28, 2017 at 11:59

1 Answer 1

1

The result object emulates a list or dictionary object. Check its length:

if len(result) > 0:

But your test should work as an empty list or dictionary evaluates as False:

create or replace function p()
returns boolean as $$

result = plpy.execute('select 1 as i where false')
if result: return True
else: return False

$$ language plpythonu;

Returns false:

select p();
 p 
---
 f

Pass the parameters to execute in instead of substitute yourself. Otherwise you will vulnerable to SQL injection:

query = """
    select value
    from table
    where doctitle like format('%%%s%%', $1)
"""
plan = plpy.prepare(query, ["text"])
result = plpy.execute(plan, [_text_parameter])
if result:
    final = result[0]["value"]

https://www.postgresql.org/docs/current/static/plpython-database.html

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

Comments

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.