
-- StoreProcedure {gravalogin()} Versao {02} Esquema {padrao} Descricao {Grava login}
-- -----------------------------------------------------------------------------------------------

CREATE OR REPLACE FUNCTION padrao.gravalogin(VARCHAR, VARCHAR, VARCHAR, VARCHAR)
  RETURNS bool AS
  $BODY$
  DECLARE
 	p_usuario             alias for $1;
	p_esquema             alias for $2;
	p_localhost           alias for $3;
    p_localhostuser       alias for $4;
 	v_retorna             boolean;
  
  BEGIN
        LOOP
           UPDATE padrao.login
              SET conexaoid           = pg_backend_pid(),
				  usuario             = p_usuario,
				  esquema             = p_esquema,
				  localhost           = p_localhost,
				  localhostuser       = p_localhostuser,
				  data_login          = current_timestamp
            WHERE conexaoid           = pg_backend_pid();

            EXIT  WHEN found;

            BEGIN
                INSERT INTO padrao.login
                          ( conexaoid,
						    usuario,
						    esquema,
						    localhost,
						    localhostuser,
						  	data_login )
                     VALUES(pg_backend_pid(),      
							p_usuario,               
							p_esquema,         
							p_localhost,        
							p_localhostuser,              
							current_timestamp);
                EXIT ;

            EXCEPTION
                WHEN UNIQUE_VIOLATION THEN
                    -- do nothing
                      v_retorna = false;
            END;
        END LOOP;
  
   RETURN v_retorna;
  END
  $BODY$
  LANGUAGE 'plpgsql' VOLATILE;

  