# 2007 August 21
#
# 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.
#
#***********************************************************************
#
# The focus of this file is testing some specific characteristics of the 
# IO traffic generated by SQLite (making sure SQLite is not writing out
# more database pages than it has to, stuff like that).
#
# $Id: io.test,v 1.2 2007/08/22 02:56:44 drh Exp $

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

set ::nWrite 0
proc nWrite {db} {
  set bt [btree_from_db $db]
  db_enter $db
  array set stats [btree_pager_stats $bt]
  db_leave $db
  set res [expr $stats(write) - $::nWrite]
  set ::nWrite $stats(write)
  set res
}

do_test io-1.1 {
  execsql {
    PRAGMA page_size = 1024;
    CREATE TABLE abc(a,b);
  }
  nWrite db
} {2}

# Insert into the table 4 records of aproximately 240 bytes each.
# This should completely fill the root-page of the table. Each
# INSERT causes 2 db pages to be written - the root-page of "abc"
# and page 1 (db change-counter page).
do_test io-1.2 {
  set ret [list]
  execsql { INSERT INTO abc VALUES(1,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(2,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(3,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(4,randstr(230,230)); }
  lappend ret [nWrite db]
} {2 2 2 2}

# Insert another 240 byte record. This causes two leaf pages
# to be added to the root page of abc. 4 pages in total
# are written to the db file - the two leaf pages, the root
# of abc and the change-counter page.
do_test io-1.3 {
  execsql { INSERT INTO abc VALUES(5,randstr(230,230)); }
  nWrite db
} {4}

# Insert another 3 240 byte records. After this, the tree consists of 
# the root-node, which is close to empty, and two leaf pages, both of 
# which are full. 
do_test io-1.4 {
  set ret [list]
  execsql { INSERT INTO abc VALUES(6,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(7,randstr(230,230)); }
  lappend ret [nWrite db]
  execsql { INSERT INTO abc VALUES(8,randstr(230,230)); }
  lappend ret [nWrite db]
} {2 2 2}

#db eval {select * from sqlite_master} {btree_tree_dump [btree_from_db db] 2}

# This insert should use the quick-balance trick to add a third leaf
# to the b-tree used to store table abc. It should only be necessary to
# write to 3 pages to do this: the change-counter, the root-page and
# the new leaf page.
do_test io-1.5 {
  execsql { INSERT INTO abc VALUES(9,randstr(230,230)); }
  nWrite db
} {3}

#db eval {select * from sqlite_master} {btree_tree_dump [btree_from_db db] 2}

finish_test
