# 2021 April 22
#
# 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.
#

if {![info exists testdir]} {
  set testdir [file join [file dirname [info script]] .. .. test]
} 
source [file join [file dirname [info script]] session_common.tcl]
source $testdir/tester.tcl
ifcapable !session {finish_test; return}

set testprefix sessionsize

proc do_changeset_size_test {tn sql} {
  sqlite3session S db main
  S attach *
  db eval $sql

  set sz [S changeset_size]
  set C [S changeset]
  set szC [string length $C]
  S delete

  do_test $tn "expr $sz" $szC
}

do_execsql_test 1.0 {
  CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c);
  INSERT INTO t1 VALUES(1, 'abc', 'def');
  INSERT INTO t1 VALUES(2, 'ghi', 'jkl');
}

do_changeset_size_test 1.1 {
  INSERT INTO t1 VALUES(3, 'hello', 'world');
}

do_changeset_size_test 1.2 {
  DELETE FROM t1 WHERE a=2;
}

do_changeset_size_test 1.3 {
  DELETE FROM t1 WHERE a=3;
  INSERT INTO t1 VALUES(3, 1, 2);
}

do_changeset_size_test 1.4 {
  UPDATE t1 SET c='hello world' WHERE a=3;
}

#-------------------------------------------------------------------------

do_execsql_test 2.0 {
  CREATE TABlE t2(a, b, c, d, PRIMARY KEY(a, b)) WITHOUT ROWID;
  CREATE TABlE t3(a, b, c, d PRIMARY KEY);
}

do_changeset_size_test 2.1 {
  WITH s(i) AS (
    SELECT 1 UNION ALL SELECT i+1 FROM s WHERE i<50
  )
  INSERT INTO t2 SELECT i, i+1, i+2, i+3 FROM s;

  UPDATE t2 SET c=randomblob(a) WHERE a>10
}

do_changeset_size_test 2.2 {
  DELETE FROM t2 WHERE a=1;
  INSERT INTO t2 VALUES(1, 4, 3, 4);
}

do_changeset_size_test 2.2 {
  UPDATE t2 SET b=4 WHERE a=2
}

do_changeset_size_test 2.3 {
  INSERT INTO t2 VALUES('a', 'b', 'c', 'd');
  UPDATE t2 SET c='qwertyuiop' WHERE a='a';
}

do_changeset_size_test 2.4 {
  DELETE FROM t2 WHERE a='a';
  INSERT INTO t2 VALUES('a', 'b', 'c', 'd');
}

do_changeset_size_test 2.5 {
  UPDATE t2 SET a='aa', b='bb' WHERE (a, b) = ('a', 'b');
}

do_changeset_size_test 2.6 {
  UPDATE t2 SET a='a', b='b' WHERE (a, b) = ('aa', 'bb');
}

do_changeset_size_test 2.7 {
  INSERT INTO t3 DEFAULT VALUES;
  INSERT INTO t3 VALUES(1,2,3,4);
}

#-------------------------------------------------------------------------
reset_db

do_execsql_test 3.0 {
  CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
}

do_test 3.1 {
  sqlite3session S db main
  S object_config size -1
} 1

do_test 3.2.1 { S object_config size 0  } 0
do_test 3.2.2 { S object_config size -1 } 0
do_test 3.2.3 { S object_config size 1  } 1
do_test 3.2.4 { S object_config size -1 } 1

do_test 3.3 { S attach t1 } {}
do_test 3.4 { S object_config size 1  } {SQLITE_MISUSE}
do_test 3.4 { S object_config size -1 } {1}

S delete

finish_test