Skip to content

Instantly share code, notes, and snippets.

@adrianolsk
Last active August 6, 2018 23:50
Show Gist options
  • Save adrianolsk/b1a1184bb8dcd67f34a4c2d9f2feffda to your computer and use it in GitHub Desktop.
Save adrianolsk/b1a1184bb8dcd67f34a4c2d9f2feffda to your computer and use it in GitHub Desktop.
PostgreSQL usefull scrips
--add
select
f_add_col(cast(tablename as text), 'created_at', 'timestamptz', 'now()')
from
pg_catalog.pg_tables
where
schemaname = 'public';
--drop
--select f_drop_col(cast(tablename as text), 'created_at' ) from pg_catalog.pg_tables where schemaname = 'public';
/* Good POSTGRESQL material : http://www.postgresqltutorial.com/ */
-- function to add a column
CREATE OR REPLACE function f_add_col(_tbl regclass, _col text, _type regtype, _default text)
RETURNS bool AS
$func$
BEGIN
IF EXISTS (SELECT 1 FROM pg_attribute
WHERE attrelid = _tbl
AND attname = _col
AND NOT attisdropped) THEN
RETURN FALSE;
ELSE
EXECUTE format('ALTER TABLE %s ADD COLUMN %I %s default %s', _tbl, _col, _type, _default);
RETURN TRUE;
END IF;
END
$func$ LANGUAGE plpgsql;
CREATE OR REPLACE function f_drop_col(_tbl regclass, _col text)
RETURNS bool AS
$func$
BEGIN
IF EXISTS (SELECT 1 FROM pg_attribute
WHERE attrelid = _tbl
AND attname = _col
AND NOT attisdropped) THEN
EXECUTE format('ALTER TABLE %s drop COLUMN %I ', _tbl, _col);
RETURN true;
ELSE
RETURN false;
END IF;
END
$func$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment