Sub topic 17
Defining Your Own Casts with CREATE CAST
This chapter assumes you know the three cast contexts (implicit, assignment, explicit) and that pg_cast lists the built-in casts. It also assumes you can write a simple SQL function. The examples run in psql on any recent PostgreSQL version.
When a custom cast makes sense
PostgreSQL ships with casts for its built-in types. For types you define yourself, such as enums, composites and extension types, it has no cast between them. Converting text to or from your type already works, because PostgreSQL falls back to the type's input and output functions. Other pairs fail:
ERROR: cannot cast type yesno to booleanCREATE CAST fills that gap. A cast is a catalog entry in pg_cast. It tells the parser which conversion to run and in which contexts it may run silently.
The three forms
The syntax has three variants. They differ in how the conversion is performed.
| Form | How the value is converted | Typical use |
|---|---|---|
| `WITH FUNCTION f(source)` | Calls your function | Real logic, such as mapping `'yes'` to `true` |
| `WITHOUT FUNCTION` | Reuses the bytes unchanged (binary coercible) | Two types with identical internal representation |
| `WITH INOUT` | Runs the source type's output function, then the target type's input function | Two types whose text forms are compatible |
A cast backed by a function
This is the form you will use most often. The example converts an enum to boolean.
CREATE TYPE yesno AS ENUM ('yes', 'no');
CREATE FUNCTION yesno_to_bool(yesno) RETURNS boolean
LANGUAGE sql IMMUTABLE AS $$ SELECT $1 = 'yes' $$;
CREATE CAST (yesno AS boolean) WITH FUNCTION yesno_to_bool(yesno);
SELECT 'yes'::yesno::boolean AS result;The query returns true. The function must follow these rules:
- It takes the source type as its first argument, or a type that is binary coercible to it.
- It may take a second argument of type
integer, which receives the type modifier of the target. For example, it receives 2 forvarchar(2). - It may take a third argument of type
boolean, which istruewhen the cast is explicit. - Its return type must be the target type.
Declare conversion functions IMMUTABLE when the result depends only on the input. The planner can then fold constant casts and use them in expression indexes.
Choosing the context
CREATE CAST without a clause creates an explicit-only cast. Two optional clauses widen it.
| Clause | Cast fires in |
|---|---|
| none | Explicit casts only (`CAST`, `::`) |
| `AS ASSIGNMENT` | `INSERT` and `UPDATE` targets, plus explicit casts |
| `AS IMPLICIT` | Any expression, plus assignment and explicit use |
Here is an assignment cast in the opposite direction. It lets you insert a boolean straight into a yesno column.
CREATE FUNCTION bool_to_yesno(boolean) RETURNS yesno
LANGUAGE sql IMMUTABLE STRICT AS $$
SELECT CASE WHEN $1 THEN 'yes'::yesno ELSE 'no'::yesno END
$$;
CREATE CAST (boolean AS yesno) WITH FUNCTION bool_to_yesno(boolean) AS ASSIGNMENT;
CREATE TABLE survey (answer yesno);
INSERT INTO survey VALUES (true), (false), (NULL);
SELECT answer FROM survey;STRICT makes PostgreSQL return NULL for NULL input without calling the function. Without it, the CASE would turn NULL into 'no', which is a silent data error.
Because the cast is assignment-only, SELECT true = 'yes'::yesno still fails. The comparison is an expression, not an assignment, so the cast never fires there.
Casting with INOUT
Suppose a second enum has the same labels as yesno. Neither a function nor a binary cast is a good fit, since you would have to write a mapping by hand. WITH INOUT converts through the text form instead.
CREATE TYPE answer_code AS ENUM ('yes', 'no');
CREATE CAST (yesno AS answer_code) WITH INOUT;
SELECT 'yes'::yesno::answer_code AS converted;The cast calls enum_out on the source value and enum_in on the result. If a source label has no matching label in the target, the conversion raises an error at run time. It does not fail when the cast is created, so test every label.
Binary-coercible casts
WITHOUT FUNCTION tells PostgreSQL that the two types have the same internal representation, so no work is needed. This is how text and varchar convert into each other for free. It is also the riskiest form. If the layouts differ in any way, you can crash a backend or return corrupt data, and the server cannot check this for you. Use it only for types that share an underlying implementation, such as domain-like wrappers in an extension.
Inspecting what you created
Custom casts appear in pg_cast next to the built-in ones.
SELECT castsource::regtype, casttarget::regtype, castcontext, castmethod
FROM pg_cast
WHERE castsource = 'yesno'::regtype
OR casttarget = 'yesno'::regtype
ORDER BY 1, 2;You should see three rows. castcontext shows e for explicit, a for assignment and i for implicit. castmethod shows f for function, b for binary coercible and i for I/O conversion (WITH INOUT). The automatic string casts do not appear in this catalog. They are generated on demand.
Limits and housekeeping
- One cast per pair. You cannot create a second cast for a source and target pair that already has one, and you cannot replace a built-in cast. To change a custom cast, drop it and create it again.
- Ownership. You must own the source or the target type and have
USAGEprivilege on the other. - Domains. Casts to or from a domain have no effect. PostgreSQL uses the casts of the domain's base type. Define the cast on the base type instead.
- No string casts needed. PostgreSQL already provides I/O conversion casts for every type to and from
text,varcharandchar, so do not write your own. - Dependencies. The cast depends on its function. Dropping the function fails unless you add
CASCADE, which also drops the cast.
To remove the casts from this chapter:
DROP CAST (yesno AS boolean);
DROP CAST (boolean AS yesno);
DROP CAST (yesno AS answer_code);Common mistakes
- Forgetting
STRICTor NULL handling. The conversion function runs on NULL input and may return a non-NULL value. - Making a cast implicit "for convenience." This changes resolution for the whole database, not just your query.
- Marking a function
IMMUTABLEwhen it reads a table or a setting. Cached and index-folded results then go stale. - Expecting a cast in only one direction to work in both. A cast from
AtoBsays nothing aboutBtoA.
Exercise
You create CREATE CAST (boolean AS yesno) WITH FUNCTION bool_to_yesno(boolean) AS ASSIGNMENT;. Which of these statements works: INSERT INTO survey VALUES (true); or SELECT * FROM survey WHERE answer = true;? Why?
Show answer
The INSERT works, because assigning a value to a table column is an assignment context and the cast is allowed there. The SELECT fails with an operator error such as "operator does not exist: yesno = boolean". The comparison is an ordinary expression, where only implicit casts are considered. To make it work, either write answer = true::boolean::yesno (explicit casts are always allowed) or declare the cast AS IMPLICIT, accepting the effect on operator resolution across the database.