Sub topic 6
Turning user input into a tsquery safely
This chapter assumes you can write basic SQL, know that to_tsvector turns text into lexemes, and have seen to_tsquery and the @@ operator. It covers how to feed text typed by a user into a search query without errors or surprises.
Why `to_tsquery` is the wrong default for user input
to_tsquery expects text that is already valid tsquery syntax. Lexemes must be joined by operators such as &, |, ! and <->. A search box does not give you that. A user types full text search, and the parser rejects it:
SELECT to_tsquery('english', 'full text search');
-- ERROR: syntax error in tsquery: "full text search"Other inputs fail too: a lone &, an unbalanced parenthesis, a trailing !, or a stray apostrophe. If your application passes raw input to to_tsquery, any of these becomes a database error and a failed request.
This is a separate problem from SQL injection. Always pass the search string as a bound parameter, never by concatenating it into the SQL text. Even with a bound parameter, the string still has to be valid tsquery syntax, and that is the part this chapter handles.
PostgreSQL has three constructors that accept arbitrary text. None of them raise syntax errors for odd punctuation.
The three safe constructors
SELECT
websearch_to_tsquery('english', 'postgres "full text" -mysql') AS web_query,
plainto_tsquery('english', 'full text search') AS plain_query,
phraseto_tsquery('english', 'full text search') AS phrase_query;The result is:
| Column | Value |
|---|---|
| `web_query` | `'postgr' & 'full' <-> 'text' & !'mysql'` |
| `plain_query` | `'full' & 'text' & 'search'` |
| `phrase_query` | `'full' <-> 'text' <-> 'search'` |
All three run the text through the configuration you name, so the stemming and stop-word removal match what to_tsvector did to your documents. Here postgres became postgr.
| Function | Operators in the input | Result | Column |
|---|---|---|---|
| `plainto_tsquery` | Ignored as punctuation | All terms joined with `&` | |
| `phraseto_tsquery` | Ignored as punctuation | All terms joined with `<->` (adjacent) | |
| `websearch_to_tsquery` | Quotes, `or`, and a leading `-` are understood | Mix of `&`, ` | `, `<->` and `!` |
phraseto_tsquery needs PostgreSQL 9.6 or later. websearch_to_tsquery needs PostgreSQL 11 or later.
`plainto_tsquery`
Use this when you want "every word must appear" and nothing more. Operator characters in the input are discarded:
SELECT plainto_tsquery('english', 'fox & dog | !cat');
-- 'fox' & 'dog' & 'cat'Notice that !cat lost its negation. A user who types a minus sign or an exclamation mark will not get an exclusion. This is safe, but it gives no control over the query.
`phraseto_tsquery`
Use this when the whole input must appear as a phrase. The <-> operator means "followed by the next lexeme at the next position". Stop words are dropped, but the gap they leave is counted, so phraseto_tsquery('english', 'quick the fox') produces 'quick' <2> 'fox'.
`websearch_to_tsquery`
This is the best fit for a search box, because it mimics the syntax people already know from web search engines:
- Unquoted words are ANDed.
"quoted text"becomes a phrase (<->).orbetween words becomes|.- A leading
-before a word or quoted phrase becomes!.
SELECT websearch_to_tsquery('english', 'cat or dog -"hot dog"');
-- ('cat' | 'dog') & !( 'hot' <-> 'dog' )The exact parenthesization PostgreSQL prints can differ from this sketch. What matters is the structure: or has lower precedence than the implicit AND.
Any other punctuation is ignored, and unbalanced quotes do not cause an error. Prefer this function unless you have a specific reason to use another.
Edge cases to handle
Stop-word-only and empty input
A query like the contains only a stop word, so nothing is left to search for:
SELECT websearch_to_tsquery('english', 'the');
-- NOTICE: text-search query contains only stop words or doesn't contain lexemes, ignored
-- (empty tsquery)An empty tsquery matches no documents, so WHERE search @@ query returns zero rows. That is usually what you want, but the NOTICE is emitted on every call. In an application, check for blank input before querying, and decide how to present "no results" for stop-word-only input.
Prefix matching for search-as-you-type
None of the three safe constructors support the prefix operator :*. If you want full tex to match full text, you must build the query yourself. Sanitize first, then call to_tsquery:
SELECT to_tsquery('english', string_agg(w || ':*', ' & ')) AS query
FROM regexp_split_to_table('full tex', '[^[:alnum:]]+') AS w
WHERE w <> '';
-- 'full':* & 'tex':*The regular expression splits the input on anything that is not a letter or digit, so operator characters can never reach to_tsquery. If the input has no words, string_agg returns NULL, to_tsquery returns NULL, and @@ NULL matches nothing.
Do not skip the sanitizing step. Appending :* to raw input brings back the syntax errors from the start of the chapter.
Configuration mismatch
The configuration you pass to the query constructor must match the one used to build the stored tsvector. If the document side used english and the query side used simple, the lexemes differ (postgr against postgres) and matches silently disappear. Treat the configuration name as part of the data contract.
Putting it together
This query reuses the articles table with its generated, indexed search column. A prepared statement keeps the user's text as a parameter:
PREPARE search_articles(text) AS
SELECT a.id,
a.title,
ts_rank(a.search, q.query) AS rank
FROM articles AS a,
websearch_to_tsquery('english', $1) AS q(query)
WHERE a.search @@ q.query
ORDER BY rank DESC
LIMIT 10;
EXECUTE search_articles('postgres "full text" -mysql');The constructor appears in the FROM clause, so it is evaluated once and the result is shared by the WHERE and SELECT clauses.
Common mistakes
- Mixing configurations. Using
englishfor documents andsimplefor queries (or the reverse) causes silent misses. - Expecting
-to work inplainto_tsquery. Onlywebsearch_to_tsqueryturns it into a negation. - Expecting prefix matching from
websearch_to_tsquery. It has no:*support, so build that query separately. - Forgetting empty queries. A stop-word-only search returns nothing and emits a NOTICE. Handle it in the application.
Exercise
A user types fast "query plan" -mysql into your search box, and your code runs to_tsquery('english', $1). What happens, and which single change fixes it while keeping the quoted phrase and the exclusion working?
Show answer
to_tsquery raises a syntax error, because the input is not valid tsquery syntax (the words have no operators between them and the quotes and minus are not recognized). Replace it with websearch_to_tsquery('english', $1). It treats "query plan" as the phrase 'queri' <-> 'plan', turns -mysql into !'mysql', and ANDs fast with the rest.
Exercise
You want postg typed in a search box to match documents containing postgres. Why can't you use websearch_to_tsquery alone, and how do you build the query safely?
Show answer
websearch_to_tsquery has no prefix operator. Split the input on non-alphanumeric characters, append :* to each word, join the words with & , and pass the result to to_tsquery. Splitting on non-alphanumerics removes any operator characters, so the final string is always valid tsquery syntax.