This is basically a sola solution, but a little cleaned. It is quite different that I didn’t just want to “improve” his solution (plus, I kind of think that is rude).
The main difference is that it uses the EXECUTE format. I think this is a little cleaner, but I believe you should be on PostgresSQL 9.1 or later.
It has been tested on 9.1 and works. Note. This will result in an error if the schema name / table_name / or data_type is invalid. This may be “fixed,” but in many cases it may be the correct behavior.
CREATE OR REPLACE FUNCTION add_column(schema_name TEXT, table_name TEXT, column_name TEXT, data_type TEXT) RETURNS BOOLEAN AS $BODY$ DECLARE _tmp text; BEGIN EXECUTE format('SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema=%L AND table_name=%L AND column_name=%L', schema_name, table_name, column_name) INTO _tmp; IF _tmp IS NOT NULL THEN RAISE NOTICE 'Column % already exists in %.%', column_name, schema_name, table_name; RETURN FALSE; END IF; EXECUTE format('ALTER TABLE %I.%I ADD COLUMN %I %s;', schema_name, table_name, column_name, data_type); RAISE NOTICE 'Column % added to %.%', column_name, schema_name, table_name; RETURN TRUE; END; $BODY$ LANGUAGE 'plpgsql';
using:
select add_column('public', 'foo', 'bar', 'varchar(30)');
David S Sep 26 2018-12-12T00: 00Z
source share