parameterized full text search problem

From: Don Parris <parrisdc(at)gmail(dot)com>
To: psycopg(at)postgresql(dot)org
Subject: parameterized full text search problem
Date: 2013-03-13 00:47:26
Message-ID: CAJ-7yo=W+DwVLS86tJ4wCZB77vhcKo36N-YZad3veShtzMQ_2A@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: psycopg

Hi all,

I am using Python3 with psycopg2 on Kubuntu 12.10. I have an SQL query
like so:
SELECT * FROM entity WHERE to_tsvector('english', entity_name) @@
to_tsquery('english', 'steak');

I want the user to be able to pass in the search term at runtime, something
akin to:
search_term = input(Search Payee: )
cur.execute("""SELECT * FROM entity WHERE to_tsvector(%s, entity_name) @@
to_tsquery(%s, %s);""",
("english" "english", search_term))

Running the script at the command line, I get:
python3 dbconnect_test.py
Search for Payee: compare foods
Traceback (most recent call last):
File "dbconnect_test.py", line 46, in <module>
main()
File "dbconnect_test.py", line 27, in main
("english", "english", search_term))
psycopg2.ProgrammingError: syntax error in tsquery: "compare foods"

I tried this approach (from the example in the documentation, using %(str)s
in place of %s:
cur.execute("""SELECT * FROM entity WHERE to_tsvector(%(str)s, entity_name)
@@ to_tsquery(%(str)s, %(str)s);""",
{'str': "english", 'str': "english", 'str': search_term})

With this result:
Search for Payee: compare foods # I enter a search term
Traceback (most recent call last):
File "dbconnect_test.py", line 46, in <module>
main()
File "dbconnect_test.py", line 27, in main
{'str': "english", 'str': "english", 'str': search_term})
psycopg2.ProgrammingError: invalid name syntax
LINE 1: SELECT * FROM entity WHERE to_tsvector('compare foods', enti...

Clearly, I am missing something, but am not sure what. I greatly
appreciate any help I can get on this.

Thanks,
Don
--
D.C. Parris, FMP, Linux+, ESL Certificate
Minister, Security/FM Coordinator, Free Software Advocate
http://dcparris.net/
<https://www.xing.com/profile/Don_Parris><http://www.linkedin.com/in/dcparris>
GPG Key ID: F5E179BE

Responses

Browse psycopg by date

  From Date Subject
Next Message Joe Abbate 2013-03-13 01:10:19 Re: parameterized full text search problem
Previous Message Federico Di Gregorio 2013-03-12 16:54:29 Re: postgres library in Python core