Re: add column if doesn't exist

From: Chris Browne <cbbrowne(at)acm(dot)org>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: add column if doesn't exist
Date: 2005-09-27 13:34:07
Message-ID: 60d5muk52o.fsf@dba2.int.libertyrms.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

bmetcalf(at)nortel(dot)com ("Brandon Metcalf") writes:

> p == peter_e(at)gmx(dot)net writes:
>
> p> Brandon Metcalf wrote:
> p> > Is there a way to check for the existence of a column in a table
> p> > other than, say, doing a SELECT on that column name and checking the
> p> > output?
>
> p> SELECT * FROM information_schema.columns;
>
> p> Customize to taste.
>
>
> Yes, that's what I'm looking for. Thanks.
>
> Now, is there a way to mix PostgreSQL commands and SQL and do
> something like
>
> ALTER TABLE foo ADD COLUMN bar WHERE EXISTS(SELECT * FROM
> information_schema.columns WHERE ...)
>
> ?

I set up a stored procedure to do this for Slony-I... Replace
@NAMESPACE@ with your favorite namespace, and slon_quote_brute can
likely be treated as an identity function unless you use silly
namespace names :-).

create or replace function @NAMESPACE(at)(dot)add_missing_table_field (text, text, text, text)
returns bool as '
DECLARE
p_namespace alias for $1;
p_table alias for $2;
p_field alias for $3;
p_type alias for $4;
v_row record;
v_query text;
BEGIN
select 1 into v_row from pg_namespace n, pg_class c, pg_attribute a
where @NAMESPACE(at)(dot)slon_quote_brute(n.nspname) = p_namespace and
c.relnamespace = n.oid and
@NAMESPACE(at)(dot)slon_quote_brute(c.relname) = p_table and
a.attrelid = c.oid and
@NAMESPACE(at)(dot)slon_quote_brute(a.attname) = p_field;
if not found then
raise notice ''Upgrade table %.% - add field %'', p_namespace, p_table, p_field;
v_query := ''alter table '' || p_namespace || ''.'' || p_table || '' add column '';
v_query := v_query || p_field || '' '' || p_type || '';'';
execute v_query;
return ''t'';
else
return ''f'';
end if;
END;' language plpgsql;

comment on function @NAMESPACE(at)(dot)add_missing_table_field (text, text, text, text)
is 'Add a column of a given type to a table if it is missing';

--
output = ("cbbrowne" "@" "ntlug.org")
http://cbbrowne.com/info/sgml.html
"The surest sign that intelligent life exists elsewhere in the
universe is that it has never tried to contact us."
-- Calvin and Hobbes

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Daryl Richter 2005-09-27 14:02:16 Re: Updating cidr column with network operator
Previous Message Daryl Richter 2005-09-27 13:24:06 Re: how to do 'deep queries'?