# 2018 October 18
#
# 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 implements regression tests for SQLite library.
#

if {![info exists testdir]} {
  set testdir [file join [file dirname [info script]] .. .. test]
} 
source [file join [file dirname [info script]] session_common.tcl]
source $testdir/tester.tcl
ifcapable !session {finish_test; return}

set testprefix sessioninvert

proc do_invert_test {tn sql} {

  forcecopy test.db test.db2
  sqlite3 db2 test.db2

  set C [changeset_from_sql $sql]

  forcecopy test.db test.db3
  sqlite3 db3 test.db3
  uplevel [list do_test $tn.1 [list compare_db db db3] {}]

  set I [sqlite3changeset_invert $C]
  sqlite3changeset_apply db $I {}
  uplevel [list do_test $tn.2 [list compare_db db db2] {}]
  
  sqlite3changeset_apply_v2 -invert db3 $C {}
  uplevel [list do_test $tn.3 [list compare_db db db3] {}]

  catch { db2 close }
  catch { db3 close }
}

do_execsql_test 1.0 {
  CREATE TABLE t1(a PRIMARY KEY, b, c);
  CREATE TABLE t2(d, e, f, PRIMARY KEY(e, f));

  INSERT INTO t1 VALUES(1, 'one', 'i');
  INSERT INTO t1 VALUES(2, 'two', 'ii');
  INSERT INTO t1 VALUES(3, 'three', 'iii');
  INSERT INTO t1 VALUES(4, 'four', 'iv');
  INSERT INTO t1 VALUES(5, 'five', 'v');
  INSERT INTO t1 VALUES(6, 'six', 'vi');

  INSERT INTO t2 SELECT * FROM t1;
}

do_invert_test 1.1 {
  INSERT INTO t1 VALUES(7, 'seven', 'vii');
}

do_invert_test 1.2 {
  DELETE FROM t1 WHERE a<4;
}

do_invert_test 1.2 {
  UPDATE t1 SET c=5;
}

do_invert_test 1.3 {
  UPDATE t1 SET b = a+1 WHERE a%2;
  DELETE FROM t2;
  INSERT INTO t1 VALUES(10, 'ten', NULL);
}

do_invert_test 1.4 {
  UPDATE t2 SET d = d-1;
}

do_execsql_test 2.0 { 
  ANALYZE;
  PRAGMA writable_schema = 1;
  DROP TABLE IF EXISTS sqlite_stat4;
  SELECT * FROM sqlite_stat1;
} {
  t2 sqlite_autoindex_t2_1 {6 1 1} 
  t1 sqlite_autoindex_t1_1 {6 1}
}

do_invert_test 2.1 {
  INSERT INTO sqlite_stat1 VALUES('t3', 'idx2', '1 2 3');
}

do_invert_test 2.2 {
  DELETE FROM sqlite_stat1;
}

do_invert_test 2.3 {
  UPDATE sqlite_stat1 SET stat = 'hello world';
}

do_test 3.0 {
  forcecopy test.db test.db2
  sqlite3 db2 test.db2
  set P [patchset_from_sql {
    INSERT INTO t2 VALUES(1, 2, 3);
    DELETE FROM t2 WHERE d = 3;
  }]

  list [catch { sqlite3changeset_apply_v2 -invert db2 $P {} } msg] $msg
} {1 SQLITE_CORRUPT}

do_test 3.1 {
  sqlite3changeset_apply_v2 db2 $P {} 
  compare_db db db2
} {}


finish_test
