Sub topic 6
Turning User Input into a `tsquery` Safely
This chapter assumes you know basic SELECT, WHERE, and PostgreSQL text-search types. You should also know how to run SQL in psql or another SQL client.
A tsquery is PostgreSQL's structured representation of a search request. You can write one directly with operators such as & for AND, | for OR, ! for NOT, and <-> for adjacent terms:
SELECT to_tsquery('english', 'database & index');Direct to_tsquery input must follow PostgreSQL's query syntax. That makes it powerful, but raw user input can cause syntax errors when it contains punctuation or incomplete operators. It can also give users more query control than your application intends to expose.
Choose a constructor for the input format
PostgreSQL provides constructors that convert ordinary user text into a tsquery:
| Constructor | Input style | Behavior |
|---|---|---|
| `plainto_tsquery` | Plain words | Combines meaningful terms with AND |
| `phraseto_tsquery` | A phrase | Requires terms in sequence |
| `websearch_to_tsquery` | Search-box syntax | Supports quotes, `OR`, and a leading minus |
Use websearch_to_tsquery for a normal search box. It accepts user-friendly input without requiring users to learn tsquery operators.
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 english argument is a text search configuration. It controls tokenization, stop words, and stemming. Use the same configuration when creating document vectors and queries. Otherwise, a document and its query might produce different lexemes.
plainto_tsquery is useful when every supplied term should be required:
SELECT plainto_tsquery('english', 'postgres indexing');It does not interpret quotes or words such as OR as special search syntax. phraseto_tsquery preserves word order and requires the terms to occur as a phrase, allowing PostgreSQL's phrase matching rules to account for stop words.
Parse once, then match
Build the query once for each search request and reuse it for filtering and ranking:
WITH parsed AS (
SELECT websearch_to_tsquery('english', $1) AS query
)
SELECT a.id,
a.title,
ts_rank(a.search, parsed.query) AS rank
FROM articles AS a
CROSS JOIN parsed
WHERE a.search @@ parsed.query
ORDER BY rank DESC
LIMIT 10;The $1 parameter is supplied by the client library as a bound parameter. Parameter binding protects the SQL statement itself from injection. The search constructor then safely interprets the value as search text.
Exercise
Which constructor is usually the safest default for a search box where users may type quotes, OR, or a leading minus?
Show answer
websearchtotsquery, because it accepts that search-box syntax without requiring raw tsquery operators.