drop schema if exists test cascade;
create schema test;

create table test.data(
  id serial primary key,
  time timestamptz not null default clock_timestamp(),
  object_id integer not null,
  data integer not null
);

insert into test.data(object_id, data) select 1, i from generate_series(1, 10000) i;

create unique index on test.data(object_id, time);

create function test.can_read(_object_id integer) returns boolean as $$
begin
  return true;
end $$ language plpgsql stable;

create view test.view
with (security_barrier)
as select * from test.data
where test.can_read(object_id)
;

create function test.fun(_object_id integer, _from timestamptz, _to timestamptz) returns setof bigint as $$
begin
  return query
  select sum(V1.data + V2.data)
  from test.view V1
  inner join test.view V2 using(id)
  where
  V1.object_id=$1
  and V1.time between $2 and $3
  and V2.time between $2 and $3;
end $$ language plpgsql stable;
