Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save edgarogh/f4baa3b29d34f0272f61b99959977f93 to your computer and use it in GitHub Desktop.
Save edgarogh/f4baa3b29d34f0272f61b99959977f93 to your computer and use it in GitHub Desktop.
A PostrgeSQL function to define a materialized view column as `not null`.
create or replace function alter_materialized_view_alter_column_set_not_null(mv regclass, col_name text, not_null bool)
returns setof bool
returns null on null input
security definer
language sql
as $$
with to_update as (
select
attrelid as attrelid_u, attnum as attnum_u
from pg_catalog.pg_attribute as attr
left outer join pg_catalog.pg_type as tp on tp.typelem = attr.atttypid
where
attr.attrelid = mv::oid and
attr.attname = col_name and
not attr.attisdropped and
(tp.typanalyze is null or cast(tp.typanalyze as text) = 'array_typanalyze')
and attr.attnum > 0
)
update pg_catalog.pg_attribute
set attnotnull = not_null
from to_update t
where attrelid_u = attrelid and attnum_u = attnum
returning attnotnull
$$
;
-- Aknowledgment : https://dba.stackexchange.com/a/255798

Usage

-- Set a column as non-nullable
select alter_materialized_view_alter_column_set_not_null('my_materialized_view', 'my_column', true);

Note on permissions

Because modifying pg_catalog.pg_attribute requires superuser, but making a column's nullability is something a non-superuser may want to do, the function is defined with security definer and should be created as superuser. security definer works a bit like the setuid bit on Unix, it makes the function run with its definer's permissions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment