How Does Making unaccent() IMMUTABLE Speed Up Odoo Searches in PostgreSQL?

Postgres provides the unaccent extension to remove any diacritical marks from a given text. It helps in accent-insensitive searches, and something like searching for 'cafe' can also match and return café.

But when it comes to volatility classification of the unaccent() function, it can determine how Postgres optimises queries and executes them. By default, all the unaccent functions within the extension are STABLE, but this limits some optimisations in postgres. Let’s see what happens when we change that to IMMUTABLE.

1. Understanding Function Volatility

First, let’s understand the three volatility categories:

  • IMMUTABLE: Always returns the same result for the same arguments
  • STABLE: Returns the same result for the same arguments within a single SQL statement, but its result can change between statements.
  • VOLATILE: Can return different results even if they are called with the same arguments in a single statement.

These classes help postgres to determine which optimisations are safer when executing queries.

2. Why Is unaccent() Classified as STABLE?

The unaccent function uses external rule files; by default, they are unaccent.rules, which contain all the mappings of accents and letters. But these rules in this unaccent.rules file can be changed, so the function’s output is not guaranteed to remain the same throughout the lifetime of the database.

For example, if a rule changes how a particular character is translated, calling unaccent() with the same input could produce a different result. This is why unaccent functions are kept STABLE rather than IMMUTABLE. So that postgres does not make assumptions about results that could change when a rule in that file changes.

You can check the volatility of the unaccent function using the query (if the extension is created in your DB):

data_new=# select oid::regprocedure, provolatile from pg_proc where proname = 'unaccent';
             oid              | provolatile 
------------------------------+-------------
 unaccent(text)               | s
 unaccent(regdictionary,text) | s
(2 rows)

Here:

  • i represents IMMUTABLE.
  • s represents STABLE.
  • v represents VOLATILE.

3. How Does STABLE Affect Query Optimization?

When a function is marked STABLE, postgres knows that its result remains consistent within a statement. But it cannot make the same assumptions that it can make about an immutable function.

For example, consider the following query:

SELECT *
FROM account_move
WHERE unaccent(name) ILIKE unaccent('%ABC%');

The search pattern is constant, but the unaccent() function is classified as STABLE. Here, if the function were set as IMMUTABLE, postgres could check the constant expressions when planning the query instead of evaluating it during execution repeatedly.

This can help us to reduce unnecessary function calculations, especially when the same expression appears in multiple search conditions. It can also make immutable expression indexes possible, since postgres requires functions used in index expressions to be immutable.

But this does not mean that every query will automatically become faster when we set it to immutable. Any improvement will depend on the structure of the query and things postgres can apply.

4. What We Found in Odoo Source Code:

In the Odoo source code, we found that the unaccent(text) function is set to IMMUTABLE. In db.py from Odoo 19 source code:You can find:

   cr.execute("CREATE EXTENSION IF NOT EXISTS unaccent")
   # From PostgreSQL's point of view, making 'unaccent' immutable is incorrect
   # because it depends on external data - see
   # https://www.postgresql.org/message-id/flat/201012021544.oB2FiTn1041521@wwwmaster.postgresql.org#201012021544.oB2FiTn1041521@wwwmaster.postgresql.org
   # But in the case of Odoo, we consider that those data don't
   # change in the lifetime of a database. If they do change, all
   # indexes created with this function become corrupted!
   cr.execute("ALTER FUNCTION unaccent(text) IMMUTABLE")

This query “ALTER FUNCTION unaccent(text) IMMUTABLE” sets the function to be immutable, and the comment added above already mentions that Odoo considers that the unaccent.rules file doesn't change in the lifetime of a database. If they do change, all indexes created with this function become corrupted!

But that only sets the function unaccent(text) to immutable. We have another function in the extension with two arguments, unaccent(regdictionary, text); we set this one to immutable to find the performance differences below in a search query from Odoo.

5. Testing the Performance Difference in Odoo

To understand the impact, I tested an actual Odoo search query against the account_move and res_partner tables before and after setting the unaccent(regdictionary,text) function to immutable.

Before Changing the Volatility

Initially, the unaccent extension created from Odoo gives these volatilities for each function (volatility of unaccent(text) is set to IMMUTABLE in db.py in Odoo source code).

odoo_db=# select oid::regprocedure, provolatile from pg_proc where proname = 'unaccent';
                     oid                      | provolatile 
----------------------------------------------+-------------
 unaccent(text)                               | i
 unaccent_schema.unaccent(text)               | s
 unaccent_schema.unaccent(regdictionary,text) | s
(3 rows)

And I used the following search query from Odoo:

