Sub topic 11
Inspecting pg_cast
This chapter assumes you know the three cast contexts (implicit, assignment, explicit) from the earlier chapter and can run queries in psql. Here you will read the catalog that records them, pg_cast, and learn which conversions it does not list.
What pg_cast stores
pg_cast is a system catalog with one row per registered conversion between two types. Both built-in casts and casts created with CREATE CAST appear in it. The columns that matter for inspection are:
| Column | Meaning |
|---|---|
| `castsource` | OID of the source type |
| `casttarget` | OID of the target type |
| `castfunc` | OID of the function that performs the conversion, or 0 if no function is needed |
| `castcontext` | `i` implicit, `a` assignment, `e` explicit only |
| `castmethod` | `f` uses a function, `i` uses I/O conversion, `b` is binary coercible |
The type columns hold OIDs, which are unreadable. Casting them to regtype prints type names, and casting castfunc to regproc or regprocedure prints function names.
Reading a single cast
The query below looks up two casts out of integer.
SELECT castsource::regtype, casttarget::regtype, castcontext
FROM pg_cast
WHERE castsource = 'int4'::regtype
AND casttarget IN ('int8'::regtype, 'int2'::regtype);integer to bigint has context i, so it can happen implicitly in any expression. integer to smallint has context a. It is allowed in an INSERT or UPDATE assignment and in an explicit cast, but never silently inside an expression. The reason is that narrowing can overflow.
To make the output easier to read, decode the one-letter codes:
SELECT castsource::regtype AS source,
casttarget::regtype AS target,
castfunc::regproc AS func,
CASE castcontext WHEN 'i' THEN 'implicit'
WHEN 'a' THEN 'assignment'
WHEN 'e' THEN 'explicit' END AS context,
CASE castmethod WHEN 'f' THEN 'function'
WHEN 'i' THEN 'I/O'
WHEN 'b' THEN 'binary' END AS method
FROM pg_cast
WHERE castsource = 'int4'::regtype
ORDER BY target::text;The ORDER BY is there because the catalog has no guaranteed row order. Expect rows for bigint, smallint, numeric, real and double precision. Your server version may add a few more.
In psql, \dC integer prints a similar summary. It lists casts where the pattern matches the source or the target type.
The three methods
castmethod tells you how the value is actually converted.
- Function (
f): PostgreSQL calls the function incastfunc.integertobigintworks this way. - Binary coercible (
b): the two types share the same physical representation, so no work is done.texttovarcharis an example. So isintegertooid. - I/O conversion (
i): the value is written out with the source type's output function and read back with the target type's input function. Built-in rows with this method are rare, because PostgreSQL provides I/O conversions automatically (see the next section).
Some cast functions take more than one argument. A function with the signature (source, integer, boolean) receives the target type modifier and an "is explicit" flag. This is how length and precision work. Inspect the cast from varchar to varchar:
SELECT castfunc::regprocedure, castcontext
FROM pg_cast
WHERE castsource = 'varchar'::regtype
AND casttarget = 'varchar'::regtype;The function takes the length and the explicit flag. When the flag is true, it truncates the string silently. When the flag is false, as in an assignment, it raises value too long for type character varying(2). That is the difference between the two varchar(2) statements in the earlier chapter on text conversions.
Casts that are not in pg_cast
A missing row does not mean a conversion is impossible. pg_cast has no entry for text to integer, yet '42'::integer works. Check this directly:
SELECT count(*) AS rows_found
FROM pg_cast
WHERE castsource = 'text'::regtype
AND casttarget = 'int4'::regtype;The count is 0. PostgreSQL applies automatic I/O conversion casts whenever a string type is involved, and these are never stored in the catalog. The rules are:
- To a string type (
text,varchar,char): allowed from any type, at assignment level. SoINSERT INTO t(text_col) VALUES (42)works, butSELECT 42 || 'x'finds no operator by implicit conversion alone. - From a string type: allowed from any string type to any type, but only as an explicit cast. This is why
'3.7'::integercalls the integer input function and fails withinvalid input syntax for type integer.
Other automatic casts are also absent from the catalog:
- Array casts, such as
text[]toint[], work whenever the element types have a cast. The context is the element cast's context. - A domain casts to and from its base type.
- Casts between composite types are not automatic.
Useful catalog queries
What can an integer become implicitly? Filter on context i:
SELECT casttarget::regtype AS reachable_implicitly
FROM pg_cast
WHERE castsource = 'int4'::regtype
AND castcontext = 'i'
ORDER BY 1::text;Operator resolution relies on this list when it looks for a way to make integer + numeric work.
Which casts are explicit-only? These are the conversions PostgreSQL will not apply without your say-so:
SELECT castsource::regtype AS source, casttarget::regtype AS target
FROM pg_cast
WHERE castcontext = 'e'
AND castsource = 'int4'::regtype
ORDER BY target::text;integer to boolean appears here. SELECT 1::boolean works, but WHERE 1 does not, because the cast is never applied implicitly.
Which casts use a function with extra arguments? The pg_proc catalog records the argument count:
SELECT c.castsource::regtype, c.casttarget::regtype, p.pronargs
FROM pg_cast c
JOIN pg_proc p ON p.oid = c.castfunc
WHERE p.pronargs > 1
ORDER BY 1::text, 2::text
LIMIT 10;Gotchas
- Casts do not chain. If
Aconverts toBandBconverts toC, PostgreSQL does not combine them to go fromAtoC. This is why'3.7'::numeric::integerneeds two steps while'3.7'::integerfails. The second form asks for one I/O conversion straight tointeger. - The catalog describes the server you are connected to. Extensions add casts (for example,
hstoretojsonb). Two databases can give different answers. - Changing a cast's context changes query meaning. Making a cast implicit can make existing queries ambiguous or can silently change which operator they use. You should be cautious about doing this with
CREATE CAST ... AS IMPLICIT. The final chapter covers this. castfunc = 0means different things. With methodb, no function is needed. With methodi, PostgreSQL uses the I/O functions. Readcastmethodbefore drawing conclusions.
Exercise
A query SELECT * FROM orders WHERE total = '10.5'::text fails with "operator does not exist: numeric = text". You search pg_cast for a row with castsource = 'text' and casttarget = 'numeric' and find none. Does that mean '10.5'::numeric is impossible? Which context applies to the I/O conversion from text, and what is the simplest fix for the query?
Show answer
No. A missing row only means there is no stored cast. PostgreSQL provides an automatic I/O conversion from any string type to any other type, so '10.5'::numeric works. That conversion is allowed only as an explicit cast, never implicitly or on assignment, so the comparison of numeric with text finds no operator. The simplest fix is to write the literal without the ::text annotation (total = '10.5') so it is resolved as an untyped literal, or to cast it explicitly with total = '10.5'::numeric.
Exercise
Write a query that lists every target type that smallint (int2) can reach in an implicit cast, with the name of the cast function.
Show answer
SELECT casttarget::regtype, castfunc::regproc FROM pg_cast WHERE castsource = 'int2'::regtype AND castcontext = 'i' ORDER BY casttarget::text;