--
-- ### Advanced inner join index check
-- 

drop if exists table car;
drop if exists table cartype;
drop if exists table part;
drop if exists table damage;

create table car ( cid int not null, tid int, carname string(20));
create primary index on car(cid);
create index car_i1 on car(tid);

create table cartype ( tid int not null, typename string(20));
create primary index on cartype(tid);
create index cartype_i1 on cartype(typename);

create table part ( pid int not null, partname string(20));
create primary index on part(pid);
create index part_i1 on part(partname);

create table damage ( did int not null, ts datetime, pid int, cid int); 
create primary index on damage(did);
create index damage_i1 on damage(pid, cid);

insert into car values ( 1, 1, 'mycar');
insert into car values ( 2, 1, 'yaurcar');

insert into cartype values ( 1, 'X-Type');
insert into cartype values ( 2, 'Y-Type');

insert into part values ( 1, 'wheel');
insert into part values ( 2, 'gear');
insert into part values ( 3, 'engine');

insert into damage values ( 1, '01.01.2020 12:45:00', 3, 1);


drop if exists view damageview;
create view damageview as
select
d.ts as ts,
ct.typename as typename,
p.partname as partname
from cartype ct 
inner join part p -- new : join can be without condition 
inner join car c on c.tid = ct.tid
inner join damage d on d.pid = p.pid and d.cid = c.cid;

-- index damage_i1 should be used
plan select * from damageview where typename = 'X-Type' and partname = 'engine';
