# 2025 November 11
#
# 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.
#
#***********************************************************************
#

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

forcedelete test.db2
do_execsql_test 1.0 {
  CREATE TABLE t1(x, y);
  ATTACH 'test.db2' AS aux;
  CREATE TABLE aux.t1(x, y);
}

do_faultsim_test 1.1 -faults oom* -prep {
} -body {
  execsql {
    CREATE TEMP TRIGGER tmptrig AFTER INSERT ON t1 BEGIN
      INSERT INTO aux.t1 VALUES(new.x, new.y);
    END;
  }
} -test {
  faultsim_test_result {0 {}}
  catchsql { DROP TRIGGER tmptrig }
}

do_execsql_test 2.0 {
  CREATE TEMP TRIGGER tmptrig AFTER INSERT ON t1 BEGIN
    INSERT INTO aux.t1 VALUES(new.x, new.y);
  END;
}

do_faultsim_test 2 -faults oom* -prep {
} -body {
  execsql {
    INSERT INTO t1 VALUES('x', 'y');
  }
} -test {
  faultsim_test_result {0 {}}
}

do_execsql_test 3.0.1 {
  SELECT * FROM t1;
  DELETE FROM t1;
  DELETE FROM aux.t1;
} [db eval {SELECT * FROM aux.t1}]

do_execsql_test 3.0.2 {
  CREATE TEMP TRIGGER tmptrig2 AFTER INSERT ON aux.t1 BEGIN
    INSERT INTO t1 VALUES(new.x||'2', new.y||'2');
  END;
}

do_faultsim_test 3 -faults oom* -prep {
} -body {
  execsql {
    INSERT INTO aux.t1 VALUES('aaa', 'bbb');
  }
} -test {
  faultsim_test_result {0 {}}
}

proc repeatlist {list n} {
  set ret [list]
  for {set i 0} {$i < $n} {incr i} {
    set ret [concat $ret $list]
  }
  set ret
}

do_execsql_test 3.x.1 {
  SELECT * FROM main.t1;
} [repeatlist {aaa2 bbb2} 5]

do_execsql_test 3.x.2 {
  SELECT * FROM aux.t1;
} [repeatlist {aaa bbb aaa2 bbb2} 5]

faultsim_save_and_close
do_faultsim_test 4 -faults oom* -prep {
  faultsim_restore_and_reopen
  execsql { ATTACH 'test.db2' AS aux; }
} -body {
  execsql {
    CREATE TEMP TRIGGER xyz AFTER DELETE ON main.t1 BEGIN
      DELETE FROM aux.t1 WHERE rowid=old.rowid;
    END;

    DELETE FROM t1 WHERE rowid=2;
  }
} -test {
  faultsim_test_result {0 {}} {1 {unable to open a temporary database file for storing temporary tables}}
}

faultsim_save_and_close
do_faultsim_test 5 -faults oom* -prep {
  faultsim_restore_and_reopen
  execsql { ATTACH 'test.db2' AS aux; }
} -body {
  execsql {
    CREATE TEMP TRIGGER xyz AFTER UPDATE ON aux.t1 BEGIN
      UPDATE main.t1 SET x=new.x, y=new.y WHERE rowid=new.rowid;
    END;
    UPDATE aux.t1 SET x=x||x WHERE rowid=1+abs(random() % 5);
  }
} -test {
  faultsim_test_result {0 {}} {1 {unable to open a temporary database file for storing temporary tables}}
}


finish_test
