Last active
August 6, 2018 23:50
-
-
Save adrianolsk/b1a1184bb8dcd67f34a4c2d9f2feffda to your computer and use it in GitHub Desktop.
PostgreSQL usefull scrips
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--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/ */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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