--
-- ### Foreign key checks
--

-- one-dimensional fkey
drop if exists table t1;
drop if exists table t2;

create table t1 ( primary a int not null, b int );
create table t2 ( primary c int not null, a int );
alter table t2 add foreign key fk1 ( a ) references t1 ( a );

tableinfo t2;

insert into t1 values ( 1, 22);
insert into t1 values ( 2, 33);
insert into t1 values ( 3, 44);
insert into t1 values ( 4, 55);

insert into t2 values ( 1, 1);
insert into t2 values ( 2, 2);
insert into t2 values ( 3, 3);


update t1 set b = 23 where a = 1;


select * from t2;

drop table t2;
drop table t1;


-- multidimensional fkey
create table t1 ( primary a int not null, primary  b int not null );
create table t2 ( primary c int not null, a int, b int );
alter table t2 add foreign key fk1 ( a, b ) references t1 ( a, b );

insert into t1 values ( 1, 1 );
insert into t1 values ( 1, 2 );
insert into t1 values ( 1, 3 );
insert into t1 values ( 1, 4 );
insert into t1 values ( 2, 1 );
insert into t1 values ( 2, 2 );
insert into t1 values ( 2, 3 );
insert into t1 values ( 2, 4 );

insert into t2 values ( 100, 1, 1 );
tableinfo t2;

drop foreign key fk1;
drop table t1;

tableinfo t2;
insert into t2 values ( 101, 1, 100 );
drop table t2;




-- self refering key reference checks
create table t1 ( primary a int not null, b int);

insert into t1 values ( 1, 1 );

alter table t1 add foreign key t1_fk(b) references  t1(a);

insert into t1 values ( 2, 1 );
insert into t1 values ( 3, 2 );
insert into t1 values ( 25, 2 );
insert into t1 values ( 26, 2 );
insert into t1 values ( 4, 1);
insert into t1 values ( 27, 1);

update t1 set b = 2 where b = 2;

update t1 set a = 5 where a = 4;
update t1 set a = 6 where a = 3;

select * from t1;
update t1 set b = 26 where b = 1;

select * from t1;

-- alias update
update t1 tx set b = 5 where b = 26;
select * from t1;
-- alias delete
delete from t1 tx where a = 26;
select * from t1;

delete from t1 tx where b = 2;
select * from t1;
delete from t1 tx where a = 2;
delete from t1 tx where a = 1;
delete from t1 tx where a = 27;

drop foreign key t1_fk;
delete from t1 tx where a = 5;

select * from t1;

-- check with btree on t1(b)
drop if exists table t1;

create table t1 ( primary a int not null, b int);

create btree b1 on t1(b);

insert into t1 values ( 1, 1 );

alter table t1 add foreign key t1_fk(b) references  t1(a);

insert into t1 values ( 2, 1 );
insert into t1 values ( 3, 2 );
insert into t1 values ( 25, 2 );
insert into t1 values ( 26, 2 );
insert into t1 values ( 4, 1);
insert into t1 values ( 27, 1);


update t1 set b = 2 where b = 2;

update t1 set a = 5 where a = 4;
update t1 set a = 6 where a = 3;

insert into t1 values ( 28, 26);

select * from t1;

delete from t1 where b = 26;

select * from t1;

drop table t1;



