# 2024 Aug 28
#
# 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.
#
#***********************************************************************
#

source [file join [file dirname [info script]] fts5_common.tcl]
set testprefix fts5corrupt8

# If SQLITE_ENABLE_FTS5 is not defined, omit this file.
ifcapable !fts5 {
  finish_test
  return
}

do_execsql_test 1.0 {
  CREATE VIRTUAL TABLE t1 USING fts5(x);
}

do_execsql_test 1.1 {
  UPDATE t1_data SET block='hello world' WHERE id=10
}

db close
sqlite3 db test.db

do_catchsql_test 1.2 {
  SELECT * FROM t1
} {1 {database disk image is malformed}}
do_catchsql_test 1.3 {
  DROP TABLE t1
} {0 {}}
do_execsql_test 1.4 {
  SELECT * FROM sqlite_schema
}

do_execsql_test 2.0 {
  CREATE VIRTUAL TABLE t1 USING fts5(x);
}
do_execsql_test 2.1 {
  UPDATE t1_config SET v=555 WHERE k='version'
}
db close
sqlite3 db test.db
do_catchsql_test 2.2 {
  SELECT * FROM t1
} {1 {invalid fts5 file format (found 555, expected 4 or 5) - run 'rebuild'}}
do_catchsql_test 2.3 {
  DROP TABLE t1
} {1 {invalid fts5 file format (found 555, expected 4 or 5) - run 'rebuild'}}
do_test 2.4 {
  sqlite3_fts5_drop_corrupt_table db main t1
} {}
do_execsql_test 2.5 {
  SELECT * FROM sqlite_schema
}

do_execsql_test 3.0 {
  CREATE VIRTUAL TABLE t1 USING fts5(x);
}
do_execsql_test 3.1 {
  DELETE FROM t1_config;
}
db close
sqlite3 db test.db
do_catchsql_test 3.2 {
  SELECT * FROM t1
} {1 {invalid fts5 file format (found 0, expected 4 or 5) - run 'rebuild'}}
do_catchsql_test 3.3 {
  DROP TABLE t1
} {1 {invalid fts5 file format (found 0, expected 4 or 5) - run 'rebuild'}}


do_test 3.4 {
  sqlite3_db_config db DEFENSIVE 1
} {1}
do_test 3.5 {
  sqlite3_fts5_drop_corrupt_table db main t1
} {}
do_test 3.6 {
  sqlite3_db_config db DEFENSIVE -1
} {1}
do_execsql_test 3.7 {
  SELECT * FROM sqlite_schema
}

finish_test

