I'm sure someone has asked this question before but I wasn't able to find it by searching around. So at least if it gets marked as a duplicate, maybe it'll be easier to find here. The Postgres docs have not helped me.
I have the following SQL:
create table foobar(col1 bool);
create or replace function foo(tablename varchar) returns void as $func$
begin
alter table tablename add column if not exists bar boolean;
end;
$func$ language plpgsql;
select foo('foobar');
What I expect to happen:
- Create a table foobar with boolean column col1
- Create a function foo which adds a boolean column bar to specified table
- Run function to add this column to table foobar
What actually happens, is that the first two SQL statements are executed successfully but the third fails:
ERROR: relation "tablename" does not exist
My IDE is telling me that this should be fine. I have fussed with this for a while and have not been able to come up with a way to make this cooperate except by using format() string replacement:
create or replace function foo(tablename varchar) returns void as $func$
begin
execute(format('alter table %I add column if not exists bar boolean;', tablename));
end;
$func$ language plpgsql;
Is there really no other way of doing this?