An interesting error that may happen in PostgreSQL when using prepared statements is:
ERROR: cached plan must not change result type
This may happen when:
- A prepared statement is prepared on the server
- The tables structure is changed in a way that the result of the prepared statement will change
- Prepared statement is executed
Let’s try to reproduce it:
CREATE TABLE phonebook(phone INT);
PREPARE prepsel (INT) AS SELECT * FROM phonebook WHERE phone = $1;
EXECUTE prepsel(1); --all OK here
ALTER TABLE phonebook ADD COLUMN a INT;
EXECUTE prepsel(1);
ERROR: cached plan must NOT CHANGE RESULT TYPE
The possible solution are:
- Re-create the statement, so it will use up-to-date table definition
- Stop your application or cause it to drop the database connection otherwise. Prepared statements are allocated per-session.
- Change the prepared statement to use minimum columns used, e.g. change SELECT * to SELECT id. This way, only if “id” column changes your statement will become invalid.