I have a function that does some mathematical calculations. It calls another function, which is volatile. I would like to know if the calling function can be declared as either
stable, or it must necessarily be
volatile as well.
The documentation describes
IMMUTABLE indicates that the function cannot modify the database and always returns the same result when given the same argument values; that is, it does not do database lookups or otherwise use information not directly present in its argument list. [...]
This means you can do the following:
CREATE OR REPLACE FUNCTION immutablerandom() RETURNS integer LANGUAGE plpgsql IMMUTABLE AS $$ DECLARE a numeric; BEGIN a := random(); RETURN 1; END; $$;
random() is a volatile function, and
immutablerandom() fulfills the criteria of the definition of
IMMUTABLE. If this actually makes sense is a different thing - you have to discard the results of the volatile function altogether, and in practice I cannot see a case where I could use it.
If you declare the function as immutable then PostgreSQL will generally believe you. If it is not actually immutable and that causes something to break (corrupted functional indexes being an obvious example off the top of my head) then you get to keep both pieces. So yes, you can do it. But it is running with scissors.
For example, say you create a claimed-to-be-immutable function which calls the single-argument form of to_tsvector (and so is not truly immutable), and build a functional index using that function. Then if you change the setting for
default_text_search_config, your queries will stop returning the correct results until you manually rebuild the index. It won't be corrupt in the sense of crashing the database, it will just return the wrong rows.