Before:
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=53380.91..53380.92 rows=1 width=8) (actual time=974.056..974.284 rows=1.00 loops=1)
   Output: count(*)
   Buffers: shared hit=11600 read=4598
   ->  Limit  (cost=42489.24..53355.90 rows=10001 width=0) (actual time=974.043..974.265 rows=0.00 loops=1)
         Buffers: shared hit=11600 read=4598
         ->  Bitmap Heap Scan on public.account_move  (cost=42489.24..136568.82 rows=86585 width=0) (actual time=974.034..974.252 rows=0.00 loops=1)
               Recheck Cond: (account_move.company_id = ANY ('{32,1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,23,24,25,26,27,28,29,30,31,33,34,35,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,90,91,92,93}'::integer[]))
               Filter: ((unaccent((account_move.name)::text) ~~* '%ABC%'::text) OR (ANY (account_move.partner_id = (hashed SubPlan 1).col1)) OR (unaccent((account_move.ref)::text) ~~* '%ABC%'::text))
               Rows Removed by Filter: 215841
               Heap Blocks: exact=10164
               Buffers: shared hit=11600 read=4598
               ->  Bitmap Index Scan on account_move__company_id_index  (cost=0.00..1718.64 rows=160581 width=0) (actual time=7.584..7.586 rows=215841.00 loops=1)
                     Index Cond: (account_move.company_id = ANY ('{32,1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,23,24,25,26,27,28,29,30,31,33,34,35,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,90,91,92,93}'::integer[]))
                     Index Searches: 1
                     Buffers: shared hit=184
               SubPlan 1
                 ->  Gather  (cost=1000.19..40724.01 rows=9902 width=4) (actual time=12.412..121.916 rows=28.00 loops=1)
                       Output: res_partner.id
                       Workers Planned: 2
                       Workers Launched: 2
                       Buffers: shared hit=1252 read=4598
                       ->  Parallel Seq Scan on public.res_partner  (cost=0.19..38733.81 rows=4126 width=4) (actual time=18.943..115.371 rows=9.33 loops=3)
                             Output: res_partner.id
                             Filter: (((res_partner.company_id = ANY ('{32,1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,23,24,25,26,27,28,29,30,31,33,34,35,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,90,91,92,93}'::integer[])) OR (res_partner.company_id IS NULL) OR (res_partner.partner_share IS NOT TRUE)) AND ((unaccent((res_partner.company_registry)::text) ~~* '%ABC%'::text) OR (unaccent((res_partner.complete_name)::text) ~~* '%ABC%'::text) OR (unaccent((res_partner.email)::text) ~~* '%ABC%'::text) OR (unaccent((res_partner.ref)::text) ~~* '%ABC%'::text) OR (unaccent((res_partner.vat)::text) ~~* '%ABC%'::text)))
                             Rows Removed by Filter: 20720
                             Buffers: shared hit=1252 read=4598
                             Worker 0:  actual time=22.105..112.560 rows=5.00 loops=1
                               Buffers: shared hit=440 read=1442
                             Worker 1:  actual time=22.825..112.514 rows=14.00 loops=1
                               Buffers: shared hit=447 read=1566
 Query Identifier: -1340181433865899140
 Planning:
   Buffers: shared hit=20
 Planning Time: 1.413 ms
 Execution Time: 974.352 ms
(35 rows)

This query was executed in 974.352 ms. The execution plan also showed:

Bitmap Heap Scan on public.account_move (using the company_id index, which returns 215,841 of the 216,057 rows, so it filters almost nothing)

Gather with Workers Planned: 2 and Workers Launched: 2 over a Parallel Seq Scan on public.res_partner.

PostgreSQL selected parallel sequential scans to evaluate the search conditions.

You can see one detail in this plan: the pattern appears as a plain constant ('%ABC%'), and the unaccented function call was already evaluated during planning time. This is because Odoo’s unaccent is declared immutable. But that is only a thin SQL wrapper, and its body is like:

SELECT unaccent_schema.unaccent('unaccent_schema.unaccent', $1)

The wrapper is IMMUTABLE, but the function inside it is still STABLE. PostgreSQL does not inline a SQL function that is declared IMMUTABLE when its body is not actually immutable, so for every row the filter has to make a call to the wrapper function. The wrapper also has the default planner cost of 100, which makes the filter look expensive to the planner.

Now, let’s change the volatility; we can set the two-argument function to immutable:

ALTER FUNCTION unaccent_schema.unaccent(regdictionary, text) IMMUTABLE;
odoo_db=# select oid::regprocedure, provolatile from pg_proc where proname = 'unaccent';
                    oid                      | provolatile
----------------------------------------------+-------------
unaccent(text)                               | i
unaccent_schema.unaccent(text)               | s
unaccent_schema.unaccent(regdictionary,text) | i
(3 rows)

Since the wrapper calls this function and it is now immutable, Postgres can inline the wrapper into the query. The filter then calls unaccent_schema.unaccent(regdictionary, ...) directly for every row, without the extra SQL function layer.

