# 2015 August 14
#
# 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.
#
#***********************************************************************
#

if {![info exists testdir]} {
  set testdir [file join [file dirname [info script]] .. .. test]
}
source $testdir/tester.tcl
set ::testprefix rbusave

do_execsql_test 1.0 {
  CREATE TABLE t1(a PRIMARY KEY, b, c) WITHOUT ROWID;
  CREATE TABLE t2(a INTEGER PRIMARY KEY, b, c);
  CREATE INDEX i1 ON t1(b);
  CREATE INDEX i2 ON t2(c, b);

  INSERT INTO t1 VALUES(1, 1, 1);
  INSERT INTO t1 VALUES(2, 2, 2);
  INSERT INTO t1 VALUES(3, 3, 3);

  INSERT INTO t2 VALUES(1, 1, 1);
  INSERT INTO t2 VALUES(2, 2, 2);
  INSERT INTO t2 VALUES(3, 3, 3);
}

do_test 1.1 {
  forcedelete test.db2
  sqlite3 db2 test.db2
  db2 eval {
    CREATE TABLE data_t1(a, b, c, rbu_control);
    INSERT INTO data_t1 VALUES(4, 4, 4, 0);
    INSERT INTO data_t1 VALUES(2, NULL, NULL, 1);
    INSERT INTO data_t1 VALUES(1, 'one', NULL, '.x.');

    CREATE TABLE data_t2(a, b, c, rbu_control);
    INSERT INTO data_t2 VALUES(4, 4, 4, 0);
    INSERT INTO data_t2 VALUES(2, NULL, NULL, 1);
    INSERT INTO data_t2 VALUES(1, 'one', NULL, '.x.');
  }
} {}

proc test_to_bak {} {
  foreach f {
    test.db test.db-wal test.db-oal test.db-journal 
    test.db2 test.db2-wal test.db2-oal test.db2-journal 
  } {
    set t [string map {test bak} $f]
    forcedelete $t
    if {[file exists $f]} { forcecopy $f $t }
  }
}

do_test 1.2 {
  test_to_bak
  sqlite3rbu rrr bak.db bak.db2
  set nStep 0
  while {[rrr step]=="SQLITE_OK"} {incr nStep}
  set res2 [rrr close]
} {SQLITE_DONE}


sqlite3rbu rbu test.db test.db2
set res "SQLITE_OK"
for {set i 1} {$res=="SQLITE_OK"} {incr i} {
  set res [rbu step]

  do_test 1.3.$i.1 {
    rbu savestate
    test_to_bak
    sqlite3rbu rrr bak.db bak.db2
    set nRem 0
    while {[rrr step]=="SQLITE_OK"} {incr nRem}
    set res2 [rrr close]
  } {SQLITE_DONE}

  do_test 1.3.$i.3 { expr $nRem+$i } [expr {$nStep + ($res=="SQLITE_DONE")}]

  do_test 1.3.$i.3 {
    sqlite3 bak bak.db
    bak eval {
      SELECT * FROM t1;
      SELECT * FROM t2;
    }
  } {1 one 1 3 3 3 4 4 4 1 one 1 3 3 3 4 4 4}

  bak close
}

do_test 1.4 { rbu close } {SQLITE_DONE}

do_execsql_test 1.5 {
  SELECT * FROM t1;
  SELECT * FROM t2;
} {1 one 1 3 3 3 4 4 4 1 one 1 3 3 3 4 4 4}

finish_test
