I'm running PostgreSQL 9.4.4.
I'm new to Postgres (used to Oracle & SQL Server) so I might be doing something really silly.
I'm trying to dynamically create partitions for a table. I've got the individual parts of the code working however I can't get the function to execute the dynamic DDL statements. If I replace the execute with an insert into a log table, the statements that are generated are valid and I can run them myself but if the function attempts to execute the following error is produced:
select part_test();
ERROR: query string argument of EXECUTE is null
CONTEXT: PL/pgSQL function phil_test() line 18 at EXECUTE statement
A reproducible function is as follows:
create table harry(logged_time timestamp, id integer);
create or replace function part_test () returns void as $$
declare
rec record;
begin
for REC in SELECT 'create table if not exists '||'harry'||'_'
||to_char(date_trunc('day', my_date), 'YYYY_MON_DD')
||' (check (logged_time>=DATE'''
||to_char(date_trunc('day', my_date), 'YYYY_MON_DD')
||''' and logged_time < DATE'''
||lead(to_char(date_trunc('day', my_date), 'YYYY_MON_DD'),1)
over (order by date_trunc('day', my_date))
||''')) inherits ('||'harry'||');' STMT
FROM generate_series
( '2015-SEP-01'::timestamp
, '2015-SEP-10'::timestamp
, '1 day'::interval) my_date
LOOP
execute REC.STMT;
END LOOP;
end;
$$ LANGUAGE plpgsql;