--
-- views_by_type__record_view/3
--
create or replace function views_by_type__record_view(
  p_object_id integer,
  p_viewer_id integer,
  p_view_type character varying
) returns int4 as $$

DECLARE
    v_views     views_views.views_count%TYPE;
BEGIN 
    select views_count into v_views from views_by_type where object_id = p_object_id and viewer_id = p_viewer_id and view_type = p_view_type;

    if v_views is null then 
        INSERT into views_by_type(object_id,viewer_id,view_type) 
        VALUES (p_object_id, p_viewer_id,p_view_type);
        v_views := 0;
    else
        UPDATE views_by_type
           SET views_count = views_count + 1, last_viewed = now(), view_type = p_view_type
         WHERE object_id = p_object_id
           and viewer_id = p_viewer_id
           and view_type = p_view_type;
    end if;

    return v_views + 1;
END;
$$ language plpgsql;