Skip to content

Instantly share code, notes, and snippets.

@sylvainv
sylvainv / pg-update-sequences.sql
Last active May 23, 2017 03:04
Update all PostgreSQL sequences to the max id.
DO $$
DECLARE r pg_catalog.pg_class%rowtype;
DECLARE _max_id int;
DECLARE _table_name text;
DECLARE _column_name text;
DECLARE _result int;
BEGIN
FOR r IN
select * from pg_catalog.pg_class where relkind = 'S'
LOOP
@sylvainv
sylvainv / pg_record_timestamps.sql
Last active August 8, 2020 15:07
Records timestamps on insert/update helper for PostgreSQL
CREATE OR REPLACE FUNCTION add_timestamps_to_table(_table text, _type text) RETURNS void AS $$
BEGIN
EXECUTE format('ALTER TABLE %I ADD COLUMN IF NOT EXISTS created_at %s', _table, _type);
EXECUTE format('ALTER TABLE %I ADD COLUMN IF NOT EXISTS updated_at %s', _table, _type);
END;
$$ LANGUAGE 'plpgsql';
CREATE OR REPLACE FUNCTION set_timestamps_not_null_on_table(_table text) RETURNS void AS $$
BEGIN
EXECUTE format('ALTER TABLE %I ALTER COLUMN created_at SET NOT NULL', _table);
AUT
BEL
BGR
CYP
CZE
DEU
DNK
ESP
EST
FIN