Now, let’s run the same query we used above again, and the plan looks like this:

                                                                                                                        QUERY PLAN                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=10031.28..10031.29 rows=1 width=8) (actual time=537.820..537.837 rows=1.00 loops=1)
   Output: count(*)
   Buffers: shared hit=10552 read=5256
   ->  Limit  (cost=8144.61..10006.27 rows=10001 width=0) (actual time=537.811..537.822 rows=0.00 loops=1)
         Buffers: shared hit=10552 read=5256
         ->  Seq Scan on public.account_move  (cost=8144.61..24262.18 rows=86585 width=0) (actual time=537.806..537.812 rows=0.00 loops=1)
               Filter: ((account_move.company_id = ANY ('{32,1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,23,24,25,26,27,28,29,30,31,33,34,35,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,90,91,92,93}'::integer[])) AND ((unaccent_schema.unaccent('unaccent_schema.unaccent'::regdictionary, (account_move.name)::text) ~~* '%ABC%'::text) OR (ANY (account_move.partner_id = (hashed SubPlan 1).col1)) OR (unaccent_schema.unaccent('unaccent_schema.unaccent'::regdictionary, (account_move.ref)::text) ~~* '%ABC%'::text)))
               Rows Removed by Filter: 216057
               Buffers: shared hit=10552 read=5256
               SubPlan 1
                 ->  Seq Scan on public.res_partner  (cost=0.19..8119.67 rows=9902 width=4) (actual time=5.755..137.466 rows=28.00 loops=1)
                       Output: res_partner.id
                       Filter: (((res_partner.company_id = ANY ('{32,1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,23,24,25,26,27,28,29,30,31,33,34,35,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,90,91,92,93}'::integer[])) OR (res_partner.company_id IS NULL) OR (res_partner.partner_share IS NOT TRUE)) AND ((unaccent_schema.unaccent('unaccent_schema.unaccent'::regdictionary, (res_partner.company_registry)::text) ~~* '%ABC%'::text) OR (unaccent_schema.unaccent('unaccent_schema.unaccent'::regdictionary, (res_partner.complete_name)::text) ~~* '%ABC%'::text) OR (unaccent_schema.unaccent('unaccent_schema.unaccent'::regdictionary, (res_partner.email)::text) ~~* '%ABC%'::text) OR (unaccent_schema.unaccent('unaccent_schema.unaccent'::regdictionary, (res_partner.ref)::text) ~~* '%ABC%'::text) OR (unaccent_schema.unaccent('unaccent_schema.unaccent'::regdictionary, (res_partner.vat)::text) ~~* '%ABC%'::text)))
                       Rows Removed by Filter: 62159
                       Buffers: shared hit=376 read=5256
 Query Identifier: -1340181433865899140
 Planning:
   Buffers: shared hit=19
 Planning Time: 1.169 ms
 Execution Time: 537.892 ms
(20 rows)

The same query now executes in 537.892 ms, about 1.8x faster (45% less time). Both the data and results produced are the same in the two runs we did above: all 216,057 rows in the account_move table are filtered, the subplan of res_partner gives the same 28 partners, and both have no matching rows.

Let’s see why the planner chooses serial: the wrapper function costs 100, but the inlined function has cost 1. The planner did not think using parallel workers was worth it, because that filter looked cheaper.

What actually took the time: the hashed subplan on the table res_partner finished before the account_move table scan started returning; therefore, the scan of account_move time took like 538 - 141 = 397 ms after, instead of something like 974 - 122 = 852 ms before, which is roughly 2x more faster.

What does this mean for our results?

  1. The search for scanning the tables in the query was 2x faster, as stated above. Here, each row is cheaper to filter out without the wrapper.
  2. Since we already have Odoo’s wrapper as IMMUTABLE (as it is set in the Odoo source code), those indexes in Odoo are already usable. Therefore, queries that use trigram indexes did not get changed.
  3. But one query got much slower. A Search for a selective term with ORDER BY date DESC LIMIT 80 went from 6.8 ms to 260 ms. The function itself was not slower. What happened was that the plan changed. While the wrapper was expensive (cost 100), the planner chose a bitmap scan on the trigram indexes. Once the wrapper was inlined and became cheap, the planner decided that walking the date index backwards and filtering was cheaper, assuming matches are spread evenly over time. They are not, so it read about 177,000 rows to find 435 matches.

So making the function immutable is not a guaranteed speedup. It saves work per row and allows constant folding, but it also changes the cost estimates the planner works with, and that can lead to a different plan, better or worse, depending on your data.

Changing the volatility of unaccent(regdictionary, text) to IMMUTABLE lets PostgreSQL inline Odoo's unaccent wrapper, which makes non-indexed searches such as the res_partner search noticeably faster. It does not help queries that are already served by the trigram indexes, and it can change plans for queries that combine a search with ORDER BY ... LIMIT. Test it on your own database before applying it in production.

WhatsApp