--atualiza todas sequencias do banco
CREATE OR REPLACE FUNCTION updatesequences() 
RETURNS bool as $BODY$
/**
  NAME: updateSequences
  PURPOSE: Atualizar todas as sequences do banco para os valores de acordo com a
  tabela que gerenciam, fazendo SELECT MAX(coluna_gerenciada) FROM tabela.

  REVISIONS:
  Ver       Date       Author            Description
  --------- ---------- ----------------- ------------------------------------
  1.0       09/07/2011 Alex Smith        1. Função criada.
*/
DECLARE
    v_row RECORD;
BEGIN
    FOR v_row IN SELECT DISTINCT 'SELECT setval(''' || REGEXP_REPLACE(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '(^.*''([^'']*)[''].*$)',E'\\2') || ''', COALESCE((SELECT MAX(' || a.attname || ') FROM ' || n.nspname || '.' || c.relname || '), 1));' AS sqlToRun
                   FROM pg_catalog.pg_attribute a
             INNER JOIN pg_catalog.pg_attrdef d
                     ON d.adrelid = a.attrelid
                    AND d.adnum = a.attnum
                    AND a.atthasdef
             INNER JOIN pg_class c
                     ON a.attrelid = c.oid
              LEFT JOIN pg_catalog.pg_namespace n
                     ON n.oid = c.relnamespace
                  WHERE a.attnum > 0
                    AND NOT a.attisdropped
                    AND a.attislocal -- somente campos nao herdados
                    AND d.adsrc like '%nextval%' AND atttypid <> 1043 --somente campos que não são string
               ORDER BY 1
    LOOP
        RAISE NOTICE '%', v_row.sqlToRun;
        EXECUTE v_row.sqlToRun;
    END LOOP;

    RETURN TRUE;
END;
 $BODY$ language plpgsql;
