# 2018 December 15
#
# 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.  The
# focus of this file is testing the operation of the library in
# "PRAGMA journal_mode=WAL2" mode.
#

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

set testprefix wal2lock
ifcapable !wal {finish_test ; return }

db close
testvfs tvfs 
sqlite3 db test.db -vfs tvfs

do_execsql_test 1.0 {
  PRAGMA journal_mode = wal2;
  CREATE TABLE y1(y, yy);
  CREATE INDEX y1y ON y1(y);
  CREATE INDEX y1yy ON y1(yy);
  INSERT INTO y1 VALUES(1, 2), (3, 4), (5, 6);
} {wal2}

tvfs script vfs_callback
tvfs filter xShmLock

set ::lock [list]
proc vfs_callback {func file name lock} {
  lappend ::lock $lock
  return SQLITE_OK
}

do_execsql_test 1.1.1 {
  SELECT * FROM y1
} {1 2 3 4 5 6}
do_test 1.1.2 {
  set ::lock
} {{4 1 lock shared} {4 1 unlock shared}}

set ::bFirst 1
proc vfs_callback {func file name lock} {
  if {$::bFirst} {
    set ::bFirst 0
    return SQLITE_BUSY
  }
  return SQLITE_OK
}
do_execsql_test 1.2 {
  SELECT * FROM y1
} {1 2 3 4 5 6}

set ::bFirst 1
proc vfs_callback {func file name lock} {
  if {$::bFirst} {
    set ::bFirst 0
    return SQLITE_IOERR
  }
  return SQLITE_OK
}
do_catchsql_test 1.3 {
  SELECT * FROM y1
} {1 {disk I/O error}}

puts "# Warning: This next test case causes SQLite to call xSleep(1) 100 times."
puts "# Normally this equates to a delay of roughly 10 seconds, but if SQLite"
puts "# is built on unix without HAVE_USLEEP defined, it may be much longer."
proc vfs_callback {func file name lock} { return SQLITE_BUSY }
do_catchsql_test 1.4 {
  SELECT * FROM y1
} {1 {locking protocol}}
proc vfs_callback {func file name lock} { return SQLITE_OK }

sqlite3 db2 test.db -vfs tvfs
set ::bFirst 1

proc vfs_callback {func file name lock} {
  if {$::bFirst} {
    set ::bFirst 0
    db2 eval { INSERT INTO y1 VALUES(7, 8) }
  }
}

do_execsql_test 1.5.1 {
  SELECT * FROM y1
} {1 2 3 4 5 6 7 8}
do_execsql_test 1.5.2 {
  SELECT * FROM y1
} {1 2 3 4 5 6 7 8}

db close
db2 close
tvfs delete
finish_test
