The problem is that the where
clause must match the check constraint
. As neither date_trunc()
nor current_date
are immutable they will not be "inlined" in the query meaning that those functions evaluation will only happen at query execution time, after the query planning phase, and so the planner will not know if the condition matches the check constraint
To give the planner the information it needs the query will have to be built dynamically
create or replace function select_from_invoices(
_d date
) returns setof invoices as $body$
begin
return query execute $$
select *
from invoices
where invoice_date > $1
$$
using date_trunc('month', _d)
;
end;
$body$ language plpgsql;
Now the query will only be planned after the result of date_trunc
is concatenated to the query string.
Execute it:
select *
from select_from_invoices(current_date);