create function createPartitionIfNotExists(forDate date) returns void
as $body$
declare monthStart date := date_trunc('month', forDate);
declare monthEndExclusive date := monthStart + interval '1 month';
declare tableName text := 'mytable_' || to_char(forDate, 'YYYYmm');
begin
if to_regclass(tableName) is null then
execute format('create table %I partition of myTable_master for values from (%L) to (%L)', tableName, monthStart, monthEndExclusive);
execute format('create unique index on %I (forDate, key2)', tableName);
end if;
end;
$body$ language plpgsql;