# 2004 August 30
#
# 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.
#
# This file implements tests to make sure SQLite does not crash or
# segfault if it sees a corrupt database file.
#
# $Id: corrupt2.test,v 1.2 2005/01/22 03:39:39 danielk1977 Exp $

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

# The following tests - corrupt2-1.* - create some databases corrupted in
# specific ways and ensure that SQLite detects them as corrupt.
#
do_test corrupt2-1.1 {
  execsql {
    CREATE TABLE abc(a, b, c);
  }
} {}

do_test corrupt2-1.2 {

  # Corrupt the 16 byte magic string at the start of the file
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  copy_file test.db corrupt.db
  set f [open corrupt.db a]
  seek $f 8 start
  puts $f blah
  close $f

  sqlite3 db2 corrupt.db
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {file is encrypted or is not a database}}

do_test corrupt2-1.3 {
  db2 close

  # Corrupt the page-size (bytes 16 and 17 of page 1).
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  copy_file test.db corrupt.db
  set f [open corrupt.db a]
  fconfigure $f -encoding binary
  seek $f 16 start
  puts -nonewline $f "\x00\xFF"
  close $f

  sqlite3 db2 corrupt.db
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {file is encrypted or is not a database}}

do_test corrupt2-1.4 {
  db2 close

  # Corrupt the free-block list on page 1.
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  copy_file test.db corrupt.db
  set f [open corrupt.db a]
  fconfigure $f -encoding binary
  seek $f 101 start
  puts -nonewline $f "\xFF\xFF"
  close $f

  sqlite3 db2 corrupt.db
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {database disk image is malformed}}

do_test corrupt2-1.5 {
  db2 close

  # Corrupt the free-block list on page 1.
  file delete -force corrupt.db
  file delete -force corrupt.db-journal
  copy_file test.db corrupt.db
  set f [open corrupt.db a]
  fconfigure $f -encoding binary
  seek $f 101 start
  puts -nonewline $f "\x00\xC8"
  seek $f 200 start
  puts -nonewline $f "\x00\x00"
  puts -nonewline $f "\x10\x00"
  close $f

  sqlite3 db2 corrupt.db
  catchsql {
    SELECT * FROM sqlite_master;
  } db2
} {1 {database disk image is malformed}}
db2 close

finish_test