# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#
# This file tests the triggers of views.
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test trigger4-1.1 {
  execsql {
    create table test1(id integer primary key,a);
    create table test2(id integer,b);
    create view test as
      select test1.id as id,a as a,b as b
      from test1 join test2 on test2.id =  test1.id;
    create trigger I_test instead of insert on test
      begin
        insert into test1 (id,a) values (NEW.id,NEW.a);
        insert into test2 (id,b) values (NEW.id,NEW.b);
      end;
    insert into test values(1,2,3);
    select * from test1;
  }
} {1 2}
do_test trigger4-1.2 {
  execsql {
    select * from test2;
  }
} {1 3}
do_test trigger4-1.3 {
  db close
  sqlite db test.db
  execsql {
    insert into test values(4,5,6);
    select * from test1;
  }
} {1 2 4 5}
do_test trigger4-1.4 {
  execsql {
    select * from test2;
  }
} {1 3 4 6}

do_test trigger4-2.1 {
  execsql {
    create trigger U_test instead of update on test
      begin
        update test1 set a=NEW.a where id=NEW.id;
        update test2 set b=NEW.b where id=NEW.id;
      end;
    update test set a=22 where id=1;
    select * from test1;
  }
} {1 22 4 5}
do_test trigger4-2.2 {
  execsql {
    select * from test2;
  }
} {1 3 4 6}
do_test trigger4-2.3 {
  db close
  sqlite db test.db
  execsql {
    update test set b=66 where id=4;
    select * from test1;
  }
} {1 22 4 5}
do_test trigger4-2.4 {
  execsql {
    select * from test2;
  }
} {1 3 4 66}

do_test trigger4-3.1 {
  catchsql {
    drop table test2;
    insert into test values(7,8,9);
  }
} {1 {no such table: main.test2}}
do_test trigger4-3.2 {
  db close
  sqlite db test.db
  catchsql {
    insert into test values(7,8,9);
  }
} {1 {no such table: main.test2}}
do_test trigger4-3.3 {
  catchsql {
    update test set a=222 where id=1;
  }
} {1 {no such table: main.test2}}
do_test trigger4-3.4 {
  execsql {
    select * from test1;
  }
} {1 22 4 5}
do_test trigger4-3.5 {
  execsql {
    create table test2(id,b);
    insert into test values(7,8,9);
    select * from test1;
  }
} {1 22 4 5 7 8}
do_test trigger4-3.6 {
  execsql {
    select * from test2;
  }
} {7 9}
do_test trigger4-3.7 {
  db close
  sqlite db test.db
  execsql {
    update test set b=99 where id=7;
    select * from test2;
  }
} {7 99}

integrity_check trigger4-4.1

finish_test
