System.Data.SQLite
Check-in [17c0ae883b]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Add full support for the native session extension.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 17c0ae883b98c0caacd88e1dbbe5bff77936c0e4
User & Date: mistachkin 2017-10-14 07:33:16
Context
2017-10-14
21:57
Update to tests for the session extension. check-in: 8ad03d5b81 user: mistachkin tags: trunk
07:33
Add full support for the native session extension. check-in: 17c0ae883b user: mistachkin tags: trunk
07:25
Add projects, solutions, and build environment support for Visual Studio 2017. check-in: 9d2b034e4c user: mistachkin tags: trunk
07:20
Update the master release archive manifest. Closed-Leaf check-in: 71327c1dd6 user: mistachkin tags: sessions
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to Doc/Extra/Provider/version.html.

42
43
44
45
46
47
48

49
50
51
52
53
54
55
    </div>
    <div id="mainSection">
    <div id="mainBody">
    <h1 class="heading">Version History</h1>
    <p><b>1.0.106.0 - October XX, 2017 <font color="red">(release scheduled)</font></b></p>
    <ul>
      <li>Updated to <a href="https://www.sqlite.org/releaselog/3_20_1.html">SQLite 3.20.1</a>.</li>

      <li>Add BindDecimalAsText and GetDecimalAsText connection flags to force binding and returning of decimal values as text. Pursuant to <a href="https://system.data.sqlite.org/index.html/info/b167206ad3">[b167206ad3]</a>.</li>
      <li>Add preliminary support for Visual Studio 2017 and the .NET Framework 4.7. This does <b>not</b> include support for the design-time components for Visual Studio, see <a href="https://system.data.sqlite.org/index.html/info/8292431f51">[8292431f51]</a>.</li>
    </ul>
    <p><b>1.0.105.2 - June 12, 2017</b></p>
    <ul>
      <li>Updated to <a href="https://www.sqlite.org/releaselog/3_19_3.html">SQLite 3.19.3</a>.</li>
      <li>Fix issues that prevented SQLiteBlob creation from succeeding for tables that did not have an integer primary key.</li>







>







42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
    </div>
    <div id="mainSection">
    <div id="mainBody">
    <h1 class="heading">Version History</h1>
    <p><b>1.0.106.0 - October XX, 2017 <font color="red">(release scheduled)</font></b></p>
    <ul>
      <li>Updated to <a href="https://www.sqlite.org/releaselog/3_20_1.html">SQLite 3.20.1</a>.</li>
      <li>Add full support for the native <a href="https://www.sqlite.org/sessionintro.html">session</a> extension.</li>
      <li>Add BindDecimalAsText and GetDecimalAsText connection flags to force binding and returning of decimal values as text. Pursuant to <a href="https://system.data.sqlite.org/index.html/info/b167206ad3">[b167206ad3]</a>.</li>
      <li>Add preliminary support for Visual Studio 2017 and the .NET Framework 4.7. This does <b>not</b> include support for the design-time components for Visual Studio, see <a href="https://system.data.sqlite.org/index.html/info/8292431f51">[8292431f51]</a>.</li>
    </ul>
    <p><b>1.0.105.2 - June 12, 2017</b></p>
    <ul>
      <li>Updated to <a href="https://www.sqlite.org/releaselog/3_19_3.html">SQLite 3.19.3</a>.</li>
      <li>Fix issues that prevented SQLiteBlob creation from succeeding for tables that did not have an integer primary key.</li>

Changes to SQLite.Interop/props/SQLite.Interop.2005.vsprops.

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
	<UserMacro
		Name="INTEROP_DEBUG_DEFINES"
		Value="INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1"
		PerformEnvironmentSet="true"
	/>
	<UserMacro
		Name="INTEROP_EXTRA_DEFINES"
		Value="INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1"
		PerformEnvironmentSet="true"
	/>
	<UserMacro
		Name="INTEROP_ASSEMBLY_RESOURCES"
		Value="/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp"
		PerformEnvironmentSet="true"
	/>







|







55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
	<UserMacro
		Name="INTEROP_DEBUG_DEFINES"
		Value="INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1"
		PerformEnvironmentSet="true"
	/>
	<UserMacro
		Name="INTEROP_EXTRA_DEFINES"
		Value="INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1;INTEROP_SESSION_EXTENSION=1"
		PerformEnvironmentSet="true"
	/>
	<UserMacro
		Name="INTEROP_ASSEMBLY_RESOURCES"
		Value="/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp"
		PerformEnvironmentSet="true"
	/>

Changes to SQLite.Interop/props/SQLite.Interop.2008.vsprops.

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
	<UserMacro
		Name="INTEROP_DEBUG_DEFINES"
		Value="INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1"
		PerformEnvironmentSet="true"
	/>
	<UserMacro
		Name="INTEROP_EXTRA_DEFINES"
		Value="INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1"
		PerformEnvironmentSet="true"
	/>
	<UserMacro
		Name="INTEROP_ASSEMBLY_RESOURCES"
		Value="/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp"
		PerformEnvironmentSet="true"
	/>







|







55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
	<UserMacro
		Name="INTEROP_DEBUG_DEFINES"
		Value="INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1"
		PerformEnvironmentSet="true"
	/>
	<UserMacro
		Name="INTEROP_EXTRA_DEFINES"
		Value="INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1;INTEROP_SESSION_EXTENSION=1"
		PerformEnvironmentSet="true"
	/>
	<UserMacro
		Name="INTEROP_ASSEMBLY_RESOURCES"
		Value="/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp"
		PerformEnvironmentSet="true"
	/>

Changes to SQLite.Interop/props/SQLite.Interop.2010.props.

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">







|







14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1;INTEROP_SESSION_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">

Changes to SQLite.Interop/props/SQLite.Interop.2012.props.

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">







|







14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1;INTEROP_SESSION_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">

Changes to SQLite.Interop/props/SQLite.Interop.2013.props.

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">







|







14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1;INTEROP_SESSION_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">

Changes to SQLite.Interop/props/SQLite.Interop.2015.props.

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">







|







14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1;INTEROP_SESSION_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">

Changes to SQLite.Interop/props/SQLite.Interop.2017.props.

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">







|







14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <INTEROP_LINKER_VERSION>1.0</INTEROP_LINKER_VERSION>
    <INTEROP_MANIFEST_VERSION>1.0.106.0</INTEROP_MANIFEST_VERSION>
    <INTEROP_RC_VERSION>1,0,106,0</INTEROP_RC_VERSION>
    <INTEROP_INCLUDE_DIRECTORIES>src\core</INTEROP_INCLUDE_DIRECTORIES>
    <INTEROP_LIBRARY_DIRECTORIES></INTEROP_LIBRARY_DIRECTORIES>
    <INTEROP_LIBRARY_DEPENDENCIES></INTEROP_LIBRARY_DEPENDENCIES>
    <INTEROP_DEBUG_DEFINES>INTEROP_DEBUG=0x31F;INTEROP_LOG=1;INTEROP_TEST_EXTENSION=1</INTEROP_DEBUG_DEFINES>
    <INTEROP_EXTRA_DEFINES>INTEROP_PLACEHOLDER=1;INTEROP_EXTENSION_FUNCTIONS=1;INTEROP_VIRTUAL_TABLE=1;INTEROP_FTS5_EXTENSION=1;INTEROP_PERCENTILE_EXTENSION=1;INTEROP_TOTYPE_EXTENSION=1;INTEROP_REGEXP_EXTENSION=1;INTEROP_JSON1_EXTENSION=1;INTEROP_SHA1_EXTENSION=1;INTEROP_SESSION_EXTENSION=1</INTEROP_EXTRA_DEFINES>
    <INTEROP_ASSEMBLY_RESOURCES>/ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteCommand.bmp,System.Data.SQLite.SQLiteCommand.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteConnection.bmp,System.Data.SQLite.SQLiteConnection.bmp /ASSEMBLYRESOURCE:..\System.Data.SQLite\Resources\SQLiteDataAdapter.bmp,System.Data.SQLite.SQLiteDataAdapter.bmp</INTEROP_ASSEMBLY_RESOURCES>
    <INTEROP_KEY_FILE>$(ProjectDir)..\Keys\System.Data.SQLite.snk</INTEROP_KEY_FILE>
    <INTEROP_NATIVE_NAME>SQLite.Interop</INTEROP_NATIVE_NAME>
    <INTEROP_MIXED_NAME>System.Data.SQLite</INTEROP_MIXED_NAME>
  </PropertyGroup>
  <ItemGroup>
    <BuildMacro Include="ConfigurationYear">

Changes to SQLite.Interop/src/generic/interop.c.

6
7
8
9
10
11
12









13
14
15
16
17
18
19
...
127
128
129
130
131
132
133



134
135
136
137
138
139
140
 ********************************************************/

#ifdef _WIN32
#define SQLITE_API __declspec(dllexport)
#else
#define WINAPI
#endif










#include "../core/sqlite3.c"

#if !SQLITE_OS_WIN
#include <wchar.h>
#endif

................................................................................
  "LOG",
#endif
#ifdef INTEROP_PERCENTILE_EXTENSION
  "PERCENTILE_EXTENSION",
#endif
#ifdef INTEROP_REGEXP_EXTENSION
  "REGEXP_EXTENSION",



#endif
#ifdef INTEROP_SHA1_EXTENSION
  "SHA1_EXTENSION",
#endif
#ifdef INTEROP_TEST_EXTENSION
  "TEST_EXTENSION",
#endif







>
>
>
>
>
>
>
>
>







 







>
>
>







6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
...
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
 ********************************************************/

#ifdef _WIN32
#define SQLITE_API __declspec(dllexport)
#else
#define WINAPI
#endif

#if /* SQLITE_VERSION_NUMBER >= 3013000 && */ defined(INTEROP_SESSION_EXTENSION)
#ifndef SQLITE_ENABLE_SESSION
#define SQLITE_ENABLE_SESSION (1)
#endif
#ifndef SQLITE_ENABLE_PREUPDATE_HOOK
#define SQLITE_ENABLE_PREUPDATE_HOOK (1)
#endif
#endif

#include "../core/sqlite3.c"

#if !SQLITE_OS_WIN
#include <wchar.h>
#endif

................................................................................
  "LOG",
#endif
#ifdef INTEROP_PERCENTILE_EXTENSION
  "PERCENTILE_EXTENSION",
#endif
#ifdef INTEROP_REGEXP_EXTENSION
  "REGEXP_EXTENSION",
#endif
#ifdef INTEROP_SESSION_EXTENSION
  "SESSION_EXTENSION",
#endif
#ifdef INTEROP_SHA1_EXTENSION
  "SHA1_EXTENSION",
#endif
#ifdef INTEROP_TEST_EXTENSION
  "TEST_EXTENSION",
#endif

Changes to Setup/compile-interop-assembly-debug.sh.

8
9
10
11
12
13
14
15
16
17
18
  gccflags="-arch i386 -arch x86_64"
else
  libname=libSQLite.Interop.so
  gccflags=""
fi

pushd "$scriptdir/../SQLite.Interop/src/generic"
gcc -g -fPIC -shared $gccflags -o $libname interop.c -I../core -DSQLITE_THREADSAFE=1 -DSQLITE_USE_URI=1 -DSQLITE_ENABLE_COLUMN_METADATA=1 -DSQLITE_ENABLE_STAT4=1 -DSQLITE_ENABLE_FTS3=1 -DSQLITE_ENABLE_LOAD_EXTENSION=1 -DSQLITE_ENABLE_RTREE=1 -DSQLITE_SOUNDEX=1 -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 -DSQLITE_ENABLE_API_ARMOR=1 -DSQLITE_ENABLE_DBSTAT_VTAB=1 -DSQLITE_DEBUG=1 -DSQLITE_MEMDEBUG=1 -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 -DINTEROP_LOG=1 -DINTEROP_TEST_EXTENSION=1 -DINTEROP_EXTENSION_FUNCTIONS=1 -DINTEROP_VIRTUAL_TABLE=1 -DINTEROP_FTS5_EXTENSION=1 -DINTEROP_PERCENTILE_EXTENSION=1 -DINTEROP_TOTYPE_EXTENSION=1 -DINTEROP_REGEXP_EXTENSION=1 -DINTEROP_JSON1_EXTENSION=1 -DINTEROP_SHA1_EXTENSION=1 $extradefs -lm -lpthread -ldl
mkdir -p ../../../bin/2013/Debug/bin
mv $libname ../../../bin/2013/Debug/bin
popd







|



8
9
10
11
12
13
14
15
16
17
18
  gccflags="-arch i386 -arch x86_64"
else
  libname=libSQLite.Interop.so
  gccflags=""
fi

pushd "$scriptdir/../SQLite.Interop/src/generic"
gcc -g -fPIC -shared $gccflags -o $libname interop.c -I../core -DSQLITE_THREADSAFE=1 -DSQLITE_USE_URI=1 -DSQLITE_ENABLE_COLUMN_METADATA=1 -DSQLITE_ENABLE_STAT4=1 -DSQLITE_ENABLE_FTS3=1 -DSQLITE_ENABLE_LOAD_EXTENSION=1 -DSQLITE_ENABLE_RTREE=1 -DSQLITE_SOUNDEX=1 -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 -DSQLITE_ENABLE_API_ARMOR=1 -DSQLITE_ENABLE_DBSTAT_VTAB=1 -DSQLITE_DEBUG=1 -DSQLITE_MEMDEBUG=1 -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 -DINTEROP_LOG=1 -DINTEROP_TEST_EXTENSION=1 -DINTEROP_EXTENSION_FUNCTIONS=1 -DINTEROP_VIRTUAL_TABLE=1 -DINTEROP_FTS5_EXTENSION=1 -DINTEROP_PERCENTILE_EXTENSION=1 -DINTEROP_TOTYPE_EXTENSION=1 -DINTEROP_REGEXP_EXTENSION=1 -DINTEROP_JSON1_EXTENSION=1 -DINTEROP_SHA1_EXTENSION=1 -DINTEROP_SESSION_EXTENSION=1 $extradefs -lm -lpthread -ldl
mkdir -p ../../../bin/2013/Debug/bin
mv $libname ../../../bin/2013/Debug/bin
popd

Changes to Setup/compile-interop-assembly-release.sh.

8
9
10
11
12
13
14
15
16
17
18
  gccflags="-arch i386 -arch x86_64"
else
  libname=libSQLite.Interop.so
  gccflags=""
fi

pushd "$scriptdir/../SQLite.Interop/src/generic"
gcc -g -fPIC -shared $gccflags -o $libname interop.c -I../core -DSQLITE_THREADSAFE=1 -DSQLITE_USE_URI=1 -DSQLITE_ENABLE_COLUMN_METADATA=1 -DSQLITE_ENABLE_STAT4=1 -DSQLITE_ENABLE_FTS3=1 -DSQLITE_ENABLE_LOAD_EXTENSION=1 -DSQLITE_ENABLE_RTREE=1 -DSQLITE_SOUNDEX=1 -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 -DSQLITE_ENABLE_API_ARMOR=1 -DSQLITE_ENABLE_DBSTAT_VTAB=1 -DINTEROP_TEST_EXTENSION=1 -DINTEROP_EXTENSION_FUNCTIONS=1 -DINTEROP_VIRTUAL_TABLE=1 -DINTEROP_FTS5_EXTENSION=1 -DINTEROP_PERCENTILE_EXTENSION=1 -DINTEROP_TOTYPE_EXTENSION=1 -DINTEROP_REGEXP_EXTENSION=1 -DINTEROP_JSON1_EXTENSION=1 -DINTEROP_SHA1_EXTENSION=1 $extradefs -lm -lpthread -ldl
mkdir -p ../../../bin/2013/Release/bin
mv $libname ../../../bin/2013/Release/bin
popd







|



8
9
10
11
12
13
14
15
16
17
18
  gccflags="-arch i386 -arch x86_64"
else
  libname=libSQLite.Interop.so
  gccflags=""
fi

pushd "$scriptdir/../SQLite.Interop/src/generic"
gcc -g -fPIC -shared $gccflags -o $libname interop.c -I../core -DSQLITE_THREADSAFE=1 -DSQLITE_USE_URI=1 -DSQLITE_ENABLE_COLUMN_METADATA=1 -DSQLITE_ENABLE_STAT4=1 -DSQLITE_ENABLE_FTS3=1 -DSQLITE_ENABLE_LOAD_EXTENSION=1 -DSQLITE_ENABLE_RTREE=1 -DSQLITE_SOUNDEX=1 -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 -DSQLITE_ENABLE_API_ARMOR=1 -DSQLITE_ENABLE_DBSTAT_VTAB=1 -DINTEROP_TEST_EXTENSION=1 -DINTEROP_EXTENSION_FUNCTIONS=1 -DINTEROP_VIRTUAL_TABLE=1 -DINTEROP_FTS5_EXTENSION=1 -DINTEROP_PERCENTILE_EXTENSION=1 -DINTEROP_TOTYPE_EXTENSION=1 -DINTEROP_REGEXP_EXTENSION=1 -DINTEROP_JSON1_EXTENSION=1 -DINTEROP_SHA1_EXTENSION=1 -DINTEROP_SESSION_EXTENSION=1 $extradefs -lm -lpthread -ldl
mkdir -p ../../../bin/2013/Release/bin
mv $libname ../../../bin/2013/Release/bin
popd

Changes to Setup/data/verify.lst.

211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
...
609
610
611
612
613
614
615

616
617
618
619
620
621
622
...
821
822
823
824
825
826
827

828
829
830
831
832
833
834
...
885
886
887
888
889
890
891

892
893
894
895
896
897
898
...
950
951
952
953
954
955
956

957
958
959
960
961
962
963
964
965

966
967
968

969
970
971
972
973
974
975
  Externals/Eagle/
  Externals/Eagle/bin/
  Externals/Eagle/bin/EagleShell.exe.config
  Externals/Eagle/bin/EagleShell.exe.mda.config
  Externals/Eagle/lib/
  Externals/Eagle/lib/Eagle1.0/
  Externals/Eagle/lib/Eagle1.0/vendor.eagle
  Externals/Eagle/lib/Test1.0/
  Keys/
  Keys/System.Data.SQLite.CF.snk
  Keys/System.Data.SQLite.snk
  lib/
  lib/System.Data.SQLite/
  lib/System.Data.SQLite/common.eagle
  lib/System.Data.SQLite/pkgIndex.eagle
................................................................................
  System.Data.SQLite/SQLiteModule.cs
  System.Data.SQLite/SQLiteModuleCommon.cs
  System.Data.SQLite/SQLiteModuleEnumerable.cs
  System.Data.SQLite/SQLiteModuleNoop.cs
  System.Data.SQLite/SQLiteParameter.cs
  System.Data.SQLite/SQLiteParameterCollection.cs
  System.Data.SQLite/SQLitePatchLevel.cs

  System.Data.SQLite/SQLiteStatement.cs
  System.Data.SQLite/SQLiteTransaction.cs
  System.Data.SQLite/SQLiteTransaction2.cs
  System.Data.SQLite/SQLiteTransactionBase.cs
  System.Data.SQLite/System.Data.SQLite.2005.csproj
  System.Data.SQLite/System.Data.SQLite.2008.csproj
  System.Data.SQLite/System.Data.SQLite.2010.csproj
................................................................................
  Tests/data/Uninstaller_Test_Vs2013.log
  Tests/data/Uninstaller_Test_Vs2015.log
  Tests/data/wal.db
  Tests/installer.eagle
  Tests/linq.eagle
  Tests/memory.eagle
  Tests/progress.eagle

  Tests/speed.eagle
  Tests/stress.eagle
  Tests/template/
  Tests/template/empty.eagle
  Tests/thread.eagle
  Tests/tkt-00f86f9739.eagle
  Tests/tkt-0a32885109.eagle
................................................................................
  Tests/tkt-9ba9346f75.eagle
  Tests/tkt-9d353b0bd8.eagle
  Tests/tkt-a4d9c7ee94.eagle
  Tests/tkt-a7d04fb111.eagle
  Tests/tkt-aba4549801.eagle
  Tests/tkt-ac47dd230a.eagle
  Tests/tkt-ae5267b863.eagle

  Tests/tkt-b4a7ddc83f.eagle
  Tests/tkt-bb4b04d457.eagle
  Tests/tkt-c010fa6584.eagle
  Tests/tkt-c28d7fe915.eagle
  Tests/tkt-ccfa69fc32.eagle
  Tests/tkt-d4728aecb7.eagle
  Tests/tkt-da685c0bac.eagle
................................................................................
  Externals/Eagle/lib/Eagle1.0/file3.eagle
  Externals/Eagle/lib/Eagle1.0/info.eagle
  Externals/Eagle/lib/Eagle1.0/init.eagle
  Externals/Eagle/lib/Eagle1.0/list.eagle
  Externals/Eagle/lib/Eagle1.0/object.eagle
  Externals/Eagle/lib/Eagle1.0/pkgIndex.eagle
  Externals/Eagle/lib/Eagle1.0/pkgIndex.tcl

  Externals/Eagle/lib/Eagle1.0/platform.eagle
  Externals/Eagle/lib/Eagle1.0/process.eagle
  Externals/Eagle/lib/Eagle1.0/runopt.eagle
  Externals/Eagle/lib/Eagle1.0/safe.eagle
  Externals/Eagle/lib/Eagle1.0/shell.eagle
  Externals/Eagle/lib/Eagle1.0/shim.eagle
  Externals/Eagle/lib/Eagle1.0/test.eagle
  Externals/Eagle/lib/Eagle1.0/testlog.eagle
  Externals/Eagle/lib/Eagle1.0/unkobj.eagle

  Externals/Eagle/lib/Eagle1.0/update.eagle
  Externals/Eagle/lib/Eagle1.0/vendor.eagle
  Externals/Eagle/lib/Eagle1.0/word.tcl

  Externals/Eagle/lib/Test1.0/all.eagle
  Externals/Eagle/lib/Test1.0/constraints.eagle
  Externals/Eagle/lib/Test1.0/epilogue.eagle
  Externals/Eagle/lib/Test1.0/pkgIndex.eagle
  Externals/Eagle/lib/Test1.0/pkgIndex.tcl
  Externals/Eagle/lib/Test1.0/prologue.eagle
}







<







 







>







 







>







 







>







 







>









>



>







211
212
213
214
215
216
217

218
219
220
221
222
223
224
...
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
...
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
...
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
...
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
  Externals/Eagle/
  Externals/Eagle/bin/
  Externals/Eagle/bin/EagleShell.exe.config
  Externals/Eagle/bin/EagleShell.exe.mda.config
  Externals/Eagle/lib/
  Externals/Eagle/lib/Eagle1.0/
  Externals/Eagle/lib/Eagle1.0/vendor.eagle

  Keys/
  Keys/System.Data.SQLite.CF.snk
  Keys/System.Data.SQLite.snk
  lib/
  lib/System.Data.SQLite/
  lib/System.Data.SQLite/common.eagle
  lib/System.Data.SQLite/pkgIndex.eagle
................................................................................
  System.Data.SQLite/SQLiteModule.cs
  System.Data.SQLite/SQLiteModuleCommon.cs
  System.Data.SQLite/SQLiteModuleEnumerable.cs
  System.Data.SQLite/SQLiteModuleNoop.cs
  System.Data.SQLite/SQLiteParameter.cs
  System.Data.SQLite/SQLiteParameterCollection.cs
  System.Data.SQLite/SQLitePatchLevel.cs
  System.Data.SQLite/SQLiteSession.cs
  System.Data.SQLite/SQLiteStatement.cs
  System.Data.SQLite/SQLiteTransaction.cs
  System.Data.SQLite/SQLiteTransaction2.cs
  System.Data.SQLite/SQLiteTransactionBase.cs
  System.Data.SQLite/System.Data.SQLite.2005.csproj
  System.Data.SQLite/System.Data.SQLite.2008.csproj
  System.Data.SQLite/System.Data.SQLite.2010.csproj
................................................................................
  Tests/data/Uninstaller_Test_Vs2013.log
  Tests/data/Uninstaller_Test_Vs2015.log
  Tests/data/wal.db
  Tests/installer.eagle
  Tests/linq.eagle
  Tests/memory.eagle
  Tests/progress.eagle
  Tests/session.eagle
  Tests/speed.eagle
  Tests/stress.eagle
  Tests/template/
  Tests/template/empty.eagle
  Tests/thread.eagle
  Tests/tkt-00f86f9739.eagle
  Tests/tkt-0a32885109.eagle
................................................................................
  Tests/tkt-9ba9346f75.eagle
  Tests/tkt-9d353b0bd8.eagle
  Tests/tkt-a4d9c7ee94.eagle
  Tests/tkt-a7d04fb111.eagle
  Tests/tkt-aba4549801.eagle
  Tests/tkt-ac47dd230a.eagle
  Tests/tkt-ae5267b863.eagle
  Tests/tkt-b167206ad3.eagle
  Tests/tkt-b4a7ddc83f.eagle
  Tests/tkt-bb4b04d457.eagle
  Tests/tkt-c010fa6584.eagle
  Tests/tkt-c28d7fe915.eagle
  Tests/tkt-ccfa69fc32.eagle
  Tests/tkt-d4728aecb7.eagle
  Tests/tkt-da685c0bac.eagle
................................................................................
  Externals/Eagle/lib/Eagle1.0/file3.eagle
  Externals/Eagle/lib/Eagle1.0/info.eagle
  Externals/Eagle/lib/Eagle1.0/init.eagle
  Externals/Eagle/lib/Eagle1.0/list.eagle
  Externals/Eagle/lib/Eagle1.0/object.eagle
  Externals/Eagle/lib/Eagle1.0/pkgIndex.eagle
  Externals/Eagle/lib/Eagle1.0/pkgIndex.tcl
  Externals/Eagle/lib/Eagle1.0/pkgt.eagle
  Externals/Eagle/lib/Eagle1.0/platform.eagle
  Externals/Eagle/lib/Eagle1.0/process.eagle
  Externals/Eagle/lib/Eagle1.0/runopt.eagle
  Externals/Eagle/lib/Eagle1.0/safe.eagle
  Externals/Eagle/lib/Eagle1.0/shell.eagle
  Externals/Eagle/lib/Eagle1.0/shim.eagle
  Externals/Eagle/lib/Eagle1.0/test.eagle
  Externals/Eagle/lib/Eagle1.0/testlog.eagle
  Externals/Eagle/lib/Eagle1.0/unkobj.eagle
  Externals/Eagle/lib/Eagle1.0/unzip.eagle
  Externals/Eagle/lib/Eagle1.0/update.eagle
  Externals/Eagle/lib/Eagle1.0/vendor.eagle
  Externals/Eagle/lib/Eagle1.0/word.tcl
  Externals/Eagle/lib/Test1.0/
  Externals/Eagle/lib/Test1.0/all.eagle
  Externals/Eagle/lib/Test1.0/constraints.eagle
  Externals/Eagle/lib/Test1.0/epilogue.eagle
  Externals/Eagle/lib/Test1.0/pkgIndex.eagle
  Externals/Eagle/lib/Test1.0/pkgIndex.tcl
  Externals/Eagle/lib/Test1.0/prologue.eagle
}

Changes to System.Data.SQLite/SQLiteConnection.cs.

1756
1757
1758
1759
1760
1761
1762









































1763
1764
1765
1766
1767
1768
1769
....
2969
2970
2971
2972
2973
2974
2975
















































































2976
2977
2978
2979
2980
2981
2982
          }
        }
      }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////










































    /// <summary>
    /// Raises the <see cref="Changed" /> event.
    /// </summary>
    /// <param name="connection">
    /// The connection associated with this event.  If this parameter is not
    /// null and the specified connection cannot raise events, then the
    /// registered event handlers will not be invoked.
................................................................................
    /// Forwards to the local <see cref="CreateCommand" /> function.
    /// </summary>
    /// <returns></returns>
    protected override DbCommand CreateDbCommand()
    {
      return CreateCommand();
    }

















































































    /// <summary>
    /// Returns the data source file name without extension or path.
    /// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
#endif







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
....
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
          }
        }
      }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// Attempts to lookup the native handle associated with the connection.  An exception will
    /// be thrown if this cannot be accomplished.
    /// </summary>
    /// <param name="connection">
    /// The connection associated with the desired native handle.
    /// </param>
    /// <returns>
    /// The native handle associated with the connection or <see cref="IntPtr.Zero" /> if it
    /// cannot be determined.
    /// </returns>
    private static SQLiteConnectionHandle GetNativeHandle(
        SQLiteConnection connection
        )
    {
        if (connection == null)
            throw new ArgumentNullException("connection");

        SQLite3 sqlite3 = connection._sql as SQLite3;

        if (sqlite3 == null)
            throw new InvalidOperationException("Connection has no wrapper");

        SQLiteConnectionHandle handle = sqlite3._sql;

        if (handle == null)
            throw new InvalidOperationException("Connection has an invalid handle.");

        IntPtr handlePtr = handle;

        if (handlePtr == IntPtr.Zero)
        {
            throw new InvalidOperationException(
                "Connection has an invalid handle pointer.");
        }

        return handle;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// Raises the <see cref="Changed" /> event.
    /// </summary>
    /// <param name="connection">
    /// The connection associated with this event.  If this parameter is not
    /// null and the specified connection cannot raise events, then the
    /// registered event handlers will not be invoked.
................................................................................
    /// Forwards to the local <see cref="CreateCommand" /> function.
    /// </summary>
    /// <returns></returns>
    protected override DbCommand CreateDbCommand()
    {
      return CreateCommand();
    }

#if INTEROP_SESSION_EXTENSION
    /// <summary>
    /// Attempts to create a new <see cref="ISQLiteSession" /> object instance
    /// using this connection and the specified database name.
    /// </summary>
    /// <param name="databaseName">
    /// The name of the database for the newly created session.
    /// </param>
    /// <returns>
    /// The newly created session -OR- null if it cannot be created.
    /// </returns>
    public ISQLiteSession CreateSession(
        string databaseName
        )
    {
        CheckDisposed();

        return new SQLiteSession(GetNativeHandle(this), _flags, databaseName);
    }

    /// <summary>
    /// Attempts to create a new <see cref="ISQLiteChangeSet" /> object instance
    /// using this connection and the specified raw data.
    /// </summary>
    /// <param name="rawData">
    /// The raw data that contains a change set (or patch set).
    /// </param>
    /// <returns>
    /// The newly created change set -OR- null if it cannot be created.
    /// </returns>
    public ISQLiteChangeSet CreateChangeSet(
        byte[] rawData
        )
    {
        CheckDisposed();

        return new SQLiteMemoryChangeSet(rawData, GetNativeHandle(this), _flags);
    }

    /// <summary>
    /// Attempts to create a new <see cref="ISQLiteChangeSet" /> object instance
    /// using this connection and the specified stream.
    /// </summary>
    /// <param name="inputStream">
    /// The stream where the raw data that contains a change set (or patch set)
    /// may be read.
    /// </param>
    /// <param name="outputStream">
    /// The stream where the raw data that contains a change set (or patch set)
    /// may be written.
    /// </param>
    /// <returns>
    /// The newly created change set -OR- null if it cannot be created.
    /// </returns>
    public ISQLiteChangeSet CreateChangeSet(
        Stream inputStream,
        Stream outputStream
        )
    {
        CheckDisposed();

        return new SQLiteStreamChangeSet(
            inputStream, outputStream, GetNativeHandle(this), _flags);
    }

    /// <summary>
    /// Attempts to create a new <see cref="ISQLiteChangeGroup" /> object
    /// instance using this connection.
    /// </summary>
    /// <returns>
    /// The newly created change group -OR- null if it cannot be created.
    /// </returns>
    public ISQLiteChangeGroup CreateChangeGroup()
    {
        CheckDisposed();

        return new SQLiteChangeGroup(_flags);
    }
#endif

    /// <summary>
    /// Returns the data source file name without extension or path.
    /// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
#endif

Changes to System.Data.SQLite/SQLiteDefineConstants.cs.

71
72
73
74
75
76
77




78
79
80
81
82
83
84
#if INTEROP_PERCENTILE_EXTENSION
            "INTEROP_PERCENTILE_EXTENSION",
#endif

#if INTEROP_REGEXP_EXTENSION
            "INTEROP_REGEXP_EXTENSION",
#endif





#if INTEROP_SHA1_EXTENSION
            "INTEROP_SHA1_EXTENSION",
#endif

#if INTEROP_TEST_EXTENSION
            "INTEROP_TEST_EXTENSION",







>
>
>
>







71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#if INTEROP_PERCENTILE_EXTENSION
            "INTEROP_PERCENTILE_EXTENSION",
#endif

#if INTEROP_REGEXP_EXTENSION
            "INTEROP_REGEXP_EXTENSION",
#endif

#if INTEROP_SESSION_EXTENSION
            "INTEROP_SESSION_EXTENSION",
#endif

#if INTEROP_SHA1_EXTENSION
            "INTEROP_SHA1_EXTENSION",
#endif

#if INTEROP_TEST_EXTENSION
            "INTEROP_TEST_EXTENSION",

Changes to System.Data.SQLite/SQLiteModule.cs.

333
334
335
336
337
338
339





















340
341
342
343
344
345
346
...
568
569
570
571
572
573
574














































575
576
577
578
579
580
581
....
3479
3480
3481
3482
3483
3484
3485



























3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
....
3635
3636
3637
3638
3639
3640
3641

























3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
            pValue = IntPtr.Zero;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Internal Marshal Helper Methods





















        /// <summary>
        /// Converts a logical array of native pointers to native sqlite3_value
        /// structures into a managed array of <see cref="SQLiteValue" />
        /// object instances.
        /// </summary>
        /// <param name="argc">
        /// The number of elements in the logical array of native sqlite3_value
................................................................................
        public byte[] GetBlob()
        {
            if (pValue == IntPtr.Zero) return null;

            return SQLiteBytes.FromIntPtr(
                UnsafeNativeMethods.sqlite3_value_blob(pValue), GetBytes());
        }















































        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Uses the native value handle to obtain and store the managed value
        /// for this object instance, thus saving it for later use.  The type
        /// of the managed value is determined by the type affinity of the
................................................................................
        /// <returns>
        /// The native NUL-terminated UTF-8 string pointer or
        /// <see cref="IntPtr.Zero" /> upon failure.
        /// </returns>
        public static IntPtr Utf8IntPtrFromString(
            string value
            )



























        {
            if (value == null)
                return IntPtr.Zero;

            IntPtr result = IntPtr.Zero;
            byte[] bytes = GetUtf8BytesFromString(value);

            if (bytes == null)
                return IntPtr.Zero;

            int length = bytes.Length;

            result = SQLiteMemory.Allocate(length + 1);

            if (result == IntPtr.Zero)
                return IntPtr.Zero;

            Marshal.Copy(bytes, 0, result, length);
................................................................................
        /// </param>
        /// <returns>
        /// The native pointer to a logical byte array or null upon failure.
        /// </returns>
        public static IntPtr ToIntPtr(
            byte[] value
            )

























        {
            if (value == null)
                return IntPtr.Zero;

            int length = value.Length;

            if (length == 0)
                return IntPtr.Zero;

            IntPtr result = SQLiteMemory.Allocate(length);

            if (result == IntPtr.Zero)







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|







333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
...
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
....
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
....
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
            pValue = IntPtr.Zero;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Internal Marshal Helper Methods
        /// <summary>
        /// Converts a native pointer to a native sqlite3_value structure into
        /// a managed <see cref="SQLiteValue" /> object instance.
        /// </summary>
        /// <param name="pValue">
        /// The native pointer to a native sqlite3_value structure to convert.
        /// </param>
        /// <returns>
        /// The managed <see cref="SQLiteValue" /> object instance or null upon
        /// failure.
        /// </returns>
        internal static SQLiteValue FromIntPtr(
            IntPtr pValue
            )
        {
            if (pValue == IntPtr.Zero) return null;
            return new SQLiteValue(pValue);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Converts a logical array of native pointers to native sqlite3_value
        /// structures into a managed array of <see cref="SQLiteValue" />
        /// object instances.
        /// </summary>
        /// <param name="argc">
        /// The number of elements in the logical array of native sqlite3_value
................................................................................
        public byte[] GetBlob()
        {
            if (pValue == IntPtr.Zero) return null;

            return SQLiteBytes.FromIntPtr(
                UnsafeNativeMethods.sqlite3_value_blob(pValue), GetBytes());
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Gets and returns an <see cref="Object" /> instance associated with
        /// this value.
        /// </summary>
        /// <returns>
        /// The <see cref="Object" /> associated with this value.  If the type
        /// affinity of the object is unknown or cannot be determined, a null
        /// value will be returned.
        /// </returns>
        public object GetObject()
        {
            switch (GetTypeAffinity())
            {
                case TypeAffinity.Uninitialized:
                    {
                        return null;
                    }
                case TypeAffinity.Int64:
                    {
                        return GetInt64();
                    }
                case TypeAffinity.Double:
                    {
                        return GetDouble();
                    }
                case TypeAffinity.Text:
                    {
                        return GetString();
                    }
                case TypeAffinity.Blob:
                    {
                        return GetBytes();
                    }
                case TypeAffinity.Null:
                    {
                        return DBNull.Value;
                    }
                default:
                    {
                        return null;
                    }
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Uses the native value handle to obtain and store the managed value
        /// for this object instance, thus saving it for later use.  The type
        /// of the managed value is determined by the type affinity of the
................................................................................
        /// <returns>
        /// The native NUL-terminated UTF-8 string pointer or
        /// <see cref="IntPtr.Zero" /> upon failure.
        /// </returns>
        public static IntPtr Utf8IntPtrFromString(
            string value
            )
        {
            int length = 0;

            return Utf8IntPtrFromString(value, ref length);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Converts the specified managed string into a native NUL-terminated
        /// UTF-8 string pointer using memory obtained from the SQLite core
        /// library.
        /// </summary>
        /// <param name="value">
        /// The managed string to convert.
        /// </param>
        /// <param name="length">
        /// The length of the native string, in bytes.
        /// </param>
        /// <returns>
        /// The native NUL-terminated UTF-8 string pointer or
        /// <see cref="IntPtr.Zero" /> upon failure.
        /// </returns>
        public static IntPtr Utf8IntPtrFromString(
            string value,
            ref int length
            )
        {
            if (value == null)
                return IntPtr.Zero;

            IntPtr result = IntPtr.Zero;
            byte[] bytes = GetUtf8BytesFromString(value);

            if (bytes == null)
                return IntPtr.Zero;

            length = bytes.Length;

            result = SQLiteMemory.Allocate(length + 1);

            if (result == IntPtr.Zero)
                return IntPtr.Zero;

            Marshal.Copy(bytes, 0, result, length);
................................................................................
        /// </param>
        /// <returns>
        /// The native pointer to a logical byte array or null upon failure.
        /// </returns>
        public static IntPtr ToIntPtr(
            byte[] value
            )
        {
            int length = 0;

            return ToIntPtr(value, ref length);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Converts a managed byte array into a native pointer to a logical
        /// array of bytes.
        /// </summary>
        /// <param name="value">
        /// The managed byte array to convert.
        /// </param>
        /// <param name="length">
        /// The length, in bytes, of the converted logical array of bytes.
        /// </param>
        /// <returns>
        /// The native pointer to a logical byte array or null upon failure.
        /// </returns>
        public static IntPtr ToIntPtr(
            byte[] value,
            ref int length
            )
        {
            if (value == null)
                return IntPtr.Zero;

            length = value.Length;

            if (length == 0)
                return IntPtr.Zero;

            IntPtr result = SQLiteMemory.Allocate(length);

            if (result == IntPtr.Zero)

Added System.Data.SQLite/SQLiteSession.cs.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Joe Mistachkin (joe@mistachkin.com)
 *
 * Released to the public domain, use at your own risk!
 ********************************************************/

using System.Collections;
using System.Collections.Generic;

#if DEBUG
using System.Diagnostics;
#endif

using System.IO;
using System.Globalization;
using System.Runtime.InteropServices;

namespace System.Data.SQLite
{
    #region Session Extension Enumerations
    /// <summary>
    /// This enumerated type represents a type of conflict seen when apply
    /// changes from a change set or patch set.
    /// </summary>
    public enum SQLiteChangeSetConflictType
    {
        /// <summary>
        /// This value is seen when processing a DELETE or UPDATE change if a
        /// row with the required PRIMARY KEY fields is present in the
        /// database, but one or more other (non primary-key) fields modified
        /// by the update do not contain the expected "before" values.
        /// </summary>
        Data = 1,

        /// <summary>
        /// This value is seen when processing a DELETE or UPDATE change if a
        /// row with the required PRIMARY KEY fields is not present in the
        /// database.  There is no conflicting row in this case.
        ///
        /// The results of invoking the
        /// <see cref="ISQLiteChangeSetMetadataItem.GetConflictValue" />
        /// method are undefined.
        /// </summary>
        NotFound = 2,

        /// <summary>
        /// This value is seen when processing an INSERT change if the
        /// operation would result in duplicate primary key values.
        /// The conflicting row in this case is the database row with the
        /// matching primary key.
        /// </summary>
        Conflict = 3,

        /// <summary>
        /// If a non-foreign key constraint violation occurs while applying a
        /// change (i.e. a UNIQUE, CHECK or NOT NULL constraint), the conflict
        /// callback will see this value.
        ///
        /// There is no conflicting row in this case. The results of invoking
        /// the <see cref="ISQLiteChangeSetMetadataItem.GetConflictValue" />
        /// method are undefined.
        /// </summary>
        Constraint = 4,

        /// <summary>
        /// If foreign key handling is enabled, and applying a changes leaves
        /// the database in a state containing foreign key violations, this
        /// value will be seen exactly once before the changes are committed.
        /// If the conflict handler
        /// <see cref="SQLiteChangeSetConflictResult.Omit" />, the changes,
        /// including those that caused the foreign key constraint violation,
        /// are committed. Or, if it returns
        /// <see cref="SQLiteChangeSetConflictResult.Abort" />, the changes are
        /// rolled back.
        ///
        /// No current or conflicting row information is provided. The only
        /// method it is possible to call on the supplied
        /// <see cref="ISQLiteChangeSetMetadataItem" /> object is
        /// <see cref="ISQLiteChangeSetMetadataItem.NumberOfForeignKeyConflicts" />.
        /// </summary>
        ForeignKey = 5
    }

    ///////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// This enumerated type represents the result of a user-defined conflict
    /// resolution callback.
    /// </summary>
    public enum SQLiteChangeSetConflictResult
    {
        /// <summary>
        /// If a conflict callback returns this value no special action is
        /// taken. The change that caused the conflict is not applied. The
        /// application of changes continues with the next change.
        /// </summary>
        Omit = 0,

        /// <summary>
        /// This value may only be returned from a conflict callback if the
        /// type of conflict was <see cref="SQLiteChangeSetConflictType.Data" />
        /// or <see cref="SQLiteChangeSetConflictType.Conflict" />. If this is
        /// not the case, any changes applied so far are rolled back and the
        /// call to
        /// <see cref="ISQLiteChangeSet.Apply(SessionConflictCallback,SessionTableFilterCallback,object)" />
        /// will raise a <see cref="SQLiteException" /> with an error code of
        /// <see cref="SQLiteErrorCode.Misuse" />.
        ///
        /// If this value is returned for a
        /// <see cref="SQLiteChangeSetConflictType.Data" /> conflict, then the
        /// conflicting row is either updated or deleted, depending on the type
        /// of change.
        ///
        /// If this value is returned for a
        /// <see cref="SQLiteChangeSetConflictType.Conflict" /> conflict, then
        /// the conflicting row is removed from the database and a second
        /// attempt to apply the change is made. If this second attempt fails,
        /// the original row is restored to the database before continuing.
        /// </summary>
        Replace = 1,

        /// <summary>
        /// If this value is returned, any changes applied so far are rolled
        /// back and the call to
        /// <see cref="ISQLiteChangeSet.Apply(SessionConflictCallback,SessionTableFilterCallback,object)" />
        /// will raise a <see cref="SQLiteException" /> with an error code of
        /// <see cref="SQLiteErrorCode.Abort" />.
        /// </summary>
        Abort = 2
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region Session Extension Delegates
    /// <summary>
    /// This callback is invoked when a determination must be made about
    /// whether changes to a specific table should be tracked -OR- applied.
    /// It will not be called for tables that are already attached to a
    /// <see cref="ISQLiteSession" />.
    /// </summary>
    /// <param name="clientData">
    /// The optional application-defined context data that was originally
    /// passed to the <see cref="ISQLiteSession.SetTableFilter" /> or
    /// <see cref="ISQLiteChangeSet.Apply(SessionConflictCallback,SessionTableFilterCallback,object)" />
    /// methods.  This value may be null.
    /// </param>
    /// <param name="name">
    /// The name of the table.
    /// </param>
    /// <returns>
    /// Non-zero if changes to the table should be considered; otherwise,
    /// zero.  Throwing an exception from this callback will result in
    /// undefined behavior.
    /// </returns>
    public delegate bool SessionTableFilterCallback(
        object clientData,
        string name
    );

    ///////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// This callback is invoked when there is a conflict while apply changes
    /// to a database.
    /// </summary>
    /// <param name="clientData">
    /// The optional application-defined context data that was originally
    /// passed to the
    /// <see cref="ISQLiteChangeSet.Apply(SessionConflictCallback,SessionTableFilterCallback,object)" />
    /// method.  This value may be null.
    /// </param>
    /// <param name="type">
    /// The type of this conflict.
    /// </param>
    /// <param name="item">
    /// The <see cref="ISQLiteChangeSetMetadataItem" /> object associated with
    /// this conflict.  This value may not be null; however, only properties
    /// that are applicable to the conflict type will be available.  Further
    /// information on this is available within the descriptions of the
    /// available <see cref="SQLiteChangeSetConflictType" /> values.
    /// </param>
    /// <returns>
    /// A <see cref="SQLiteChangeSetConflictResult" /> value that indicates the
    /// action to be taken in order to resolve the conflict.  Throwing an
    /// exception from this callback will result in undefined behavior.
    /// </returns>
    public delegate SQLiteChangeSetConflictResult SessionConflictCallback(
        object clientData,
        SQLiteChangeSetConflictType type,
        ISQLiteChangeSetMetadataItem item
    );
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region ISQLiteChangeSet Interface
    /// <summary>
    /// This interface contains methods used to manipulate a set of changes for
    /// a database.
    /// </summary>
    public interface ISQLiteChangeSet :
        IEnumerable<ISQLiteChangeSetMetadataItem>, IDisposable
    {
        /// <summary>
        /// This method "inverts" the set of changes within this instance.
        /// Applying an inverted set of changes to a database reverses the
        /// effects of applying the uninverted changes.  Specifically:
        /// <![CDATA[<ul>]]><![CDATA[<li>]]>
        /// Each DELETE change is changed to an INSERT, and
        /// <![CDATA[</li>]]><![CDATA[<li>]]>
        /// Each INSERT change is changed to a DELETE, and
        /// <![CDATA[</li>]]><![CDATA[<li>]]>
        /// For each UPDATE change, the old.* and new.* values are exchanged.
        /// <![CDATA[</li>]]><![CDATA[</ul>]]>
        /// This method does not change the order in which changes appear
        /// within the set of changes. It merely reverses the sense of each
        /// individual change.
        /// </summary>
        /// <returns>
        /// The new <see cref="ISQLiteChangeSet" /> instance that represents
        /// the resulting set of changes -OR- null if it is not available.
        /// </returns>
        ISQLiteChangeSet Invert();

        /// <summary>
        /// This method combines the specified set of changes with the ones
        /// contained in this instance.
        /// </summary>
        /// <param name="changeSet">
        /// The changes to be combined with those in this instance.
        /// </param>
        /// <returns>
        /// The new <see cref="ISQLiteChangeSet" /> instance that represents
        /// the resulting set of changes -OR- null if it is not available.
        /// </returns>
        ISQLiteChangeSet CombineWith(ISQLiteChangeSet changeSet);

        /// <summary>
        /// Attempts to apply the set of changes in this instance to the
        /// associated database.
        /// </summary>
        /// <param name="conflictCallback">
        /// The <see cref="SessionConflictCallback" /> delegate that will need
        /// to handle any conflicting changes that may arise.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        void Apply(
            SessionConflictCallback conflictCallback,
            object clientData
        );

        /// <summary>
        /// Attempts to apply the set of changes in this instance to the
        /// associated database.
        /// </summary>
        /// <param name="conflictCallback">
        /// The <see cref="SessionConflictCallback" /> delegate that will need
        /// to handle any conflicting changes that may arise.
        /// </param>
        /// <param name="tableFilterCallback">
        /// The optional <see cref="SessionTableFilterCallback" /> delegate
        /// that can be used to filter the list of tables impacted by the set
        /// of changes.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        void Apply(
            SessionConflictCallback conflictCallback,
            SessionTableFilterCallback tableFilterCallback,
            object clientData
        );
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region ISQLiteChangeGroup Interface
    /// <summary>
    /// This interface contains methods used to manipulate multiple sets of
    /// changes for a database.
    /// </summary>
    public interface ISQLiteChangeGroup : IDisposable
    {
        /// <summary>
        /// Attempts to add a change set (or patch set) to this change group
        /// instance.  The underlying data must be contained entirely within
        /// the <paramref name="rawData" /> byte array.
        /// </summary>
        /// <param name="rawData">
        /// The raw byte data for the specified change set (or patch set).
        /// </param>
        void AddChangeSet(byte[] rawData);

        /// <summary>
        /// Attempts to add a change set (or patch set) to this change group
        /// instance.  The underlying data will be read from the specified
        /// <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="Stream" /> instance containing the raw change set
        /// (or patch set) data to read.
        /// </param>
        void AddChangeSet(Stream stream);

        /// <summary>
        /// Attempts to create and return, via <paramref name="rawData" />, the
        /// combined set of changes represented by this change group instance.
        /// </summary>
        /// <param name="rawData">
        /// Upon success, this will contain the raw byte data for all the
        /// changes in this change group instance.
        /// </param>
        void CreateChangeSet(ref byte[] rawData);

        /// <summary>
        /// Attempts to create and write, via <paramref name="stream" />, the
        /// combined set of changes represented by this change group instance.
        /// </summary>
        /// <param name="stream">
        /// Upon success, the raw byte data for all the changes in this change
        /// group instance will be written to this <see cref="Stream" />.
        /// </param>
        void CreateChangeSet(Stream stream);
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region ISQLiteChangeSetMetadataItem Interface
    /// <summary>
    /// This interface contains properties and methods used to fetch metadata
    /// about one change within a set of changes for a database.
    /// </summary>
    public interface ISQLiteChangeSetMetadataItem : IDisposable
    {
        /// <summary>
        /// The name of the table the change was made to.
        /// </summary>
        string TableName { get; }

        /// <summary>
        /// The number of columns impacted by this change.  This value can be
        /// used to determine the highest valid column index that may be used
        /// with the <see cref="GetOldValue" />, <see cref="GetNewValue" />,
        /// and <see cref="GetConflictValue" /> methods of this interface.  It
        /// will be this value minus one.
        /// </summary>
        int NumberOfColumns { get; }

        /// <summary>
        /// This will contain the value
        /// <see cref="SQLiteAuthorizerActionCode.Insert" />,
        /// <see cref="SQLiteAuthorizerActionCode.Update" />, or
        /// <see cref="SQLiteAuthorizerActionCode.Delete" />, corresponding to
        /// the overall type of change this item represents.
        /// </summary>
        SQLiteAuthorizerActionCode OperationCode { get; }

        /// <summary>
        /// Non-zero if this change is considered to be indirect (i.e. as
        /// though they were made via a trigger or foreign key action).
        /// </summary>
        bool Indirect { get; }

        /// <summary>
        /// This array contains a <see cref="Boolean" /> for each column in
        /// the table associated with this change.  The element will be zero
        /// if the column is not part of the primary key; otherwise, it will
        /// be non-zero.
        /// </summary>
        bool[] PrimaryKeyColumns { get; }

        /// <summary>
        /// This method may only be called from within a
        /// <see cref="SessionConflictCallback" /> delegate when the conflict
        /// type is <see cref="SQLiteChangeSetConflictType.ForeignKey" />.  It
        /// returns the total number of known foreign key violations in the
        /// destination database.
        /// </summary>
        int NumberOfForeignKeyConflicts { get; }

        /// <summary>
        /// Queries and returns the original value of a given column for this
        /// change.  This method may only be called when the
        /// <see cref="OperationCode" /> has a value of
        /// <see cref="SQLiteAuthorizerActionCode.Update" /> or
        /// <see cref="SQLiteAuthorizerActionCode.Delete" />.
        /// </summary>
        /// <param name="columnIndex">
        /// The index for the column.  This value must be between zero and one
        /// less than the total number of columns for this table.
        /// </param>
        /// <returns>
        /// The original value of a given column for this change.
        /// </returns>
        SQLiteValue GetOldValue(int columnIndex);

        /// <summary>
        /// Queries and returns the updated value of a given column for this
        /// change.  This method may only be called when the
        /// <see cref="OperationCode" /> has a value of
        /// <see cref="SQLiteAuthorizerActionCode.Insert" /> or
        /// <see cref="SQLiteAuthorizerActionCode.Update" />.
        /// </summary>
        /// <param name="columnIndex">
        /// The index for the column.  This value must be between zero and one
        /// less than the total number of columns for this table.
        /// </param>
        /// <returns>
        /// The updated value of a given column for this change.
        /// </returns>
        SQLiteValue GetNewValue(int columnIndex);

        /// <summary>
        /// Queries and returns the conflicting value of a given column for
        /// this change.  This method may only be called from within a
        /// <see cref="SessionConflictCallback" /> delegate when the conflict
        /// type is <see cref="SQLiteChangeSetConflictType.Data" /> or
        /// <see cref="SQLiteChangeSetConflictType.Conflict" />.
        /// </summary>
        /// <param name="columnIndex">
        /// The index for the column.  This value must be between zero and one
        /// less than the total number of columns for this table.
        /// </param>
        /// <returns>
        /// The conflicting value of a given column for this change.
        /// </returns>
        SQLiteValue GetConflictValue(int columnIndex);
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region ISQLiteSession Interface
    /// <summary>
    /// This interface contains methods to query and manipulate the state of a
    /// change tracking session for a database.
    /// </summary>
    public interface ISQLiteSession : IDisposable
    {
        /// <summary>
        /// Determines if this session is currently tracking changes to its
        /// associated database.
        /// </summary>
        /// <returns>
        /// Non-zero if changes to the associated database are being trakced;
        /// otherwise, zero.
        /// </returns>
        bool IsEnabled();

        /// <summary>
        /// Enables tracking of changes to the associated database.
        /// </summary>
        void SetToEnabled();

        /// <summary>
        /// Disables tracking of changes to the associated database.
        /// </summary>
        void SetToDisabled();

        /// <summary>
        /// Determines if this session is currently set to mark changes as
        /// indirect (i.e. as though they were made via a trigger or foreign
        /// key action).
        /// </summary>
        /// <returns>
        /// Non-zero if changes to the associated database are being marked as
        /// indirect; otherwise, zero.
        /// </returns>
        bool IsIndirect();

        /// <summary>
        /// Sets the indirect flag for this session.  Subsequent changes will
        /// be marked as indirect until this flag is changed again.
        /// </summary>
        void SetToIndirect();

        /// <summary>
        /// Clears the indirect flag for this session.  Subsequent changes will
        /// be marked as direct until this flag is changed again.
        /// </summary>
        void SetToDirect();

        /// <summary>
        /// Determines if there are any tracked changes currently within the
        /// data for this session.
        /// </summary>
        /// <returns>
        /// Non-zero if there are no changes within the data for this session;
        /// otherwise, zero.
        /// </returns>
        bool IsEmpty();

        /// <summary>
        /// Upon success, causes changes to the specified table(s) to start
        /// being tracked.  Any tables impacted by calls to this method will
        /// not cause the <see cref="SessionTableFilterCallback" /> callback
        /// to be invoked.
        /// </summary>
        /// <param name="name">
        /// The name of the table to be tracked -OR- null to track all
        /// applicable tables within this database.
        /// </param>
        void AttachTable(string name);

        /// <summary>
        /// This method is used to set the table filter for this instance.
        /// </summary>
        /// <param name="callback">
        /// The table filter callback -OR- null to clear any existing table
        /// filter callback.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        void SetTableFilter(
            SessionTableFilterCallback callback,
            object clientData
        );

        /// <summary>
        /// Attempts to create and return, via <paramref name="rawData" />, the
        /// combined set of changes represented by this session instance.
        /// </summary>
        /// <param name="rawData">
        /// Upon success, this will contain the raw byte data for all the
        /// changes in this session instance.
        /// </param>
        void CreateChangeSet(ref byte[] rawData);

        /// <summary>
        /// Attempts to create and write, via <paramref name="stream" />, the
        /// combined set of changes represented by this session instance.
        /// </summary>
        /// <param name="stream">
        /// Upon success, the raw byte data for all the changes in this session
        /// instance will be written to this <see cref="Stream" />.
        /// </param>
        void CreateChangeSet(Stream stream);

        /// <summary>
        /// Attempts to create and return, via <paramref name="rawData" />, the
        /// combined set of changes represented by this session instance as a
        /// patch set.
        /// </summary>
        /// <param name="rawData">
        /// Upon success, this will contain the raw byte data for all the
        /// changes in this session instance.
        /// </param>
        void CreatePatchSet(ref byte[] rawData);

        /// <summary>
        /// Attempts to create and write, via <paramref name="stream" />, the
        /// combined set of changes represented by this session instance as a
        /// patch set.
        /// </summary>
        /// <param name="stream">
        /// Upon success, the raw byte data for all the changes in this session
        /// instance will be written to this <see cref="Stream" />.
        /// </param>
        void CreatePatchSet(Stream stream);

        /// <summary>
        /// This method loads the differences between two tables [with the same
        /// name, set of columns, and primary key definition] into this session
        /// instance.
        /// </summary>
        /// <param name="fromDatabaseName">
        /// The name of the database containing the table with the original
        /// data (i.e. it will need updating in order to be identical to the
        /// one within the database associated with this session instance).
        /// </param>
        /// <param name="tableName">
        /// The name of the table.
        /// </param>
        void LoadDifferencesFromTable(
            string fromDatabaseName,
            string tableName
        );
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteSessionHelpers Class
    /// <summary>
    /// This class contains some static helper methods for use within this
    /// subsystem.
    /// </summary>
    internal static class SQLiteSessionHelpers
    {
        #region Public Methods
        /// <summary>
        /// This method checks the byte array specified by the caller to make
        /// sure it will be usable.
        /// </summary>
        /// <param name="rawData">
        /// A byte array provided by the caller into one of the public methods
        /// for the classes that belong to this subsystem.  This value cannot
        /// be null or represent an empty array; otherwise, an appropriate
        /// exception will be thrown.
        /// </param>
        public static void CheckRawData(
            byte[] rawData
            )
        {
            if (rawData == null)
                throw new ArgumentNullException("rawData");

            if (rawData.Length == 0)
            {
                throw new ArgumentException(
                    "empty change set data", "rawData");
            }
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteConnectionLock Class
    /// <summary>
    /// This class is used to hold the native connection handle associated with
    /// a <see cref="SQLiteConnection" /> open until this subsystem is totally
    /// done with it.  This class is for internal use by this subsystem only.
    /// </summary>
    internal abstract class SQLiteConnectionLock : IDisposable
    {
        #region Private Constants
        /// <summary>
        /// The SQL statement used when creating the native statement handle.
        /// There are no special requirements for this other than counting as
        /// an "open statement handle".
        /// </summary>
        private const string LockNopSql = "SELECT 1;";

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// The format of the error message used when reporting, during object
        /// disposal, that the statement handle is still open (i.e. because
        /// this situation is considered a fairly serious programming error).
        /// </summary>
        private const string StatementMessageFormat =
            "Connection lock object was {0} with statement {1}";
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Data
        /// <summary>
        /// The wrapped native connection handle associated with this lock.
        /// </summary>
        private SQLiteConnectionHandle handle;

        /// <summary>
        /// The flags associated with the connection represented by the
        /// <see cref="handle" /> value.
        /// </summary>
        private SQLiteConnectionFlags flags;

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// The native statement handle for this lock.  The garbage collector
        /// cannot cause this statement to be finalized; therefore, it will
        /// serve to hold the associated native connection open until it is
        /// freed manually using the <see cref="Unlock" /> method.
        /// </summary>
        private IntPtr statement;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Constructors
        /// <summary>
        /// Constructs a new instance of this class using the specified wrapped
        /// native connection handle and associated flags.
        /// </summary>
        /// <param name="handle">
        /// The wrapped native connection handle to be associated with this
        /// lock.
        /// </param>
        /// <param name="flags">
        /// The flags associated with the connection represented by the
        /// <paramref name="handle" /> value.
        /// </param>
        /// <param name="autoLock">
        /// Non-zero if the <see cref="Lock" /> method should be called prior
        /// to returning from this constructor.
        /// </param>
        public SQLiteConnectionLock(
            SQLiteConnectionHandle handle,
            SQLiteConnectionFlags flags,
            bool autoLock
            )
        {
            this.handle = handle;
            this.flags = flags;

            if (autoLock)
                Lock();
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Protected Methods
        /// <summary>
        /// Queries and returns the wrapped native connection handle for this
        /// instance.
        /// </summary>
        /// <returns>
        /// The wrapped native connection handle for this instance -OR- null
        /// if it is unavailable.
        /// </returns>
        protected SQLiteConnectionHandle GetHandle()
        {
            return handle;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Queries and returns the flags associated with the connection for
        /// this instance.
        /// </summary>
        /// <returns>
        /// The <see cref="SQLiteConnectionFlags" /> value.  There is no return
        /// value reserved to indicate an error.
        /// </returns>
        protected SQLiteConnectionFlags GetFlags()
        {
            return flags;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Queries and returns the native connection handle for this instance.
        /// </summary>
        /// <returns>
        /// The native connection handle for this instance.  If this value is
        /// unavailable or invalid an exception will be thrown.
        /// </returns>
        protected IntPtr GetIntPtr()
        {
            if (handle == null)
            {
                throw new InvalidOperationException(
                    "Connection lock object has an invalid handle.");
            }

            IntPtr handlePtr = handle;

            if (handlePtr == IntPtr.Zero)
            {
                throw new InvalidOperationException(
                    "Connection lock object has an invalid handle pointer.");
            }

            return handlePtr;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Methods
        /// <summary>
        /// This method attempts to "lock" the associated native connection
        /// handle by preparing a SQL statement that will not be finalized
        /// until the <see cref="Unlock" /> method is called (i.e. and which
        /// cannot be done by the garbage collector).  If the statement is
        /// already prepared, nothing is done.  If the statement cannot be
        /// prepared for any reason, an exception will be thrown.
        /// </summary>
        public void Lock()
        {
            CheckDisposed();

            if (statement != IntPtr.Zero)
                return;

            IntPtr pSql = IntPtr.Zero;

            try
            {
                int nSql = 0;

                pSql = SQLiteString.Utf8IntPtrFromString(LockNopSql, ref nSql);

                IntPtr pRemain = IntPtr.Zero;
                int nRemain = 0;

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3_prepare_interop(
                    GetIntPtr(), pSql, nSql, ref statement, ref pRemain,
                    ref nRemain);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3_prepare_interop");
            }
            finally
            {
                if (pSql != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pSql);
                    pSql = IntPtr.Zero;
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// This method attempts to "unlock" the associated native connection
        /// handle by finalizing the previously prepared statement.  If the
        /// statement is already finalized, nothing is done.  If the statement
        /// cannot be finalized for any reason, an exception will be thrown.
        /// </summary>
        public void Unlock()
        {
            CheckDisposed();

            if (statement == IntPtr.Zero)
                return;

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3_finalize_interop(
                statement);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3_finalize_interop");

            statement = IntPtr.Zero;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable Members
        /// <summary>
        /// Disposes of this object instance.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteConnectionLock).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    //if (disposing)
                    //{
                    //    ////////////////////////////////////
                    //    // dispose managed resources here...
                    //    ////////////////////////////////////
                    //}

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////

                    if (statement != IntPtr.Zero)
                    {
                        //
                        // NOTE: This should never happen.  This object was
                        //       disposed (or finalized) without the Unlock
                        //       method being called first.
                        //
                        try
                        {
                            if (HelperMethods.LogPrepare(GetFlags()))
                            {
                                /* throw */
                                SQLiteLog.LogMessage(
                                    SQLiteErrorCode.Misuse,
                                    HelperMethods.StringFormat(
                                    CultureInfo.CurrentCulture,
                                    StatementMessageFormat, disposing ?
                                        "disposed" : "finalized",
                                    statement));
                            }
                        }
                        catch
                        {
                            // do nothing.
                        }

#if DEBUG
                        Debugger.Break();
#endif
                    }
                }
            }
            finally
            {
                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Destructor
        /// <summary>
        /// Finalizes this object instance.
        /// </summary>
        ~SQLiteConnectionLock()
        {
            Dispose(false);
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteChangeSetIterator Class
    /// <summary>
    /// This class manages the native change set iterator.  It is used as the
    /// base class for the <see cref="SQLiteMemoryChangeSetIterator" /> and
    /// <see cref="SQLiteStreamChangeSetIterator" /> classes.  It knows how to
    /// advance the native iterator handle as well as finalize it.
    /// </summary>
    internal class SQLiteChangeSetIterator : IDisposable
    {
        #region Private Data
        /// <summary>
        /// The native change set (a.k.a. iterator) handle.
        /// </summary>
        private IntPtr iterator;

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Non-zero if this instance owns the native iterator handle in the
        /// <see cref="iterator" /> field.  In that case, this instance will
        /// finalize the native iterator handle upon being disposed or
        /// finalized.
        /// </summary>
        private bool ownHandle;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Protected Constructors
        /// <summary>
        /// Constructs a new instance of this class using the specified native
        /// iterator handle.
        /// </summary>
        /// <param name="iterator">
        /// The native iterator handle to use.
        /// </param>
        /// <param name="ownHandle">
        /// Non-zero if this instance is to take ownership of the native
        /// iterator handle specified by <paramref name="iterator" />.
        /// </param>
        protected SQLiteChangeSetIterator(
            IntPtr iterator,
            bool ownHandle
            )
        {
            this.iterator = iterator;
            this.ownHandle = ownHandle;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        /// <summary>
        /// Throws an exception if the native iterator handle is invalid.
        /// </summary>
        internal void CheckHandle()
        {
            if (iterator == IntPtr.Zero)
                throw new InvalidOperationException("iterator is not open");
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Used to query the native iterator handle.  This method is only used
        /// by the <see cref="SQLiteChangeSetMetadataItem" /> class.
        /// </summary>
        /// <returns>
        /// The native iterator handle -OR- <see cref="IntPtr.Zero" /> if it
        /// is not available.
        /// </returns>
        internal IntPtr GetIntPtr()
        {
            return iterator;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Methods
        /// <summary>
        /// Attempts to advance the native iterator handle to its next item.
        /// </summary>
        /// <returns>
        /// Non-zero if the native iterator handle was advanced and contains
        /// more data; otherwise, zero.  If the underlying native API returns
        /// an unexpected value then an exception will be thrown.
        /// </returns>
        public bool Next()
        {
            CheckDisposed();
            CheckHandle();

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_next(
                iterator);

            switch (rc)
            {
                case SQLiteErrorCode.Ok:
                    {
                        throw new SQLiteException(SQLiteErrorCode.Ok,
                            "sqlite3changeset_next: unexpected result Ok");
                    }
                case SQLiteErrorCode.Row:
                    {
                        return true;
                    }
                case SQLiteErrorCode.Done:
                    {
                        return false;
                    }
                default:
                    {
                        throw new SQLiteException(rc, "sqlite3changeset_next");
                    }
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Static "Factory" Methods
        /// <summary>
        /// Attempts to create an instance of this class that is associated
        /// with the specified native iterator handle.  Ownership of the
        /// native iterator handle is NOT transferred to the new instance of
        /// this class.
        /// </summary>
        /// <param name="iterator">
        /// The native iterator handle to use.
        /// </param>
        /// <returns>
        /// The new instance of this class.  No return value is reserved to
        /// indicate an error; however, if the native iterator handle is not
        /// valid, any subsequent attempt to make use of it via the returned
        /// instance of this class may throw exceptions.
        /// </returns>
        public static SQLiteChangeSetIterator Attach(
            IntPtr iterator
            )
        {
            return new SQLiteChangeSetIterator(iterator, false);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable Members
        /// <summary>
        /// Disposes of this object instance.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteChangeSetIterator).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    //if (disposing)
                    //{
                    //    ////////////////////////////////////
                    //    // dispose managed resources here...
                    //    ////////////////////////////////////
                    //}

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////

                    if (iterator != IntPtr.Zero)
                    {
                        if (ownHandle)
                        {
                            UnsafeNativeMethods.sqlite3changeset_finalize(
                                iterator);
                        }

                        iterator = IntPtr.Zero;
                    }
                }
            }
            finally
            {
                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Destructor
        /// <summary>
        /// Finalizes this object instance.
        /// </summary>
        ~SQLiteChangeSetIterator()
        {
            Dispose(false);
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteMemoryChangeSetIterator Class
    /// <summary>
    /// This class manages the native change set iterator for a set of changes
    /// contained entirely in memory.
    /// </summary>
    internal sealed class SQLiteMemoryChangeSetIterator :
        SQLiteChangeSetIterator
    {
        #region Private Data
        /// <summary>
        /// The native memory buffer allocated to contain the set of changes
        /// associated with this instance.  This will always be freed when this
        /// instance is disposed or finalized.
        /// </summary>
        private IntPtr pData;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Constructors
        /// <summary>
        /// Constructs an instance of this class using the specified native
        /// memory buffer and native iterator handle.
        /// </summary>
        /// <param name="pData">
        /// The native memory buffer to use.
        /// </param>
        /// <param name="iterator">
        /// The native iterator handle to use.
        /// </param>
        /// <param name="ownHandle">
        /// Non-zero if this instance is to take ownership of the native
        /// iterator handle specified by <paramref name="iterator" />.
        /// </param>
        private SQLiteMemoryChangeSetIterator(
            IntPtr pData,
            IntPtr iterator,
            bool ownHandle
            )
            : base(iterator, ownHandle)
        {
            this.pData = pData;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Static "Factory" Methods
        /// <summary>
        /// Attempts to create an instance of this class using the specified
        /// raw byte data.
        /// </summary>
        /// <param name="rawData">
        /// The raw byte data containing the set of changes for this native
        /// iterator.
        /// </param>
        /// <returns>
        /// The new instance of this class -OR- null if it cannot be created.
        /// </returns>
        public static SQLiteMemoryChangeSetIterator Create(
            byte[] rawData
            )
        {
            SQLiteSessionHelpers.CheckRawData(rawData);

            SQLiteMemoryChangeSetIterator result = null;
            IntPtr pData = IntPtr.Zero;
            IntPtr iterator = IntPtr.Zero;

            try
            {
                int nData = 0;

                pData = SQLiteBytes.ToIntPtr(rawData, ref nData);

                if (pData == IntPtr.Zero)
                    throw new SQLiteException(SQLiteErrorCode.NoMem, null);

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_start(
                    ref iterator, nData, pData);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3changeset_start");

                result = new SQLiteMemoryChangeSetIterator(
                    pData, iterator, true);
            }
            finally
            {
                if (result == null)
                {
                    if (iterator != IntPtr.Zero)
                    {
                        UnsafeNativeMethods.sqlite3changeset_finalize(
                            iterator);

                        iterator = IntPtr.Zero;
                    }

                    if (pData != IntPtr.Zero)
                    {
                        SQLiteMemory.Free(pData);
                        pData = IntPtr.Zero;
                    }
                }
            }

            return result;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteMemoryChangeSetIterator).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            //
            // NOTE: Must dispose of the base class first (leaky abstraction)
            //       because it contains the iterator handle, which must be
            //       closed *prior* to freeing the underlying memory.
            //
            base.Dispose(disposing);

            try
            {
                if (!disposed)
                {
                    //if (disposing)
                    //{
                    //    ////////////////////////////////////
                    //    // dispose managed resources here...
                    //    ////////////////////////////////////
                    //}

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////

                    if (pData != IntPtr.Zero)
                    {
                        SQLiteMemory.Free(pData);
                        pData = IntPtr.Zero;
                    }
                }
            }
            finally
            {
                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteStreamChangeSetIterator Class
    /// <summary>
    /// This class manages the native change set iterator for a set of changes
    /// backed by a <see cref="Stream" /> instance.
    /// </summary>
    internal sealed class SQLiteStreamChangeSetIterator :
        SQLiteChangeSetIterator
    {
        #region Private Data
        /// <summary>
        /// The <see cref="SQLiteStreamAdapter" /> instance that is managing
        /// the underlying <see cref="Stream" /> used as the backing store for
        /// the set of changes associated with this native change set iterator.
        /// </summary>
        private SQLiteStreamAdapter streamAdapter;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Constructors
        /// <summary>
        /// Constructs an instance of this class using the specified native
        /// iterator handle and <see cref="SQLiteStreamAdapter" />.
        /// </summary>
        /// <param name="streamAdapter">
        /// The <see cref="SQLiteStreamAdapter" /> instance to use.
        /// </param>
        /// <param name="iterator">
        /// The native iterator handle to use.
        /// </param>
        /// <param name="ownHandle">
        /// Non-zero if this instance is to take ownership of the native
        /// iterator handle specified by <paramref name="iterator" />.
        /// </param>
        private SQLiteStreamChangeSetIterator(
            SQLiteStreamAdapter streamAdapter,
            IntPtr iterator,
            bool ownHandle
            )
            : base(iterator, ownHandle)
        {
            this.streamAdapter = streamAdapter;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Static "Factory" Methods
        /// <summary>
        /// Attempts to create an instance of this class using the specified
        /// <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="Stream" /> where the raw byte data for the set of
        /// changes may be read.
        /// </param>
        /// <param name="flags">
        /// The flags associated with the parent connection.
        /// </param>
        /// <returns>
        /// The new instance of this class -OR- null if it cannot be created.
        /// </returns>
        public static SQLiteStreamChangeSetIterator Create(
            Stream stream,
            SQLiteConnectionFlags flags
            )
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            SQLiteStreamAdapter streamAdapter = null;
            SQLiteStreamChangeSetIterator result = null;
            IntPtr iterator = IntPtr.Zero;

            try
            {
                streamAdapter = new SQLiteStreamAdapter(stream, flags);

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_start_strm(
                    ref iterator, streamAdapter.GetInputDelegate(), IntPtr.Zero);

                if (rc != SQLiteErrorCode.Ok)
                {
                    throw new SQLiteException(
                        rc, "sqlite3changeset_start_strm");
                }

                result = new SQLiteStreamChangeSetIterator(
                    streamAdapter, iterator, true);
            }
            finally
            {
                if (result == null)
                {
                    if (iterator != IntPtr.Zero)
                    {
                        UnsafeNativeMethods.sqlite3changeset_finalize(
                            iterator);

                        iterator = IntPtr.Zero;
                    }

                    if (streamAdapter != null)
                    {
                        streamAdapter.Dispose();
                        streamAdapter = null;
                    }
                }
            }

            return result;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteStreamChangeSetIterator).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    //if (disposing)
                    //{
                    //    ////////////////////////////////////
                    //    // dispose managed resources here...
                    //    ////////////////////////////////////
                    //}

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////
                }
            }
            finally
            {
                base.Dispose(disposing);

                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteStreamAdapter Class
    /// <summary>
    /// This class is used to act as a bridge between a <see cref="Stream" />
    /// instance and the delegates used with the native streaming API.
    /// </summary>
    internal sealed class SQLiteStreamAdapter : IDisposable
    {
        #region Private Data
        /// <summary>
        /// The managed stream instance used to in order to service the native
        /// delegates for both input and output.
        /// </summary>
        private Stream stream;

        /// <summary>
        /// The flags associated with the connection.
        /// </summary>
        private SQLiteConnectionFlags flags;

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// The delegate used to provide input to the native streaming API.
        /// It will be null -OR- point to the <see cref="Input" /> method.
        /// </summary>
        private UnsafeNativeMethods.xSessionInput xInput;

        /// <summary>
        /// The delegate used to provide output to the native streaming API.
        /// It will be null -OR- point to the <see cref="Output" /> method.
        /// </summary>
        private UnsafeNativeMethods.xSessionOutput xOutput;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Constructors
        /// <summary>
        /// Constructs a new instance of this class using the specified managed
        /// stream and connection flags.
        /// </summary>
        /// <param name="stream">
        /// The managed stream instance to be used in order to service the
        /// native delegates for both input and output.
        /// </param>
        /// <param name="flags">
        /// The flags associated with the parent connection.
        /// </param>
        public SQLiteStreamAdapter(
            Stream stream,
            SQLiteConnectionFlags flags
            )
        {
            this.stream = stream;
            this.flags = flags;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        /// <summary>
        /// Queries and returns the flags associated with the connection for
        /// this instance.
        /// </summary>
        /// <returns>
        /// The <see cref="SQLiteConnectionFlags" /> value.  There is no return
        /// value reserved to indicate an error.
        /// </returns>
        private SQLiteConnectionFlags GetFlags()
        {
            return flags;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Methods
        /// <summary>
        /// Returns a delegate that wraps the <see cref="Input" /> method,
        /// creating it first if necessary.
        /// </summary>
        /// <returns>
        /// A delegate that refers to the <see cref="Input" /> method.
        /// </returns>
        public UnsafeNativeMethods.xSessionInput GetInputDelegate()
        {
            CheckDisposed();

            if (xInput == null)
                xInput = new UnsafeNativeMethods.xSessionInput(Input);

            return xInput;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Returns a delegate that wraps the <see cref="Output" /> method,
        /// creating it first if necessary.
        /// </summary>
        /// <returns>
        /// A delegate that refers to the <see cref="Output" /> method.
        /// </returns>
        public UnsafeNativeMethods.xSessionOutput GetOutputDelegate()
        {
            CheckDisposed();

            if (xOutput == null)
                xOutput = new UnsafeNativeMethods.xSessionOutput(Output);

            return xOutput;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Native Callback Methods
        /// <summary>
        /// This method attempts to read <paramref name="nData" /> bytes from
        /// the managed stream, writing them to the <paramref name="pData"/>
        /// buffer.
        /// </summary>
        /// <param name="context">
        /// Optional extra context information.  Currently, this will always
        /// have a value of <see cref="IntPtr.Zero" />.
        /// </param>
        /// <param name="pData">
        /// A preallocated native buffer to receive the requested input bytes.
        /// It must be at least <paramref name="nData" /> bytes in size.
        /// </param>
        /// <param name="nData">
        /// Upon entry, the number of bytes to read.  Upon exit, the number of
        /// bytes actually read.  This value may be zero upon exit.
        /// </param>
        /// <returns>
        /// The value <see cref="SQLiteErrorCode.Ok" /> upon success -OR- an
        /// appropriate error code upon failure.
        /// </returns>
        private SQLiteErrorCode Input(
            IntPtr context,
            IntPtr pData,
            ref int nData
            )
        {
            try
            {
                Stream localStream = stream;

                if (localStream == null)
                    return SQLiteErrorCode.Misuse;

                if (nData > 0)
                {
                    byte[] bytes = new byte[nData];
                    int nRead = localStream.Read(bytes, 0, nData);

                    if ((nRead > 0) && (pData != IntPtr.Zero))
                        Marshal.Copy(bytes, 0, pData, nRead);

                    nData = nRead;
                }

                return SQLiteErrorCode.Ok;
            }
            catch (Exception e)
            {
                try
                {
                    if (HelperMethods.LogCallbackExceptions(GetFlags()))
                    {
                        SQLiteLog.LogMessage(
                            SQLiteBase.COR_E_EXCEPTION,
                            HelperMethods.StringFormat(
                            CultureInfo.CurrentCulture,
                            UnsafeNativeMethods.ExceptionMessageFormat,
                            "xSessionInput", e)); /* throw */
                    }
                }
                catch
                {
                    // do nothing.
                }
            }

            return SQLiteErrorCode.IoErr_Read;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// This method attempts to write <paramref name="nData" /> bytes to
        /// the managed stream, reading them from the <paramref name="pData"/>
        /// buffer.
        /// </summary>
        /// <param name="context">
        /// Optional extra context information.  Currently, this will always
        /// have a value of <see cref="IntPtr.Zero" />.
        /// </param>
        /// <param name="pData">
        /// A preallocated native buffer containing the requested output
        /// bytes.  It must be at least <paramref name="nData" /> bytes in
        /// size.
        /// </param>
        /// <param name="nData">
        /// The number of bytes to write.
        /// </param>
        /// <returns>
        /// The value <see cref="SQLiteErrorCode.Ok" /> upon success -OR- an
        /// appropriate error code upon failure.
        /// </returns>
        private SQLiteErrorCode Output(
            IntPtr context,
            IntPtr pData,
            int nData
            )
        {
            try
            {
                Stream localStream = stream;

                if (localStream == null)
                    return SQLiteErrorCode.Misuse;

                if (nData > 0)
                {
                    byte[] bytes = new byte[nData];

                    if (pData != IntPtr.Zero)
                        Marshal.Copy(pData, bytes, 0, nData);

                    localStream.Write(bytes, 0, nData);
                }

                localStream.Flush();

                return SQLiteErrorCode.Ok;
            }
            catch (Exception e)
            {
                try
                {
                    if (HelperMethods.LogCallbackExceptions(GetFlags()))
                    {
                        SQLiteLog.LogMessage(
                            SQLiteBase.COR_E_EXCEPTION,
                            HelperMethods.StringFormat(
                            CultureInfo.CurrentCulture,
                            UnsafeNativeMethods.ExceptionMessageFormat,
                            "xSessionOutput", e)); /* throw */
                    }
                }
                catch
                {
                    // do nothing.
                }
            }

            return SQLiteErrorCode.IoErr_Write;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable Members
        /// <summary>
        /// Disposes of this object instance.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteStreamAdapter).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        private /* protected virtual */ void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////

                        if (xInput != null)
                            xInput = null;

                        if (xOutput != null)
                            xOutput = null;

                        if (stream != null)
                            stream = null; /* NOT OWNED */
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////
                }
            }
            finally
            {
                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Destructor
        /// <summary>
        /// Finalizes this object instance.
        /// </summary>
        ~SQLiteStreamAdapter()
        {
            Dispose(false);
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteSessionStreamManager Class
    /// <summary>
    /// This class manages a collection of <see cref="SQLiteStreamAdapter"/>
    /// instances. When used, it takes responsibility for creating, returning,
    /// and disposing of its <see cref="SQLiteStreamAdapter"/> instances.
    /// </summary>
    internal sealed class SQLiteSessionStreamManager : IDisposable
    {
        #region Private Data
        /// <summary>
        /// The managed collection of <see cref="SQLiteStreamAdapter" />
        /// instances, keyed by their associated <see cref="Stream" />
        /// instance.
        /// </summary>
        private Dictionary<Stream, SQLiteStreamAdapter> streamAdapters;

        /// <summary>
        /// The flags associated with the connection.
        /// </summary>
        private SQLiteConnectionFlags flags;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Constructors
        /// <summary>
        /// Constructs a new instance of this class using the specified
        /// connection flags.
        /// </summary>
        /// <param name="flags">
        /// The flags associated with the parent connection.
        /// </param>
        public SQLiteSessionStreamManager(
            SQLiteConnectionFlags flags
            )
        {
            this.flags = flags;

            InitializeStreamAdapters();
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        /// <summary>
        /// Makes sure the collection of <see cref="SQLiteStreamAdapter" />
        /// is created.
        /// </summary>
        private void InitializeStreamAdapters()
        {
            if (streamAdapters != null)
                return;

            streamAdapters = new Dictionary<Stream, SQLiteStreamAdapter>();
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Makes sure the collection of <see cref="SQLiteStreamAdapter" />
        /// is disposed.
        /// </summary>
        private void DisposeStreamAdapters()
        {
            if (streamAdapters == null)
                return;

            foreach (KeyValuePair<Stream, SQLiteStreamAdapter> pair
                    in streamAdapters)
            {
                SQLiteStreamAdapter streamAdapter = pair.Value;

                if (streamAdapter == null)
                    continue;

                streamAdapter.Dispose();
            }

            streamAdapters.Clear();
            streamAdapters = null;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Methods
        /// <summary>
        /// Attempts to return a <see cref="SQLiteStreamAdapter" /> instance
        /// suitable for the specified <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="Stream" /> instance.  If this value is null, a null
        /// value will be returned.
        /// </param>
        /// <returns>
        /// A <see cref="SQLiteStreamAdapter" /> instance.  Typically, these
        /// are always freshly created; however, this method is designed to
        /// return the existing <see cref="SQLiteStreamAdapter" /> instance
        /// associated with the specified stream, should one exist.
        /// </returns>
        public SQLiteStreamAdapter GetAdapter(
            Stream stream
            )
        {
            CheckDisposed();

            if (stream == null)
                return null;

            SQLiteStreamAdapter streamAdapter;

            if (streamAdapters.TryGetValue(stream, out streamAdapter))
                return streamAdapter;

            streamAdapter = new SQLiteStreamAdapter(stream, flags);
            streamAdapters.Add(stream, streamAdapter);

            return streamAdapter;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable Members
        /// <summary>
        /// Disposes of this object instance.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteSessionStreamManager).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        private /* protected virtual */ void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////

                        DisposeStreamAdapters();
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////
                }
            }
            finally
            {
                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Destructor
        /// <summary>
        /// Finalizes this object instance.
        /// </summary>
        ~SQLiteSessionStreamManager()
        {
            Dispose(false);
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteChangeGroup Class
    /// <summary>
    /// This class represents a group of change sets (or patch sets).
    /// </summary>
    internal sealed class SQLiteChangeGroup : ISQLiteChangeGroup
    {
        #region Private Data
        /// <summary>
        /// The <see cref="SQLiteSessionStreamManager" /> instance associated
        /// with this change group.
        /// </summary>
        private SQLiteSessionStreamManager streamManager;

        /// <summary>
        /// The flags associated with the connection.
        /// </summary>
        private SQLiteConnectionFlags flags;

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// The native handle for this change group.  This will be deleted when
        /// this instance is disposed or finalized.
        /// </summary>
        private IntPtr changeGroup;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Constructors
        /// <summary>
        /// Constructs a new instance of this class using the specified
        /// connection flags.
        /// </summary>
        /// <param name="flags">
        /// The flags associated with the parent connection.
        /// </param>
        public SQLiteChangeGroup(
            SQLiteConnectionFlags flags
            )
        {
            this.flags = flags;

            InitializeHandle();
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        /// <summary>
        /// Throws an exception if the native change group handle is invalid.
        /// </summary>
        private void CheckHandle()
        {
            if (changeGroup == IntPtr.Zero)
                throw new InvalidOperationException("change group not open");
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Makes sure the native change group handle is valid, creating it if
        /// necessary.
        /// </summary>
        private void InitializeHandle()
        {
            if (changeGroup != IntPtr.Zero)
                return;

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changegroup_new(
                ref changeGroup);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3changegroup_new");
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Makes sure the <see cref="SQLiteSessionStreamManager" /> instance
        /// is available, creating it if necessary.
        /// </summary>
        private void InitializeStreamManager()
        {
            if (streamManager != null)
                return;

            streamManager = new SQLiteSessionStreamManager(flags);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to return a <see cref="SQLiteStreamAdapter" /> instance
        /// suitable for the specified <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="Stream" /> instance.  If this value is null, a null
        /// value will be returned.
        /// </param>
        /// <returns>
        /// A <see cref="SQLiteStreamAdapter" /> instance.  Typically, these
        /// are always freshly created; however, this method is designed to
        /// return the existing <see cref="SQLiteStreamAdapter" /> instance
        /// associated with the specified stream, should one exist.
        /// </returns>
        private SQLiteStreamAdapter GetStreamAdapter(
            Stream stream
            )
        {
            InitializeStreamManager();

            return streamManager.GetAdapter(stream);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region ISQLiteChangeGroup Members
        /// <summary>
        /// Attempts to add a change set (or patch set) to this change group
        /// instance.  The underlying data must be contained entirely within
        /// the <paramref name="rawData" /> byte array.
        /// </summary>
        /// <param name="rawData">
        /// The raw byte data for the specified change set (or patch set).
        /// </param>
        public void AddChangeSet(
            byte[] rawData
            )
        {
            CheckDisposed();
            CheckHandle();

            SQLiteSessionHelpers.CheckRawData(rawData);

            IntPtr pData = IntPtr.Zero;

            try
            {
                int nData = 0;

                pData = SQLiteBytes.ToIntPtr(rawData, ref nData);

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changegroup_add(
                    changeGroup, nData, pData);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3changegroup_add");
            }
            finally
            {
                if (pData != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pData);
                    pData = IntPtr.Zero;
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to add a change set (or patch set) to this change group
        /// instance.  The underlying data will be read from the specified
        /// <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="Stream" /> instance containing the raw change set
        /// (or patch set) data to read.
        /// </param>
        public void AddChangeSet(
            Stream stream
            )
        {
            CheckDisposed();
            CheckHandle();

            if (stream == null)
                throw new ArgumentNullException("stream");

            SQLiteStreamAdapter streamAdapter = GetStreamAdapter(stream);

            if (streamAdapter == null)
            {
                throw new SQLiteException(
                    "could not get or create adapter for input stream");
            }

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changegroup_add_strm(
                changeGroup, streamAdapter.GetInputDelegate(), IntPtr.Zero);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3changegroup_add_strm");
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to create and return, via <paramref name="rawData" />, the
        /// combined set of changes represented by this change group instance.
        /// </summary>
        /// <param name="rawData">
        /// Upon success, this will contain the raw byte data for all the
        /// changes in this change group instance.
        /// </param>
        public void CreateChangeSet(
            ref byte[] rawData
            )
        {
            CheckDisposed();
            CheckHandle();

            SQLiteSessionHelpers.CheckRawData(rawData);

            IntPtr pData = IntPtr.Zero;

            try
            {
                int nData = 0;

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changegroup_output(
                    changeGroup, ref nData, ref pData);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3changegroup_output");

                rawData = SQLiteBytes.FromIntPtr(pData, nData);
            }
            finally
            {
                if (pData != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pData);
                    pData = IntPtr.Zero;
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to create and write, via <paramref name="stream" />, the
        /// combined set of changes represented by this change group instance.
        /// </summary>
        /// <param name="stream">
        /// Upon success, the raw byte data for all the changes in this change
        /// group instance will be written to this <see cref="Stream" />.
        /// </param>
        public void CreateChangeSet(
            Stream stream
            )
        {
            CheckDisposed();
            CheckHandle();

            if (stream == null)
                throw new ArgumentNullException("stream");

            SQLiteStreamAdapter streamAdapter = GetStreamAdapter(stream);

            if (streamAdapter == null)
            {
                throw new SQLiteException(
                    "could not get or create adapter for output stream");
            }

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changegroup_output_strm(
                changeGroup, streamAdapter.GetOutputDelegate(), IntPtr.Zero);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3changegroup_output_strm");
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable Members
        /// <summary>
        /// Disposes of this object instance.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteChangeGroup).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        private /* protected virtual */ void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////

                        if (streamManager != null)
                        {
                            streamManager.Dispose();
                            streamManager = null;
                        }
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////

                    if (changeGroup != IntPtr.Zero)
                    {
                        UnsafeNativeMethods.sqlite3changegroup_delete(
                            changeGroup);

                        changeGroup = IntPtr.Zero;
                    }
                }
            }
            finally
            {
                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Destructor
        /// <summary>
        /// Finalizes this object instance.
        /// </summary>
        ~SQLiteChangeGroup()
        {
            Dispose(false);
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteSession Class
    /// <summary>
    /// This class represents the change tracking session associated with a
    /// database.
    /// </summary>
    internal sealed class SQLiteSession : SQLiteConnectionLock, ISQLiteSession
    {
        #region Private Data
        /// <summary>
        /// The <see cref="SQLiteSessionStreamManager" /> instance associated
        /// with this session.
        /// </summary>
        private SQLiteSessionStreamManager streamManager;

        /// <summary>
        /// The name of the database (e.g. "main") for this session.
        /// </summary>
        private string databaseName;

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// The native handle for this session.  This will be deleted when
        /// this instance is disposed or finalized.
        /// </summary>
        private IntPtr session;

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// The delegate used to provide table filtering to the native API.
        /// It will be null -OR- point to the <see cref="Filter" /> method.
        /// </summary>
        private UnsafeNativeMethods.xSessionFilter xFilter;

        /// <summary>
        /// The managed callback used to filter tables for this session.  Set
        /// via the <see cref="SetTableFilter" /> method.
        /// </summary>
        private SessionTableFilterCallback tableFilterCallback;

        /// <summary>
        /// The optional application-defined context data that was passed to
        /// the <see cref="SetTableFilter" /> method.  This value may be null.
        /// </summary>
        private object tableFilterClientData;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Constructors
        /// <summary>
        /// Constructs a new instance of this class using the specified wrapped
        /// native connection handle and associated flags.
        /// </summary>
        /// <param name="handle">
        /// The wrapped native connection handle to be associated with this
        /// session.
        /// </param>
        /// <param name="flags">
        /// The flags associated with the connection represented by the
        /// <paramref name="handle" /> value.
        /// </param>
        /// <param name="databaseName">
        /// The name of the database (e.g. "main") for this session.
        /// </param>
        public SQLiteSession(
            SQLiteConnectionHandle handle,
            SQLiteConnectionFlags flags,
            string databaseName
            )
            : base(handle, flags, true)
        {
            this.databaseName = databaseName;

            InitializeHandle();
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        /// <summary>
        /// Throws an exception if the native session handle is invalid.
        /// </summary>
        private void CheckHandle()
        {
            if (session == IntPtr.Zero)
                throw new InvalidOperationException("session is not open");
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Makes sure the native session handle is valid, creating it if
        /// necessary.
        /// </summary>
        private void InitializeHandle()
        {
            if (session != IntPtr.Zero)
                return;

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3session_create(
                GetIntPtr(), SQLiteString.GetUtf8BytesFromString(databaseName),
                ref session);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3session_create");
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// This method sets up the internal table filtering associated state
        /// of this instance.
        /// </summary>
        /// <param name="callback">
        /// The table filter callback -OR- null to clear any existing table
        /// filter callback.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        /// <returns>
        /// The <see cref="UnsafeNativeMethods.xSessionFilter" /> native
        /// delegate -OR- null to clear any existing table filter.
        /// </returns>
        private UnsafeNativeMethods.xSessionFilter ApplyTableFilter(
            SessionTableFilterCallback callback, /* in: NULL OK */
            object clientData                    /* in: NULL OK */
            )
        {
            tableFilterCallback = callback;
            tableFilterClientData = clientData;

            if (callback == null)
            {
                if (xFilter != null)
                    xFilter = null;

                return null;
            }

            if (xFilter == null)
                xFilter = new UnsafeNativeMethods.xSessionFilter(Filter);

            return xFilter;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Makes sure the <see cref="SQLiteSessionStreamManager" /> instance
        /// is available, creating it if necessary.
        /// </summary>
        private void InitializeStreamManager()
        {
            if (streamManager != null)
                return;

            streamManager = new SQLiteSessionStreamManager(GetFlags());
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to return a <see cref="SQLiteStreamAdapter" /> instance
        /// suitable for the specified <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="Stream" /> instance.  If this value is null, a null
        /// value will be returned.
        /// </param>
        /// <returns>
        /// A <see cref="SQLiteStreamAdapter" /> instance.  Typically, these
        /// are always freshly created; however, this method is designed to
        /// return the existing <see cref="SQLiteStreamAdapter" /> instance
        /// associated with the specified stream, should one exist.
        /// </returns>
        private SQLiteStreamAdapter GetStreamAdapter(
            Stream stream
            )
        {
            InitializeStreamManager();

            return streamManager.GetAdapter(stream);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Native Callback Methods
        /// <summary>
        /// This method is called when determining if a table needs to be
        /// included in the tracked changes for the associated database.
        /// </summary>
        /// <param name="context">
        /// Optional extra context information.  Currently, this will always
        /// have a value of <see cref="IntPtr.Zero" />.
        /// </param>
        /// <param name="pTblName">
        /// The native pointer to the name of the table.
        /// </param>
        /// <returns>
        /// Non-zero if changes to the specified table should be considered;
        /// otherwise, zero.
        /// </returns>
        private int Filter(
            IntPtr context, /* NOT USED */
            IntPtr pTblName
            )
        {
            try
            {
                return tableFilterCallback(tableFilterClientData,
                    SQLiteString.StringFromUtf8IntPtr(pTblName)) ? 1 : 0;
            }
            catch (Exception e)
            {
                try
                {
                    if (HelperMethods.LogCallbackExceptions(GetFlags()))
                    {
                        SQLiteLog.LogMessage( /* throw */
                            SQLiteBase.COR_E_EXCEPTION,
                            HelperMethods.StringFormat(
                            CultureInfo.CurrentCulture,
                            UnsafeNativeMethods.ExceptionMessageFormat,
                            "xSessionFilter", e));
                    }
                }
                catch
                {
                    // do nothing.
                }
            }

            return 0;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region ISQLiteSession Members
        /// <summary>
        /// Determines if this session is currently tracking changes to its
        /// associated database.
        /// </summary>
        /// <returns>
        /// Non-zero if changes to the associated database are being trakced;
        /// otherwise, zero.
        /// </returns>
        public bool IsEnabled()
        {
            CheckDisposed();
            CheckHandle();

            return UnsafeNativeMethods.sqlite3session_enable(session, -1) != 0;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Enables tracking of changes to the associated database.
        /// </summary>
        public void SetToEnabled()
        {
            CheckDisposed();
            CheckHandle();

            UnsafeNativeMethods.sqlite3session_enable(session, 1);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disables tracking of changes to the associated database.
        /// </summary>
        public void SetToDisabled()
        {
            CheckDisposed();
            CheckHandle();

            UnsafeNativeMethods.sqlite3session_enable(session, 0);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Determines if this session is currently set to mark changes as
        /// indirect (i.e. as though they were made via a trigger or foreign
        /// key action).
        /// </summary>
        /// <returns>
        /// Non-zero if changes to the associated database are being marked as
        /// indirect; otherwise, zero.
        /// </returns>
        public bool IsIndirect()
        {
            CheckDisposed();
            CheckHandle();

            return UnsafeNativeMethods.sqlite3session_indirect(session, -1) != 0;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Sets the indirect flag for this session.  Subsequent changes will
        /// be marked as indirect until this flag is changed again.
        /// </summary>
        public void SetToIndirect()
        {
            CheckDisposed();
            CheckHandle();

            UnsafeNativeMethods.sqlite3session_indirect(session, 1);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Clears the indirect flag for this session.  Subsequent changes will
        /// be marked as direct until this flag is changed again.
        /// </summary>
        public void SetToDirect()
        {
            CheckDisposed();
            CheckHandle();

            UnsafeNativeMethods.sqlite3session_indirect(session, 0);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Determines if there are any tracked changes currently within the
        /// data for this session.
        /// </summary>
        /// <returns>
        /// Non-zero if there are no changes within the data for this session;
        /// otherwise, zero.
        /// </returns>
        public bool IsEmpty()
        {
            CheckDisposed();
            CheckHandle();

            return UnsafeNativeMethods.sqlite3session_isempty(session) != 0;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Upon success, causes changes to the specified table(s) to start
        /// being tracked.  Any tables impacted by calls to this method will
        /// not cause the <see cref="SessionTableFilterCallback" /> callback
        /// to be invoked.
        /// </summary>
        /// <param name="name">
        /// The name of the table to be tracked -OR- null to track all
        /// applicable tables within this database.
        /// </param>
        public void AttachTable(
            string name /* in: NULL OK */
            )
        {
            CheckDisposed();
            CheckHandle();

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3session_attach(
                session, SQLiteString.GetUtf8BytesFromString(name));

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3session_attach");
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// This method is used to set the table filter for this instance.
        /// </summary>
        /// <param name="callback">
        /// The table filter callback -OR- null to clear any existing table
        /// filter callback.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        public void SetTableFilter(
            SessionTableFilterCallback callback, /* in: NULL OK */
            object clientData                    /* in: NULL OK */
            )
        {
            CheckDisposed();
            CheckHandle();

            UnsafeNativeMethods.sqlite3session_table_filter(
                session, ApplyTableFilter(callback, clientData), IntPtr.Zero);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to create and return, via <paramref name="rawData" />, the
        /// combined set of changes represented by this session instance.
        /// </summary>
        /// <param name="rawData">
        /// Upon success, this will contain the raw byte data for all the
        /// changes in this session instance.
        /// </param>
        public void CreateChangeSet(
            ref byte[] rawData
            )
        {
            CheckDisposed();
            CheckHandle();

            IntPtr pData = IntPtr.Zero;

            try
            {
                int nData = 0;

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3session_changeset(
                    session, ref nData, ref pData);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3session_changeset");

                rawData = SQLiteBytes.FromIntPtr(pData, nData);
            }
            finally
            {
                if (pData != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pData);
                    pData = IntPtr.Zero;
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to create and write, via <paramref name="stream" />, the
        /// combined set of changes represented by this session instance.
        /// </summary>
        /// <param name="stream">
        /// Upon success, the raw byte data for all the changes in this session
        /// instance will be written to this <see cref="Stream" />.
        /// </param>
        public void CreateChangeSet(
            Stream stream
            )
        {
            CheckDisposed();
            CheckHandle();

            if (stream == null)
                throw new ArgumentNullException("stream");

            SQLiteStreamAdapter streamAdapter = GetStreamAdapter(stream);

            if (streamAdapter == null)
            {
                throw new SQLiteException(
                    "could not get or create adapter for output stream");
            }

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3session_changeset_strm(
                session, streamAdapter.GetOutputDelegate(), IntPtr.Zero);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3session_changeset_strm");
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to create and return, via <paramref name="rawData" />, the
        /// combined set of changes represented by this session instance as a
        /// patch set.
        /// </summary>
        /// <param name="rawData">
        /// Upon success, this will contain the raw byte data for all the
        /// changes in this session instance.
        /// </param>
        public void CreatePatchSet(
            ref byte[] rawData
            )
        {
            CheckDisposed();
            CheckHandle();

            IntPtr pData = IntPtr.Zero;

            try
            {
                int nData = 0;

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3session_patchset(
                    session, ref nData, ref pData);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3session_patchset");

                rawData = SQLiteBytes.FromIntPtr(pData, nData);
            }
            finally
            {
                if (pData != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pData);
                    pData = IntPtr.Zero;
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to create and write, via <paramref name="stream" />, the
        /// combined set of changes represented by this session instance as a
        /// patch set.
        /// </summary>
        /// <param name="stream">
        /// Upon success, the raw byte data for all the changes in this session
        /// instance will be written to this <see cref="Stream" />.
        /// </param>
        public void CreatePatchSet(
            Stream stream
            )
        {
            CheckDisposed();
            CheckHandle();

            if (stream == null)
                throw new ArgumentNullException("stream");

            SQLiteStreamAdapter streamAdapter = GetStreamAdapter(stream);

            if (streamAdapter == null)
            {
                throw new SQLiteException(
                    "could not get or create adapter for output stream");
            }

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3session_patchset_strm(
                session, streamAdapter.GetOutputDelegate(), IntPtr.Zero);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3session_patchset_strm");
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// This method loads the differences between two tables [with the same
        /// name, set of columns, and primary key definition] into this session
        /// instance.
        /// </summary>
        /// <param name="fromDatabaseName">
        /// The name of the database containing the table with the original
        /// data (i.e. it will need updating in order to be identical to the
        /// one within the database associated with this session instance).
        /// </param>
        /// <param name="tableName">
        /// The name of the table.
        /// </param>
        public void LoadDifferencesFromTable(
            string fromDatabaseName,
            string tableName
            )
        {
            CheckDisposed();
            CheckHandle();

            if (fromDatabaseName == null)
                throw new ArgumentNullException("fromDatabaseName");

            if (tableName == null)
                throw new ArgumentNullException("tableName");

            IntPtr pError = IntPtr.Zero;

            try
            {
                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3session_diff(
                    session, SQLiteString.GetUtf8BytesFromString(fromDatabaseName),
                    SQLiteString.GetUtf8BytesFromString(tableName), ref pError);

                if (rc != SQLiteErrorCode.Ok)
                {
                    string error = null;

                    if (pError != IntPtr.Zero)
                    {
                        error = SQLiteString.StringFromUtf8IntPtr(pError);

                        if (!String.IsNullOrEmpty(error))
                        {
                            error = HelperMethods.StringFormat(
                                CultureInfo.CurrentCulture, ": {0}", error);
                        }
                    }

                    throw new SQLiteException(rc, HelperMethods.StringFormat(
                        CultureInfo.CurrentCulture, "{0}{1}",
                        "sqlite3session_diff", error));
                }
            }
            finally
            {
                if (pError != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pError);
                    pError = IntPtr.Zero;
                }
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
                throw new ObjectDisposedException(typeof(SQLiteSession).Name);
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////

                        if (xFilter != null)
                            xFilter = null;

                        if (streamManager != null)
                        {
                            streamManager.Dispose();
                            streamManager = null;
                        }
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////

                    if (session != IntPtr.Zero)
                    {
                        UnsafeNativeMethods.sqlite3session_delete(session);
                        session = IntPtr.Zero;
                    }

                    Unlock();
                }
            }
            finally
            {
                base.Dispose(disposing);

                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteChangeSetBase Class
    /// <summary>
    /// This class represents the abstract concept of a set of changes.  It
    /// acts as the base class for the <see cref="SQLiteMemoryChangeSet" />
    /// and <see cref="SQLiteStreamChangeSet" /> classes.  It derives from
    /// the <see cref="SQLiteConnectionLock" /> class, which is used to hold
    /// the underlying native connection handle open until the instances of
    /// this class are disposed or finalized.  It also provides the ability
    /// to construct wrapped native delegates of the
    /// <see cref="UnsafeNativeMethods.xSessionFilter" /> and
    /// <see cref="UnsafeNativeMethods.xSessionConflict" /> types.
    /// </summary>
    internal class SQLiteChangeSetBase : SQLiteConnectionLock
    {
        #region Private Constructors
        /// <summary>
        /// Constructs an instance of this class using the specified wrapped
        /// native connection handle.
        /// </summary>
        /// <param name="handle">
        /// The wrapped native connection handle to be associated with this
        /// change set.
        /// </param>
        /// <param name="flags">
        /// The flags associated with the connection represented by the
        /// <paramref name="handle" /> value.
        /// </param>
        internal SQLiteChangeSetBase(
            SQLiteConnectionHandle handle,
            SQLiteConnectionFlags flags
            )
            : base(handle, flags, true)
        {
            // do nothing.
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        /// <summary>
        /// Creates and returns a concrete implementation of the
        /// <see cref="ISQLiteChangeSetMetadataItem" /> interface.
        /// </summary>
        /// <param name="iterator">
        /// The native iterator handle to use.
        /// </param>
        /// <returns>
        /// An instance of the <see cref="ISQLiteChangeSetMetadataItem"/>
        /// interface, which can be used to fetch metadata associated with
        /// the current item in this set of changes.
        /// </returns>
        private ISQLiteChangeSetMetadataItem CreateMetadataItem(
            IntPtr iterator
            )
        {
            return new SQLiteChangeSetMetadataItem(
                SQLiteChangeSetIterator.Attach(iterator));
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Protected Methods
        /// <summary>
        /// Attempts to create a
        /// <see cref="UnsafeNativeMethods.xSessionFilter" /> native delegate
        /// that invokes the specified
        /// <see cref="SessionTableFilterCallback" /> delegate.
        /// </summary>
        /// <param name="tableFilterCallback">
        /// The <see cref="SessionTableFilterCallback" /> to invoke when the
        /// <see cref="UnsafeNativeMethods.xSessionFilter" /> native delegate
        /// is called.  If this value is null then null is returned.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        /// <returns>
        /// The created <see cref="UnsafeNativeMethods.xSessionFilter" />
        /// native delegate -OR- null if it cannot be created.
        /// </returns>
        protected UnsafeNativeMethods.xSessionFilter GetDelegate(
            SessionTableFilterCallback tableFilterCallback,
            object clientData
            )
        {
            if (tableFilterCallback == null)
                return null;

            UnsafeNativeMethods.xSessionFilter xFilter;

            xFilter = new UnsafeNativeMethods.xSessionFilter(
                delegate(IntPtr context, IntPtr pTblName)
            {
                try
                {
                    string name = SQLiteString.StringFromUtf8IntPtr(
                        pTblName);

                    return tableFilterCallback(clientData, name) ? 1 : 0;
                }
                catch (Exception e)
                {
                    try
                    {
                        if (HelperMethods.LogCallbackExceptions(GetFlags()))
                        {
                            SQLiteLog.LogMessage( /* throw */
                                SQLiteBase.COR_E_EXCEPTION,
                                HelperMethods.StringFormat(
                                CultureInfo.CurrentCulture,
                                UnsafeNativeMethods.ExceptionMessageFormat,
                                "xSessionFilter", e));
                        }
                    }
                    catch
                    {
                        // do nothing.
                    }
                }

                return 0;
            });

            return xFilter;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to create a
        /// <see cref="UnsafeNativeMethods.xSessionConflict" /> native delegate
        /// that invokes the specified
        /// <see cref="SessionConflictCallback" /> delegate.
        /// </summary>
        /// <param name="conflictCallback">
        /// The <see cref="SessionConflictCallback" /> to invoke when the
        /// <see cref="UnsafeNativeMethods.xSessionConflict" /> native delegate
        /// is called.  If this value is null then null is returned.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        /// <returns>
        /// The created <see cref="UnsafeNativeMethods.xSessionConflict" />
        /// native delegate -OR- null if it cannot be created.
        /// </returns>
        protected UnsafeNativeMethods.xSessionConflict GetDelegate(
            SessionConflictCallback conflictCallback,
            object clientData
            )
        {
            if (conflictCallback == null)
                return null;

            UnsafeNativeMethods.xSessionConflict xConflict;

            xConflict = new UnsafeNativeMethods.xSessionConflict(
                delegate(IntPtr context,
                         SQLiteChangeSetConflictType type,
                         IntPtr iterator)
            {
                try
                {
                    ISQLiteChangeSetMetadataItem item = CreateMetadataItem(
                        iterator);

                    if (item == null)
                    {
                        throw new SQLiteException(
                            "could not create metadata item");
                    }

                    return conflictCallback(clientData, type, item);
                }
                catch (Exception e)
                {
                    try
                    {
                        if (HelperMethods.LogCallbackExceptions(GetFlags()))
                        {
                            SQLiteLog.LogMessage( /* throw */
                                SQLiteBase.COR_E_EXCEPTION,
                                HelperMethods.StringFormat(
                                CultureInfo.CurrentCulture,
                                UnsafeNativeMethods.ExceptionMessageFormat,
                                "xSessionConflict", e));
                        }
                    }
                    catch
                    {
                        // do nothing.
                    }
                }

                return SQLiteChangeSetConflictResult.Abort;
            });

            return xConflict;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteChangeSetBase).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////

                    Unlock();
                }
            }
            finally
            {
                base.Dispose(disposing);

                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteMemoryChangeSet Class
    /// <summary>
    /// This class represents a set of changes contained entirely in memory.
    /// </summary>
    internal sealed class SQLiteMemoryChangeSet :
        SQLiteChangeSetBase, ISQLiteChangeSet
    {
        #region Private Data
        /// <summary>
        /// The raw byte data for this set of changes.  Since this data must
        /// be marshalled to a native memory buffer before being used, there
        /// must be enough memory available to store at least two times the
        /// amount of data contained within it.
        /// </summary>
        private byte[] rawData;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Constructors
        /// <summary>
        /// Constructs an instance of this class using the specified raw byte
        /// data and wrapped native connection handle.
        /// </summary>
        /// <param name="rawData">
        /// The raw byte data for the specified change set (or patch set).
        /// </param>
        /// <param name="handle">
        /// The wrapped native connection handle to be associated with this
        /// set of changes.
        /// </param>
        /// <param name="flags">
        /// The flags associated with the connection represented by the
        /// <paramref name="handle" /> value.
        /// </param>
        internal SQLiteMemoryChangeSet(
            byte[] rawData,
            SQLiteConnectionHandle handle,
            SQLiteConnectionFlags flags
            )
            : base(handle, flags)
        {
            this.rawData = rawData;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region ISQLiteChangeSet Members
        /// <summary>
        /// This method "inverts" the set of changes within this instance.
        /// Applying an inverted set of changes to a database reverses the
        /// effects of applying the uninverted changes.  Specifically:
        /// <![CDATA[<ul>]]><![CDATA[<li>]]>
        /// Each DELETE change is changed to an INSERT, and
        /// <![CDATA[</li>]]><![CDATA[<li>]]>
        /// Each INSERT change is changed to a DELETE, and
        /// <![CDATA[</li>]]><![CDATA[<li>]]>
        /// For each UPDATE change, the old.* and new.* values are exchanged.
        /// <![CDATA[</li>]]><![CDATA[</ul>]]>
        /// This method does not change the order in which changes appear
        /// within the set of changes. It merely reverses the sense of each
        /// individual change.
        /// </summary>
        /// <returns>
        /// The new <see cref="ISQLiteChangeSet" /> instance that represents
        /// the resulting set of changes.
        /// </returns>
        public ISQLiteChangeSet Invert()
        {
            CheckDisposed();

            SQLiteSessionHelpers.CheckRawData(rawData);

            IntPtr pInData = IntPtr.Zero;
            IntPtr pOutData = IntPtr.Zero;

            try
            {
                int nInData = 0;

                pInData = SQLiteBytes.ToIntPtr(rawData, ref nInData);

                int nOutData = 0;

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_invert(
                    nInData, pInData, ref nOutData, ref pOutData);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3changeset_invert");

                byte[] newData = SQLiteBytes.FromIntPtr(pOutData, nOutData);

                return new SQLiteMemoryChangeSet(
                    newData, GetHandle(), GetFlags());
            }
            finally
            {
                if (pOutData != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pOutData);
                    pOutData = IntPtr.Zero;
                }

                if (pInData != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pInData);
                    pInData = IntPtr.Zero;
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// This method combines the specified set of changes with the ones
        /// contained in this instance.
        /// </summary>
        /// <param name="changeSet">
        /// The changes to be combined with those in this instance.
        /// </param>
        /// <returns>
        /// The new <see cref="ISQLiteChangeSet" /> instance that represents
        /// the resulting set of changes.
        /// </returns>
        public ISQLiteChangeSet CombineWith(
            ISQLiteChangeSet changeSet
            )
        {
            CheckDisposed();

            SQLiteSessionHelpers.CheckRawData(rawData);

            SQLiteMemoryChangeSet memoryChangeSet =
                changeSet as SQLiteMemoryChangeSet;

            if (memoryChangeSet == null)
            {
                throw new ArgumentException(
                    "not a memory based change set", "changeSet");
            }

            SQLiteSessionHelpers.CheckRawData(memoryChangeSet.rawData);

            IntPtr pInData1 = IntPtr.Zero;
            IntPtr pInData2 = IntPtr.Zero;
            IntPtr pOutData = IntPtr.Zero;

            try
            {
                int nInData1 = 0;

                pInData1 = SQLiteBytes.ToIntPtr(rawData, ref nInData1);

                int nInData2 = 0;

                pInData2 = SQLiteBytes.ToIntPtr(
                    memoryChangeSet.rawData, ref nInData2);

                int nOutData = 0;

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_concat(
                    nInData1, pInData1, nInData2, pInData2, ref nOutData,
                    ref pOutData);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3changeset_concat");

                byte[] newData = SQLiteBytes.FromIntPtr(pOutData, nOutData);

                return new SQLiteMemoryChangeSet(
                    newData, GetHandle(), GetFlags());
            }
            finally
            {
                if (pOutData != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pOutData);
                    pOutData = IntPtr.Zero;
                }

                if (pInData2 != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pInData2);
                    pInData2 = IntPtr.Zero;
                }

                if (pInData1 != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pInData1);
                    pInData1 = IntPtr.Zero;
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to apply the set of changes in this instance to the
        /// associated database.
        /// </summary>
        /// <param name="conflictCallback">
        /// The <see cref="SessionConflictCallback" /> delegate that will need
        /// to handle any conflicting changes that may arise.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        public void Apply(
            SessionConflictCallback conflictCallback,
            object clientData
            )
        {
            CheckDisposed();

            Apply(conflictCallback, null, clientData);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to apply the set of changes in this instance to the
        /// associated database.
        /// </summary>
        /// <param name="conflictCallback">
        /// The <see cref="SessionConflictCallback" /> delegate that will need
        /// to handle any conflicting changes that may arise.
        /// </param>
        /// <param name="tableFilterCallback">
        /// The optional <see cref="SessionTableFilterCallback" /> delegate
        /// that can be used to filter the list of tables impacted by the set
        /// of changes.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        public void Apply(
            SessionConflictCallback conflictCallback,
            SessionTableFilterCallback tableFilterCallback,
            object clientData
            )
        {
            CheckDisposed();

            SQLiteSessionHelpers.CheckRawData(rawData);

            if (conflictCallback == null)
                throw new ArgumentNullException("conflictCallback");

            UnsafeNativeMethods.xSessionFilter xFilter = GetDelegate(
                tableFilterCallback, clientData);

            UnsafeNativeMethods.xSessionConflict xConflict = GetDelegate(
                conflictCallback, clientData);

            IntPtr pData = IntPtr.Zero;

            try
            {
                int nData = 0;

                pData = SQLiteBytes.ToIntPtr(rawData, ref nData);

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_apply(
                    GetIntPtr(), nData, pData, xFilter, xConflict, IntPtr.Zero);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3changeset_apply");
            }
            finally
            {
                if (pData != IntPtr.Zero)
                {
                    SQLiteMemory.Free(pData);
                    pData = IntPtr.Zero;
                }
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IEnumerable<ISQLiteChangeSetMetadataItem> Members
        /// <summary>
        /// Creates an <see cref="IEnumerator" /> capable of iterating over the
        /// items within this set of changes.
        /// </summary>
        /// <returns>
        /// The new <see cref="IEnumerator{ISQLiteChangeSetMetadataItem}" />
        /// instance.
        /// </returns>
        public IEnumerator<ISQLiteChangeSetMetadataItem> GetEnumerator()
        {
            return new SQLiteMemoryChangeSetEnumerator(rawData);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IEnumerable Members
        /// <summary>
        /// Creates an <see cref="IEnumerator" /> capable of iterating over the
        /// items within this set of changes.
        /// </summary>
        /// <returns>
        /// The new <see cref="IEnumerator" /> instance.
        /// </returns>
        IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteMemoryChangeSet).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////

                        if (rawData != null)
                            rawData = null;
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////
                }
            }
            finally
            {
                base.Dispose(disposing);

                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteStreamChangeSet Class
    /// <summary>
    /// This class represents a set of changes that are backed by a
    /// <see cref="Stream" /> instance.
    /// </summary>
    internal sealed class SQLiteStreamChangeSet :
        SQLiteChangeSetBase, ISQLiteChangeSet
    {
        #region Private Data
        /// <summary>
        /// The <see cref="SQLiteStreamAdapter" /> instance that is managing
        /// the underlying input <see cref="Stream" /> used as the backing
        /// store for the set of changes associated with this instance.
        /// </summary>
        private SQLiteStreamAdapter inputStreamAdapter;

        /// <summary>
        /// The <see cref="SQLiteStreamAdapter" /> instance that is managing
        /// the underlying output <see cref="Stream" /> used as the backing
        /// store for the set of changes generated by the <see cref="Invert" />
        /// or <see cref="CombineWith" /> methods.
        /// </summary>
        private SQLiteStreamAdapter outputStreamAdapter;

        /// <summary>
        /// The <see cref="Stream" /> instance used as the backing store for
        /// the set of changes associated with this instance.
        /// </summary>
        private Stream inputStream;

        /// <summary>
        /// The <see cref="Stream" /> instance used as the backing store for
        /// the set of changes generated by the <see cref="Invert" /> or
        /// <see cref="CombineWith" /> methods.
        /// </summary>
        private Stream outputStream;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Constructors
        /// <summary>
        /// Constructs an instance of this class using the specified streams
        /// and wrapped native connection handle.
        /// </summary>
        /// <param name="inputStream">
        /// The <see cref="Stream" /> where the raw byte data for the set of
        /// changes may be read.
        /// </param>
        /// <param name="outputStream">
        /// The <see cref="Stream" /> where the raw byte data for resulting
        /// sets of changes may be written.
        /// </param>
        /// <param name="handle">
        /// The wrapped native connection handle to be associated with this
        /// set of changes.
        /// </param>
        /// <param name="flags">
        /// The flags associated with the connection represented by the
        /// <paramref name="handle" /> value.
        /// </param>
        internal SQLiteStreamChangeSet(
            Stream inputStream,
            Stream outputStream,
            SQLiteConnectionHandle handle,
            SQLiteConnectionFlags flags
            )
            : base(handle, flags)
        {
            this.inputStream = inputStream;
            this.outputStream = outputStream;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        /// <summary>
        /// Throws an exception if the input stream or its associated stream
        /// adapter are invalid.
        /// </summary>
        private void CheckInputStream()
        {
            if (inputStream == null)
            {
                throw new InvalidOperationException(
                    "input stream unavailable");
            }

            if (inputStreamAdapter == null)
            {
                inputStreamAdapter = new SQLiteStreamAdapter(
                    inputStream, GetFlags());
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Throws an exception if the output stream or its associated stream
        /// adapter are invalid.
        /// </summary>
        private void CheckOutputStream()
        {
            if (outputStream == null)
            {
                throw new InvalidOperationException(
                    "output stream unavailable");
            }

            if (outputStreamAdapter == null)
            {
                outputStreamAdapter = new SQLiteStreamAdapter(
                    outputStream, GetFlags());
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region ISQLiteChangeSet Members
        /// <summary>
        /// This method "inverts" the set of changes within this instance.
        /// Applying an inverted set of changes to a database reverses the
        /// effects of applying the uninverted changes.  Specifically:
        /// <![CDATA[<ul>]]><![CDATA[<li>]]>
        /// Each DELETE change is changed to an INSERT, and
        /// <![CDATA[</li>]]><![CDATA[<li>]]>
        /// Each INSERT change is changed to a DELETE, and
        /// <![CDATA[</li>]]><![CDATA[<li>]]>
        /// For each UPDATE change, the old.* and new.* values are exchanged.
        /// <![CDATA[</li>]]><![CDATA[</ul>]]>
        /// This method does not change the order in which changes appear
        /// within the set of changes. It merely reverses the sense of each
        /// individual change.
        /// </summary>
        /// <returns>
        /// Since the resulting set of changes is written to the output stream,
        /// this method always returns null.
        /// </returns>
        public ISQLiteChangeSet Invert()
        {
            CheckDisposed();
            CheckInputStream();
            CheckOutputStream();

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_invert_strm(
                inputStreamAdapter.GetInputDelegate(), IntPtr.Zero,
                outputStreamAdapter.GetOutputDelegate(), IntPtr.Zero);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3changeset_invert_strm");

            return null;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// This method combines the specified set of changes with the ones
        /// contained in this instance.
        /// </summary>
        /// <param name="changeSet">
        /// The changes to be combined with those in this instance.
        /// </param>
        /// <returns>
        /// Since the resulting set of changes is written to the output stream,
        /// this method always returns null.
        /// </returns>
        public ISQLiteChangeSet CombineWith(
            ISQLiteChangeSet changeSet
            )
        {
            CheckDisposed();
            CheckInputStream();
            CheckOutputStream();

            SQLiteStreamChangeSet streamChangeSet =
                changeSet as SQLiteStreamChangeSet;

            if (streamChangeSet == null)
            {
                throw new ArgumentException(
                    "not a stream based change set", "changeSet");
            }

            streamChangeSet.CheckInputStream();

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_concat_strm(
                inputStreamAdapter.GetInputDelegate(), IntPtr.Zero,
                streamChangeSet.inputStreamAdapter.GetInputDelegate(),
                IntPtr.Zero, outputStreamAdapter.GetOutputDelegate(),
                IntPtr.Zero);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3changeset_concat_strm");

            return null;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to apply the set of changes in this instance to the
        /// associated database.
        /// </summary>
        /// <param name="conflictCallback">
        /// The <see cref="SessionConflictCallback" /> delegate that will need
        /// to handle any conflicting changes that may arise.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        public void Apply(
            SessionConflictCallback conflictCallback,
            object clientData
            )
        {
            CheckDisposed();

            Apply(conflictCallback, null, clientData);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to apply the set of changes in this instance to the
        /// associated database.
        /// </summary>
        /// <param name="conflictCallback">
        /// The <see cref="SessionConflictCallback" /> delegate that will need
        /// to handle any conflicting changes that may arise.
        /// </param>
        /// <param name="tableFilterCallback">
        /// The optional <see cref="SessionTableFilterCallback" /> delegate
        /// that can be used to filter the list of tables impacted by the set
        /// of changes.
        /// </param>
        /// <param name="clientData">
        /// The optional application-defined context data.  This value may be
        /// null.
        /// </param>
        public void Apply(
            SessionConflictCallback conflictCallback,
            SessionTableFilterCallback tableFilterCallback,
            object clientData
            )
        {
            CheckDisposed();
            CheckInputStream();

            if (conflictCallback == null)
                throw new ArgumentNullException("conflictCallback");

            UnsafeNativeMethods.xSessionFilter xFilter = GetDelegate(
                tableFilterCallback, clientData);

            UnsafeNativeMethods.xSessionConflict xConflict = GetDelegate(
                conflictCallback, clientData);

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_apply_strm(
                GetIntPtr(), inputStreamAdapter.GetInputDelegate(), IntPtr.Zero,
                xFilter, xConflict, IntPtr.Zero);

            if (rc != SQLiteErrorCode.Ok)
                throw new SQLiteException(rc, "sqlite3changeset_apply_strm");
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IEnumerable<ISQLiteChangeSetMetadataItem> Members
        /// <summary>
        /// Creates an <see cref="IEnumerator" /> capable of iterating over the
        /// items within this set of changes.
        /// </summary>
        /// <returns>
        /// The new <see cref="IEnumerator{ISQLiteChangeSetMetadataItem}" />
        /// instance.
        /// </returns>
        public IEnumerator<ISQLiteChangeSetMetadataItem> GetEnumerator()
        {
            return new SQLiteStreamChangeSetEnumerator(
                inputStream, GetFlags());
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IEnumerable Members
        /// <summary>
        /// Creates an <see cref="IEnumerator" /> capable of iterating over the
        /// items within this set of changes.
        /// </summary>
        /// <returns>
        /// The new <see cref="IEnumerator" /> instance.
        /// </returns>
        IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteStreamChangeSet).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////

                        if (outputStreamAdapter != null)
                        {
                            outputStreamAdapter.Dispose();
                            outputStreamAdapter = null;
                        }

                        if (inputStreamAdapter != null)
                        {
                            inputStreamAdapter.Dispose();
                            inputStreamAdapter = null;
                        }

                        if (outputStream != null)
                            outputStream = null; /* NOT OWNED */

                        if (inputStream != null)
                            inputStream = null; /* NOT OWNED */
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////
                }
            }
            finally
            {
                base.Dispose(disposing);

                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteChangeSetEnumerator Class
    /// <summary>
    /// This class represents an <see cref="IEnumerator" /> that is capable of
    /// enumerating over a set of changes.  It serves as the base class for the
    /// <see cref="SQLiteMemoryChangeSetEnumerator" /> and
    /// <see cref="SQLiteStreamChangeSetEnumerator" /> classes.  It manages and
    /// owns an instance of the <see cref="SQLiteChangeSetIterator" /> class.
    /// </summary>
    internal abstract class SQLiteChangeSetEnumerator :
        IEnumerator<ISQLiteChangeSetMetadataItem>
    {
        #region Private Data
        /// <summary>
        /// This managed change set iterator is managed and owned by this
        /// class.  It will be disposed when this class is disposed.
        /// </summary>
        private SQLiteChangeSetIterator iterator;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Constructors
        /// <summary>
        /// Constructs an instance of this class using the specified managed
        /// change set iterator.
        /// </summary>
        /// <param name="iterator">
        /// The managed iterator instance to use.
        /// </param>
        public SQLiteChangeSetEnumerator(
            SQLiteChangeSetIterator iterator
            )
        {
            SetIterator(iterator);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        /// <summary>
        /// Throws an exception if the managed iterator instance is invalid.
        /// </summary>
        private void CheckIterator()
        {
            if (iterator == null)
                throw new InvalidOperationException("iterator unavailable");

            iterator.CheckHandle();
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Sets the managed iterator instance to a new value.
        /// </summary>
        /// <param name="iterator">
        /// The new managed iterator instance to use.
        /// </param>
        private void SetIterator(
            SQLiteChangeSetIterator iterator
            )
        {
            this.iterator = iterator;
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes of the managed iterator instance and sets its value to
        /// null.
        /// </summary>
        private void CloseIterator()
        {
            if (iterator != null)
            {
                iterator.Dispose();
                iterator = null;
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Protected Methods
        /// <summary>
        /// Disposes of the existing managed iterator instance and then sets it
        /// to a new value.
        /// </summary>
        /// <param name="iterator">
        /// The new managed iterator instance to use.
        /// </param>
        protected void ResetIterator(
            SQLiteChangeSetIterator iterator
            )
        {
            CloseIterator();
            SetIterator(iterator);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IEnumerator<ISQLiteChangeSetMetadataItem> Members
        /// <summary>
        /// Returns the current change within the set of changes, represented
        /// by a <see cref="ISQLiteChangeSetMetadataItem" /> instance.
        /// </summary>
        public ISQLiteChangeSetMetadataItem Current
        {
            get
            {
                CheckDisposed();

                return new SQLiteChangeSetMetadataItem(iterator);
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IEnumerator Members
        /// <summary>
        /// Returns the current change within the set of changes, represented
        /// by a <see cref="ISQLiteChangeSetMetadataItem" /> instance.
        /// </summary>
        object Collections.IEnumerator.Current
        {
            get
            {
                CheckDisposed();

                return Current;
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Attempts to advance to the next item in the set of changes.
        /// </summary>
        /// <returns>
        /// Non-zero if more items are available; otherwise, zero.
        /// </returns>
        public bool MoveNext()
        {
            CheckDisposed();
            CheckIterator();

            return iterator.Next();
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Throws <see cref="NotImplementedException" /> because not all the
        /// derived classes are able to support reset functionality.
        /// </summary>
        public virtual void Reset()
        {
            CheckDisposed();

            throw new NotImplementedException();
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable Members
        /// <summary>
        /// Disposes of this object instance.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteChangeSetEnumerator).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////

                        CloseIterator();
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////
                }
            }
            finally
            {
                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Destructor
        /// <summary>
        /// Finalizes this object instance.
        /// </summary>
        ~SQLiteChangeSetEnumerator()
        {
            Dispose(false);
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteMemoryChangeSetEnumerator Class
    /// <summary>
    /// This class represents an <see cref="IEnumerator" /> that is capable of
    /// enumerating over a set of changes contained entirely in memory.
    /// </summary>
    internal sealed class SQLiteMemoryChangeSetEnumerator :
        SQLiteChangeSetEnumerator
    {
        #region Private Data
        /// <summary>
        /// The raw byte data for this set of changes.  Since this data must
        /// be marshalled to a native memory buffer before being used, there
        /// must be enough memory available to store at least two times the
        /// amount of data contained within it.
        /// </summary>
        private byte[] rawData;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Constructors
        /// <summary>
        /// Constructs an instance of this class using the specified raw byte
        /// data.
        /// </summary>
        /// <param name="rawData">
        /// The raw byte data containing the set of changes for this
        /// enumerator.
        /// </param>
        public SQLiteMemoryChangeSetEnumerator(
            byte[] rawData
            )
            : base(SQLiteMemoryChangeSetIterator.Create(rawData))
        {
            this.rawData = rawData;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IEnumerator Overrides
        /// <summary>
        /// Resets the enumerator to its initial position.
        /// </summary>
        public override void Reset()
        {
            CheckDisposed();

            ResetIterator(SQLiteMemoryChangeSetIterator.Create(rawData));
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteMemoryChangeSetEnumerator).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////
                }
            }
            finally
            {
                base.Dispose(disposing);

                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteStreamChangeSetEnumerator Class
    /// <summary>
    /// This class represents an <see cref="IEnumerator" /> that is capable of
    /// enumerating over a set of changes backed by a <see cref="Stream" />
    /// instance.
    /// </summary>
    internal sealed class SQLiteStreamChangeSetEnumerator :
        SQLiteChangeSetEnumerator
    {
        #region Public Constructors
        /// <summary>
        /// Constructs an instance of this class using the specified stream.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="Stream" /> where the raw byte data for the set of
        /// changes may be read.
        /// </param>
        /// <param name="flags">
        /// The flags associated with the parent connection.
        /// </param>
        public SQLiteStreamChangeSetEnumerator(
            Stream stream,
            SQLiteConnectionFlags flags
            )
            : base(SQLiteStreamChangeSetIterator.Create(stream, flags))
        {
            // do nothing.
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteStreamChangeSetEnumerator).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                //if (!disposed)
                //{
                //    if (disposing)
                //    {
                //        ////////////////////////////////////
                //        // dispose managed resources here...
                //        ////////////////////////////////////
                //    }

                //    //////////////////////////////////////
                //    // release unmanaged resources here...
                //    //////////////////////////////////////
                //}
            }
            finally
            {
                base.Dispose(disposing);

                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion
    }
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region SQLiteChangeSetMetadataItem Class
    /// <summary>
    /// This interface implements properties and methods used to fetch metadata
    /// about one change within a set of changes for a database.
    /// </summary>
    internal sealed class SQLiteChangeSetMetadataItem :
        ISQLiteChangeSetMetadataItem
    {
        #region Private Data
        /// <summary>
        /// The <see cref="SQLiteChangeSetIterator" /> instance to use.  This
        /// will NOT be owned by this class and will not be disposed upon this
        /// class being disposed or finalized.
        /// </summary>
        private SQLiteChangeSetIterator iterator;
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Public Constructors
        /// <summary>
        /// Constructs an instance of this class using the specified iterator
        /// instance.
        /// </summary>
        /// <param name="iterator">
        /// The managed iterator instance to use.
        /// </param>
        public SQLiteChangeSetMetadataItem(
            SQLiteChangeSetIterator iterator
            )
        {
            this.iterator = iterator;
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        /// <summary>
        /// Throws an exception if the managed iterator instance is invalid.
        /// </summary>
        private void CheckIterator()
        {
            if (iterator == null)
                throw new InvalidOperationException("iterator unavailable");

            iterator.CheckHandle();
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Populates the underlying data for the <see cref="TableName" />,
        /// <see cref="NumberOfColumns" />, <see cref="OperationCode" />, and
        /// <see cref="Indirect" /> properties, using the appropriate native
        /// API.
        /// </summary>
        private void PopulateOperationMetadata()
        {
            if ((tableName == null) || (numberOfColumns == null) ||
                (operationCode == null) || (indirect == null))
            {
                CheckIterator();

                IntPtr pTblName = IntPtr.Zero;
                SQLiteAuthorizerActionCode op = SQLiteAuthorizerActionCode.None;
                int bIndirect = 0;
                int nColumns = 0;

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_op(
                    iterator.GetIntPtr(), ref pTblName, ref nColumns, ref op,
                    ref bIndirect);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3changeset_op");

                tableName = SQLiteString.StringFromUtf8IntPtr(pTblName);
                numberOfColumns = nColumns;
                operationCode = op;
                indirect = (bIndirect != 0);
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Populates the underlying data for the
        /// <see cref="PrimaryKeyColumns" /> property using the appropriate
        /// native API.
        /// </summary>
        private void PopulatePrimaryKeyColumns()
        {
            if (primaryKeyColumns == null)
            {
                CheckIterator();

                IntPtr pPrimaryKeys = IntPtr.Zero;
                int nColumns = 0;

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_pk(
                    iterator.GetIntPtr(), ref pPrimaryKeys, ref nColumns);

                if (rc != SQLiteErrorCode.Ok)
                    throw new SQLiteException(rc, "sqlite3changeset_pk");

                byte[] bytes = SQLiteBytes.FromIntPtr(pPrimaryKeys, nColumns);

                if (bytes != null)
                {
                    primaryKeyColumns = new bool[nColumns];

                    for (int index = 0; index < bytes.Length; index++)
                        primaryKeyColumns[index] = (bytes[index] != 0);
                }
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Populates the underlying data for the
        /// <see cref="NumberOfForeignKeyConflicts" /> property using the
        /// appropriate native API.
        /// </summary>
        private void PopulateNumberOfForeignKeyConflicts()
        {
            if (numberOfForeignKeyConflicts == null)
            {
                CheckIterator();

                int conflicts = 0;

                SQLiteErrorCode rc =
                    UnsafeNativeMethods.sqlite3changeset_fk_conflicts(
                        iterator.GetIntPtr(), ref conflicts);

                if (rc != SQLiteErrorCode.Ok)
                {
                    throw new SQLiteException(rc,
                        "sqlite3changeset_fk_conflicts");
                }

                numberOfForeignKeyConflicts = conflicts;
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region ISQLiteChangeSetMetadataItem Members
        /// <summary>
        /// Backing field for the <see cref="TableName" /> property. This value
        /// will be null if this field has not yet been populated via the
        /// underlying native API.
        /// </summary>
        private string tableName;

        /// <summary>
        /// The name of the table the change was made to.
        /// </summary>
        public string TableName
        {
            get
            {
                CheckDisposed();
                PopulateOperationMetadata();

                return tableName;
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Backing field for the <see cref="NumberOfColumns" /> property. This
        /// value will be null if this field has not yet been populated via the
        /// underlying native API.
        /// </summary>
        private int? numberOfColumns;

        /// <summary>
        /// The number of columns impacted by this change.  This value can be
        /// used to determine the highest valid column index that may be used
        /// with the <see cref="GetOldValue" />, <see cref="GetNewValue" />,
        /// and <see cref="GetConflictValue" /> methods of this interface.  It
        /// will be this value minus one.
        /// </summary>
        public int NumberOfColumns
        {
            get
            {
                CheckDisposed();
                PopulateOperationMetadata();

                return (int)numberOfColumns;
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Backing field for the <see cref="OperationCode" /> property.  This
        /// value will be null if this field has not yet been populated via the
        /// underlying native API.
        /// </summary>
        private SQLiteAuthorizerActionCode? operationCode;

        /// <summary>
        /// This will contain the value
        /// <see cref="SQLiteAuthorizerActionCode.Insert" />,
        /// <see cref="SQLiteAuthorizerActionCode.Update" />, or
        /// <see cref="SQLiteAuthorizerActionCode.Delete" />, corresponding to
        /// the overall type of change this item represents.
        /// </summary>
        public SQLiteAuthorizerActionCode OperationCode
        {
            get
            {
                CheckDisposed();
                PopulateOperationMetadata();

                return (SQLiteAuthorizerActionCode)operationCode;
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Backing field for the <see cref="Indirect" /> property.  This value
        /// will be null if this field has not yet been populated via the
        /// underlying native API.
        /// </summary>
        private bool? indirect;

        /// <summary>
        /// Non-zero if this change is considered to be indirect (i.e. as
        /// though they were made via a trigger or foreign key action).
        /// </summary>
        public bool Indirect
        {
            get
            {
                CheckDisposed();
                PopulateOperationMetadata();

                return (bool)indirect;
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Backing field for the <see cref="PrimaryKeyColumns" /> property.
        /// This value will be null if this field has not yet been populated
        /// via the underlying native API.
        /// </summary>
        private bool[] primaryKeyColumns;

        /// <summary>
        /// This array contains a <see cref="Boolean" /> for each column in
        /// the table associated with this change.  The element will be zero
        /// if the column is not part of the primary key; otherwise, it will
        /// be non-zero.
        /// </summary>
        public bool[] PrimaryKeyColumns
        {
            get
            {
                CheckDisposed();
                PopulatePrimaryKeyColumns();

                return primaryKeyColumns;
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Backing field for the <see cref="NumberOfForeignKeyConflicts" />
        /// property.  This value will be null if this field has not yet been
        /// populated via the underlying native API.
        /// </summary>
        private int? numberOfForeignKeyConflicts;

        /// <summary>
        /// This method may only be called from within a
        /// <see cref="SessionConflictCallback" /> delegate when the conflict
        /// type is <see cref="SQLiteChangeSetConflictType.ForeignKey" />.  It
        /// returns the total number of known foreign key violations in the
        /// destination database.
        /// </summary>
        public int NumberOfForeignKeyConflicts
        {
            get
            {
                CheckDisposed();
                PopulateNumberOfForeignKeyConflicts();

                return (int)numberOfForeignKeyConflicts;
            }
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Queries and returns the original value of a given column for this
        /// change.  This method may only be called when the
        /// <see cref="OperationCode" /> has a value of
        /// <see cref="SQLiteAuthorizerActionCode.Update" /> or
        /// <see cref="SQLiteAuthorizerActionCode.Delete" />.
        /// </summary>
        /// <param name="columnIndex">
        /// The index for the column.  This value must be between zero and one
        /// less than the total number of columns for this table.
        /// </param>
        /// <returns>
        /// The original value of a given column for this change.
        /// </returns>
        public SQLiteValue GetOldValue(
            int columnIndex
            )
        {
            CheckDisposed();
            CheckIterator();

            IntPtr pValue = IntPtr.Zero;

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_old(
                iterator.GetIntPtr(), columnIndex, ref pValue);

            return SQLiteValue.FromIntPtr(pValue);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Queries and returns the updated value of a given column for this
        /// change.  This method may only be called when the
        /// <see cref="OperationCode" /> has a value of
        /// <see cref="SQLiteAuthorizerActionCode.Insert" /> or
        /// <see cref="SQLiteAuthorizerActionCode.Update" />.
        /// </summary>
        /// <param name="columnIndex">
        /// The index for the column.  This value must be between zero and one
        /// less than the total number of columns for this table.
        /// </param>
        /// <returns>
        /// The updated value of a given column for this change.
        /// </returns>
        public SQLiteValue GetNewValue(
            int columnIndex
            )
        {
            CheckDisposed();
            CheckIterator();

            IntPtr pValue = IntPtr.Zero;

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_new(
                iterator.GetIntPtr(), columnIndex, ref pValue);

            return SQLiteValue.FromIntPtr(pValue);
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Queries and returns the conflicting value of a given column for
        /// this change.  This method may only be called from within a
        /// <see cref="SessionConflictCallback" /> delegate when the conflict
        /// type is <see cref="SQLiteChangeSetConflictType.Data" /> or
        /// <see cref="SQLiteChangeSetConflictType.Conflict" />.
        /// </summary>
        /// <param name="columnIndex">
        /// The index for the column.  This value must be between zero and one
        /// less than the total number of columns for this table.
        /// </param>
        /// <returns>
        /// The conflicting value of a given column for this change.
        /// </returns>
        public SQLiteValue GetConflictValue(
            int columnIndex
            )
        {
            CheckDisposed();
            CheckIterator();

            IntPtr pValue = IntPtr.Zero;

            SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3changeset_conflict(
                iterator.GetIntPtr(), columnIndex, ref pValue);

            return SQLiteValue.FromIntPtr(pValue);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable Members
        /// <summary>
        /// Disposes of this object instance.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region IDisposable "Pattern" Members
        /// <summary>
        /// Non-zero if this object instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Throws an exception if this object instance has been disposed.
        /// </summary>
        private void CheckDisposed() /* throw */
        {
#if THROW_ON_DISPOSED
            if (disposed)
            {
                throw new ObjectDisposedException(
                    typeof(SQLiteChangeSetMetadataItem).Name);
            }
#endif
        }

        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Disposes or finalizes this object instance.
        /// </summary>
        /// <param name="disposing">
        /// Non-zero if this object is being disposed; otherwise, this object
        /// is being finalized.
        /// </param>
        private /* protected virtual */ void Dispose(bool disposing)
        {
            try
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        ////////////////////////////////////
                        // dispose managed resources here...
                        ////////////////////////////////////

                        if (iterator != null)
                            iterator = null; /* NOT OWNED */
                    }

                    //////////////////////////////////////
                    // release unmanaged resources here...
                    //////////////////////////////////////
                }
            }
            finally
            {
                //
                // NOTE: Everything should be fully disposed at this point.
                //
                disposed = true;
            }
        }
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Destructor
        /// <summary>
        /// Finalizes this object instance.
        /// </summary>
        ~SQLiteChangeSetMetadataItem()
        {
            Dispose(false);
        }
        #endregion
    }
    #endregion
}

Changes to System.Data.SQLite/Targets/System.Data.SQLite.Files.targets.

114
115
116
117
118
119
120










121
  <ItemGroup Condition="'$(InteropVirtualTable)' != 'false'">
    <Compile Include="ISQLiteNativeModule.cs" />
    <Compile Include="SQLiteModule.cs" />
    <Compile Include="SQLiteModuleCommon.cs" />
    <Compile Include="SQLiteModuleEnumerable.cs" />
    <Compile Include="SQLiteModuleNoop.cs" />
  </ItemGroup>










</Project>







>
>
>
>
>
>
>
>
>
>

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
  <ItemGroup Condition="'$(InteropVirtualTable)' != 'false'">
    <Compile Include="ISQLiteNativeModule.cs" />
    <Compile Include="SQLiteModule.cs" />
    <Compile Include="SQLiteModuleCommon.cs" />
    <Compile Include="SQLiteModuleEnumerable.cs" />
    <Compile Include="SQLiteModuleNoop.cs" />
  </ItemGroup>

  <!--
  ******************************************************************************
  **                         Session Extension Files                          **
  ******************************************************************************
  -->

  <ItemGroup Condition="'$(InteropSessionExtension)' != 'false'">
    <Compile Include="SQLiteSession.cs" />
  </ItemGroup>
</Project>

Changes to System.Data.SQLite/Targets/System.Data.SQLite.Properties.targets.

333
334
335
336
337
338
339








340
341
342
343
344
345
346
            extension?  This will allow virtual tables to be implemented in
            managed code.
  -->
  <PropertyGroup Condition="'$(InteropVirtualTable)' != 'false'">
    <DefineConstants>$(DefineConstants);INTEROP_VIRTUAL_TABLE</DefineConstants>
  </PropertyGroup>









  <!--
      NOTE: Enable various Trace.WriteLine statements included in the code,
            based on several criteria (see the "SQLite.NET.Settings.targets"
            file for more information)?
  -->
  <PropertyGroup Condition="'$(TraceConnection)' != 'false'">
    <DefineConstants>$(DefineConstants);TRACE_CONNECTION</DefineConstants>







>
>
>
>
>
>
>
>







333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
            extension?  This will allow virtual tables to be implemented in
            managed code.
  -->
  <PropertyGroup Condition="'$(InteropVirtualTable)' != 'false'">
    <DefineConstants>$(DefineConstants);INTEROP_VIRTUAL_TABLE</DefineConstants>
  </PropertyGroup>

  <!--
      NOTE: Enable including the "session" module as a statically available
            extension?
  -->
  <PropertyGroup Condition="'$(InteropSessionExtension)' != 'false'">
    <DefineConstants>$(DefineConstants);INTEROP_SESSION_EXTENSION</DefineConstants>
  </PropertyGroup>

  <!--
      NOTE: Enable various Trace.WriteLine statements included in the code,
            based on several criteria (see the "SQLite.NET.Settings.targets"
            file for more information)?
  -->
  <PropertyGroup Condition="'$(TraceConnection)' != 'false'">
    <DefineConstants>$(DefineConstants);TRACE_CONNECTION</DefineConstants>

Changes to System.Data.SQLite/UnsafeNativeMethods.cs.

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
...
226
227
228
229
230
231
232

























233
234
235
236
237
238
239
...
485
486
487
488
489
490
491




























































492
493
494
495
496
497
498
....
3697
3698
3699
3700
3701
3702
3703

3704
3705
3706
3707
3708
3709
3710
....
3713
3714
3715
3716
3717
3718
3719











































































































































































































































































3720
3721
3722
3723
3724
3725
3726

  using System.Runtime.InteropServices;

#if (NET_40 || NET_45 || NET_451 || NET_452 || NET_46 || NET_461 || NET_462 || NET_47) && !PLATFORM_COMPACTFRAMEWORK
  using System.Runtime.Versioning;
#endif

#if !PLATFORM_COMPACTFRAMEWORK
  using System.Text;
#endif

#if !PLATFORM_COMPACTFRAMEWORK || COUNT_HANDLE
  using System.Threading;
#endif

  using System.Xml;

................................................................................
  #region Helper Methods Static Class
  /// <summary>
  /// This static class provides some methods that are shared between the
  /// native library pre-loader and other classes.
  /// </summary>
  internal static class HelperMethods
  {

























      #region Private Data
      /// <summary>
      /// This lock is used to protect the static <see cref="isMono" /> field.
      /// </summary>
      private static readonly object staticSyncRoot = new object();

      /////////////////////////////////////////////////////////////////////////
................................................................................
      {
          if (IsMono())
              return String.Format(format, args);
          else
              return String.Format(provider, format, args);
      }
      #endregion




























































  }
  #endregion

  /////////////////////////////////////////////////////////////////////////////

  #region Native Library Helper Class
  /// <summary>
................................................................................
#endif
    internal static extern IntPtr sqlite3_mprintf(IntPtr format, __arglist);
    #endregion

    // SQLite API calls that are provided by "well-known" extensions that may be statically
    // linked with the SQLite core native library currently in use.
    #region extension sqlite api calls

#if INTEROP_VIRTUAL_TABLE
#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern IntPtr sqlite3_create_disposable_module(IntPtr db, IntPtr name, ref sqlite3_module module, IntPtr pClientData, xDestroyModule xDestroy);
................................................................................
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern void sqlite3_dispose_module(IntPtr pModule);
#endif
    #endregion












































































































































































































































































    ///////////////////////////////////////////////////////////////////////////

    #region sqlite interop api calls (.NET Compact Framework only)
#if PLATFORM_COMPACTFRAMEWORK && !SQLITE_STANDARD
    [DllImport(SQLITE_DLL)]
    internal static extern void sqlite3_last_insert_rowid_interop(IntPtr db, ref long rowId);







<

<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







24
25
26
27
28
29
30

31

32
33
34
35
36
37
38
...
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
...
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
....
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
....
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077

  using System.Runtime.InteropServices;

#if (NET_40 || NET_45 || NET_451 || NET_452 || NET_46 || NET_461 || NET_462 || NET_47) && !PLATFORM_COMPACTFRAMEWORK
  using System.Runtime.Versioning;
#endif


  using System.Text;


#if !PLATFORM_COMPACTFRAMEWORK || COUNT_HANDLE
  using System.Threading;
#endif

  using System.Xml;

................................................................................
  #region Helper Methods Static Class
  /// <summary>
  /// This static class provides some methods that are shared between the
  /// native library pre-loader and other classes.
  /// </summary>
  internal static class HelperMethods
  {
      #region Private Constants
      private const string DisplayNullObject = "<nullObject>";
      private const string DisplayEmptyString = "<emptyString>";
      private const string DisplayStringFormat = "\"{0}\"";

      /////////////////////////////////////////////////////////////////////////

      private const string DisplayNullArray = "<nullArray>";
      private const string DisplayEmptyArray = "<emptyArray>";

      /////////////////////////////////////////////////////////////////////////

      private const char ArrayOpen = '[';
      private const string ElementSeparator = ", ";
      private const char ArrayClose = ']';

      /////////////////////////////////////////////////////////////////////////

      private static readonly char[] SpaceChars = {
          '\t', '\n', '\r', '\v', '\f', ' '
      };
      #endregion

      /////////////////////////////////////////////////////////////////////////

      #region Private Data
      /// <summary>
      /// This lock is used to protect the static <see cref="isMono" /> field.
      /// </summary>
      private static readonly object staticSyncRoot = new object();

      /////////////////////////////////////////////////////////////////////////
................................................................................
      {
          if (IsMono())
              return String.Format(format, args);
          else
              return String.Format(provider, format, args);
      }
      #endregion

      /////////////////////////////////////////////////////////////////////////

      #region Public Methods
      public static string ToDisplayString(
          object value
          )
      {
          if (value == null)
              return DisplayNullObject;

          string stringValue = value.ToString();

          if (stringValue.Length == 0)
              return DisplayEmptyString;

          if (stringValue.IndexOfAny(SpaceChars) < 0)
              return stringValue;

          return HelperMethods.StringFormat(
              CultureInfo.InvariantCulture, DisplayStringFormat,
              stringValue);
      }

      /////////////////////////////////////////////////////////////////////////

      public static string ToDisplayString(
          Array array
          )
      {
          if (array == null)
              return DisplayNullArray;

          if (array.Length == 0)
              return DisplayEmptyArray;

          StringBuilder result = new StringBuilder();

          foreach (object value in array)
          {
              if (result.Length > 0)
                  result.Append(ElementSeparator);

              result.Append(ToDisplayString(value));
          }

          if (result.Length > 0)
          {
#if PLATFORM_COMPACTFRAMEWORK
              result.Insert(0, ArrayOpen.ToString());
#else
              result.Insert(0, ArrayOpen);
#endif

              result.Append(ArrayClose);
          }

          return result.ToString();
      }
      #endregion
  }
  #endregion

  /////////////////////////////////////////////////////////////////////////////

  #region Native Library Helper Class
  /// <summary>
................................................................................
#endif
    internal static extern IntPtr sqlite3_mprintf(IntPtr format, __arglist);
    #endregion

    // SQLite API calls that are provided by "well-known" extensions that may be statically
    // linked with the SQLite core native library currently in use.
    #region extension sqlite api calls
    #region virtual table
#if INTEROP_VIRTUAL_TABLE
#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern IntPtr sqlite3_create_disposable_module(IntPtr db, IntPtr name, ref sqlite3_module module, IntPtr pClientData, xDestroyModule xDestroy);
................................................................................
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern void sqlite3_dispose_module(IntPtr pModule);
#endif
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region session extension
#if INTEROP_SESSION_EXTENSION
#if !PLATFORM_COMPACTFRAMEWORK
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
#endif
    internal delegate int xSessionFilter(IntPtr context, IntPtr pTblName);

#if !PLATFORM_COMPACTFRAMEWORK
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
#endif
    internal delegate SQLiteChangeSetConflictResult xSessionConflict(IntPtr context, SQLiteChangeSetConflictType type, IntPtr iterator);

#if !PLATFORM_COMPACTFRAMEWORK
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
#endif
    internal delegate SQLiteErrorCode xSessionInput(IntPtr context, IntPtr pData, ref int nData);

#if !PLATFORM_COMPACTFRAMEWORK
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
#endif
    internal delegate SQLiteErrorCode xSessionOutput(IntPtr context, IntPtr pData, int nData);

    ///////////////////////////////////////////////////////////////////////////

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3session_create(IntPtr db, byte[] dbName, ref IntPtr session);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern void sqlite3session_delete(IntPtr session);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern int sqlite3session_enable(IntPtr session, int enable);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern int sqlite3session_indirect(IntPtr session, int indirect);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3session_attach(IntPtr session, byte[] tblName);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern void sqlite3session_table_filter(IntPtr session, xSessionFilter xFilter, IntPtr context);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3session_changeset(IntPtr session, ref int nChangeSet, ref IntPtr pChangeSet);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3session_diff(IntPtr session, byte[] fromDbName, byte[] tblName, ref IntPtr errMsg);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3session_patchset(IntPtr session, ref int nPatchSet, ref IntPtr pPatchSet);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern int sqlite3session_isempty(IntPtr session);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_start(ref IntPtr iterator, int nChangeSet, IntPtr pChangeSet);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_next(IntPtr iterator);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_op(IntPtr iterator, ref IntPtr pTblName, ref int nColumns, ref SQLiteAuthorizerActionCode op, ref int bIndirect);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_pk(IntPtr iterator, ref IntPtr pPrimaryKeys, ref int nColumns);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_old(IntPtr iterator, int columnIndex, ref IntPtr pValue);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_new(IntPtr iterator, int columnIndex, ref IntPtr pValue);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_conflict(IntPtr iterator, int columnIndex, ref IntPtr pValue);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_fk_conflicts(IntPtr iterator, ref int conflicts);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_finalize(IntPtr iterator);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_invert(int nIn, IntPtr pIn, ref int nOut, ref IntPtr pOut);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_concat(int nA, IntPtr pA, int nB, IntPtr pB, ref int nOut, ref IntPtr pOut);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changegroup_new(ref IntPtr changeGroup);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changegroup_add(IntPtr changeGroup, int nData, IntPtr pData);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changegroup_output(IntPtr changeGroup, ref int nData, ref IntPtr pData);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern void sqlite3changegroup_delete(IntPtr changeGroup);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_apply(IntPtr db, int nChangeSet, IntPtr pChangeSet, xSessionFilter xFilter, xSessionConflict xConflict, IntPtr context);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_apply_strm(IntPtr db, xSessionInput xInput, IntPtr pIn, xSessionFilter xFilter, xSessionConflict xConflict, IntPtr context);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_concat_strm(xSessionInput xInputA, IntPtr pInA, xSessionInput xInputB, IntPtr pInB, xSessionOutput xOutput, IntPtr pOut);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_invert_strm(xSessionInput xInput, IntPtr pIn, xSessionOutput xOutput, IntPtr pOut);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changeset_start_strm(ref IntPtr iterator, xSessionInput xInput, IntPtr pIn);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3session_changeset_strm(IntPtr session, xSessionOutput xOutput, IntPtr pOut);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3session_patchset_strm(IntPtr session, xSessionOutput xOutput, IntPtr pOut);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changegroup_add_strm(IntPtr changeGroup, xSessionInput xInput, IntPtr pIn);

#if !PLATFORM_COMPACTFRAMEWORK
    [DllImport(SQLITE_DLL, CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport(SQLITE_DLL)]
#endif
    internal static extern SQLiteErrorCode sqlite3changegroup_output_strm(IntPtr changeGroup, xSessionOutput xOutput, IntPtr pOut);
#endif
    #endregion
    #endregion

    ///////////////////////////////////////////////////////////////////////////

    #region sqlite interop api calls (.NET Compact Framework only)
#if PLATFORM_COMPACTFRAMEWORK && !SQLITE_STANDARD
    [DllImport(SQLITE_DLL)]
    internal static extern void sqlite3_last_insert_rowid_interop(IntPtr db, ref long rowId);

Changes to Targets/SQLite.NET.Settings.targets.

706
707
708
709
710
711
712















713
714
715
716
717
718
719

                  "SQLite.Interop\props\SQLite.Interop.20YY.[vs]props"

              both for the corresponding version(s) of Visual Studio.
    -->
    <InteropVirtualTable Condition="'$(InteropVirtualTable)' == ''">true</InteropVirtualTable>
















    <!--
        NOTE: Enable the use of native Windows APIs, when available?  By
              default, this is enabled.  If this is disabled, all features
              that require the use of native Windows APIs will be unavailable.
    -->
    <UseWindows Condition="'$(UseWindows)' == ''">true</UseWindows>








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734

                  "SQLite.Interop\props\SQLite.Interop.20YY.[vs]props"

              both for the corresponding version(s) of Visual Studio.
    -->
    <InteropVirtualTable Condition="'$(InteropVirtualTable)' == ''">true</InteropVirtualTable>

    <!--
        NOTE: Enable including the session module as a statically available
              extension?  By default, this is enabled.  If this is disabled,
              support for using the session module in managed code will be
              unavailable.  If this is enabled, it must also be enabled via
              the "INTEROP_SESSION_EXTENSION=1" preprocessor define being
              present in the "INTEROP_EXTRA_DEFINES" macro in the build
              properties file:

                  "SQLite.Interop\props\SQLite.Interop.20YY.[vs]props"

              both for the corresponding version(s) of Visual Studio.
    -->
    <InteropSessionExtension Condition="'$(InteropSessionExtension)' == ''">true</InteropSessionExtension>

    <!--
        NOTE: Enable the use of native Windows APIs, when available?  By
              default, this is enabled.  If this is disabled, all features
              that require the use of native Windows APIs will be unavailable.
    -->
    <UseWindows Condition="'$(UseWindows)' == ''">true</UseWindows>

Added Tests/session.eagle.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
###############################################################################
#
# session.eagle --
#
# Written by Joe Mistachkin.
# Released to the public domain, use at your own risk!
#
###############################################################################

package require Eagle
package require Eagle.Library
package require Eagle.Test

runTestPrologue

###############################################################################

package require System.Data.SQLite.Test
runSQLiteTestPrologue

###############################################################################

proc getSomeText { random count } {
  set items [list \
      Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel \
      India Juliet Kilo Lima Mike November Oscar Papa \
      Quebec Romeo Sierra Tango Uniform Victor Whiskey X-ray \
      Yankee Zulu]

  if {!$random} then {
    variable some_text_index

    if {![info exists some_text_index]} then {
      set some_text_index 0
    }
  }

  set length [llength $items]
  set result [list]

  for {set i 0} {$i < $count} {incr i} {
    if {$random} then {
      set item [lindex $items [expr {int(rand() * $length)}]]
    } else {
      set item [lindex $items $some_text_index]
      incr some_text_index

      if {$some_text_index >= $length} then {
        set some_text_index 0
      }
    }

    lappend result $item
  }

  return $result
}

###############################################################################

proc cleanupSomeText {} {
  variable some_text_index
  unset -nocomplain some_text_index
}

###############################################################################

proc forDisplay { object member } {
  set isArray false

  if {[isObjectHandle $object] && $object ne "null"} then {
    set value [object invoke -create -- $object $member]

    if {[isObjectHandle $value] && $value ne "null"} then {
      set isArray [object invoke -- $value GetType.IsArray]
    }
  } else {
    set value null
  }

  if {$isArray} then {
    return [object invoke -flags +NonPublic \
        -parametertypes Array System.Data.SQLite.HelperMethods \
        ToDisplayString $value]
  } else {
    return [object invoke -flags +NonPublic \
        System.Data.SQLite.HelperMethods ToDisplayString $value]
  }
}

###############################################################################

proc createMemoryChangeSetForConnection { connection rawData } {
  if {[isObjectHandle $connection] && $connection ne "null"} then {
    return [$connection -alias CreateChangeSet $rawData]
  }

  return null
}

###############################################################################

proc createMemoryChangeSetForSession { session {patch false} } {
  if {[isObjectHandle $session] && $session ne "null"} then {
    set byteArray null

    if {$patch} then {
      $session -alias CreatePatchSet byteArray
    } else {
      $session -alias CreateChangeSet byteArray
    }

    set rawData [createByteArray [arrayToList byteArray]]
    object removeref $rawData

    return $rawData
  }

  return null
}

###############################################################################

proc writeRawDataToFile { fileName rawData } {
  if {[isObjectHandle $rawData] && $rawData ne "null"} then {
    set stream [object create -alias \
        System.IO.FileStream $fileName Create Write]

    $stream Write $rawData 0 [$rawData Length]
    $stream Flush; $stream Close

    return true
  }

  return false
}

###############################################################################

proc openStreamChangeSetForConnection {
        connection inputFileName outputFileName {varName ""} } {
  if {[isObjectHandle $connection] && $connection ne "null"} then {
    if {[string length $varName] > 0} then {
      upvar 1 $varName state
    }

    if {[string length $inputFileName] > 0} then {
      set state(inputStream) [object create -alias \
          System.IO.FileStream $inputFileName Open Read]
    } else {
      set state(inputStream) null
    }

    if {[string length $outputFileName] > 0} then {
      set state(outputStream) [object create -alias \
          System.IO.FileStream $outputFileName Create Write]
    } else {
      set state(outputStream) null
    }

    set state(changeSet) [$connection -alias \
        CreateChangeSet $state(inputStream) $state(outputStream)]

    return true
  }

  return false
}

###############################################################################

proc writeStreamChangeSetForSession { session fileName {patch false} } {
  if {[isObjectHandle $session] && $session ne "null"} then {
    set stream [object create -alias \
        System.IO.FileStream $fileName Create Write]

    if {$patch} then {
      $session -alias CreatePatchSet $stream
    } else {
      $session -alias CreateChangeSet $stream
    }

    $stream Flush; $stream Close

    return true
  }

  return false
}

###############################################################################

proc changeSetFileToString { connection fileName includeValues } {
  set result [list]

  if {[isObjectHandle $connection] && $connection ne "null"} then {
    if {[openStreamChangeSetForConnection \
        $connection $fileName "" state]} then {
      return [changeSetToString $state(changeSet) $includeValues]
    }
  }

  return $result
}

###############################################################################

proc metadataItemToString { item includeValues } {
  set result [list]

  if {[isObjectHandle $item] && $item ne "null"} then {
    lappend result TableName [$item TableName]
    lappend result NumberOfColumns [$item NumberOfColumns]
    lappend result OperationCode [$item OperationCode]
    lappend result Indirect [$item Indirect]

    lappend result PrimaryKeyColumns \
        [forDisplay $item PrimaryKeyColumns]

    if {$includeValues} then {
      set numberOfColumns [$item NumberOfColumns]

      for {set index 0} {$index < $numberOfColumns} {incr index} {
        set oldValue [$item GetOldValue $index]

        lappend result OldValue $index \
            [forDisplay $oldValue GetObject]

        set newValue [$item GetNewValue $index]

        lappend result NewValue $index \
            [forDisplay $newValue GetObject]

        set conflictValue [$item GetConflictValue $index]

        lappend result ConflictValue $index \
            [forDisplay $conflictValue GetObject]
      }
    }
  }

  return $result
}

###############################################################################

proc changeSetToString { changeSet includeValues } {
  set result [list]

  if {[isObjectHandle $changeSet] && $changeSet ne "null"} then {
    object foreach -alias item $changeSet {
      lappend result [metadataItemToString $item $includeValues]
    }
  }

  return $result
}

###############################################################################

proc matchSession { connection session expr } {
  if {[isObjectHandle $session] && $session ne "null"} then {
    if {![$session IsEmpty]} then {
      set rawData [createMemoryChangeSetForSession $session]
      object removeref $rawData

      if {[isObjectHandle $rawData] && $rawData ne "null"} then {
        return [matchChangeSet [set changeSet \
            [$connection -alias CreateChangeSet $rawData]] $expr]
      }
    }
  }

  return false
}

###############################################################################

proc matchChangeSet { changeSet expr } {
  if {[isObjectHandle $changeSet] && $changeSet ne "null"} then {
    object foreach -alias item $changeSet {
      if {[expr $expr]} then {return true}
    }
  }

  return false
}

###############################################################################

proc createTheSchema { db databaseName } {
  sql execute $db [subst {
    CREATE TABLE ${databaseName}.t1(x INTEGER PRIMARY KEY, y TEXT);
    CREATE TABLE ${databaseName}.t2(x INTEGER PRIMARY KEY, y TEXT);
  }]
}

###############################################################################

proc makeSomeChanges { db table types {rowId ""} {count 5} } {
  foreach type $types {
    switch -nocase -- $type {
      insert {
        set text [appendArgs "inserted: " [getSomeText false $count]]

        if {[string is integer -strict $rowId]} then {
          sql execute $db [subst {
            INSERT INTO ${table}(x, y) VALUES(?, ?);
          }] [list param1 Int32 $rowId] [list param2 String $text]
        } else {
          sql execute $db [subst {
            INSERT INTO ${table}(y) VALUES(?);
          }] [list param1 String $text]
        }
      }
      update {
        set text [appendArgs "updated: " [getSomeText false $count]]

        if {[string is integer -strict $rowId]} then {
          sql execute $db [subst {
            UPDATE ${table} SET y = ? WHERE x = ?;
          }] [list param1 String $text] [list param2 Int32 $rowId]
        } else {
          sql execute $db [subst {
            UPDATE ${table} SET y = ? WHERE x NOT IN (
              (SELECT MIN(x) FROM ${table}), (SELECT MAX(x) FROM ${table})
            );
          }] [list param1 String $text]
        }
      }
      delete {
        if {[string is integer -strict $rowId]} then {
          sql execute $db [subst {
            DELETE FROM ${table} WHERE x = ?;
          }] [list param1 Int32 $rowId]
        } else {
          sql execute $db [subst {
            DELETE FROM ${table} WHERE x = (SELECT MIN(x) FROM ${table});
          }]
        }
      }
    }
  }
}

###############################################################################

proc captureChangeSetRawData {
        connection databaseName tableName script {patch false} } {
  if {![isObjectHandle $connection] || $connection eq "null"} then {
    error "connection is invalid"
  }

  set session [$connection -alias CreateSession $databaseName]
  $session AttachTable $tableName

  if {![isObjectHandle $session] || $session eq "null"} then {
    error "cannot create session"
  }

  catch {uplevel 1 $script}
  set rawData [createMemoryChangeSetForSession $session $patch]
  object removeref $rawData

  return $rawData
}

###############################################################################

proc captureChangeSetFile {
        connection databaseName tableName script fileName {patch false} } {
  if {![isObjectHandle $connection] || $connection eq "null"} then {
    error "connection is invalid"
  }

  set session [$connection -alias CreateSession $databaseName]
  $session AttachTable $tableName

  if {![isObjectHandle $session] || $session eq "null"} then {
    error "cannot create session"
  }

  catch {uplevel 1 $script}
  writeStreamChangeSetForSession $session $fileName $patch
}

###############################################################################

proc getChangeSetFileName { {suffix ""} } {
  return [file join \
      [getTemporaryDirectory] [appendArgs changes $suffix .bin]]
}

###############################################################################

proc arrayToList { varName } {
  set result [list]

  upvar 1 $varName array

  if {[array exists array]} then {
    foreach name [lsort -integer [array names array]] {
      lappend result $array($name)
    }
  }

  return $result
}

###############################################################################

proc createByteArray { list } {
  set length [llength $list]
  set result [object create -alias System.Byte\[\] $length]

  for {set index 0} {$index < $length} {incr index} {
    set element [lindex $list $index]
    set value [object invoke -create Byte Parse $element]
    $result SetValue $value $index
  }

  return $result
}

###############################################################################

proc tableFilterCallbackT1 { clientData name } {
  lappend ::callbackResults [object invoke -create \
      System.Boolean Parse [expr {[$name ToString] in [list t1]}]]

  return [lindex $::callbackResults end]
}

###############################################################################

proc conflictCallback { clientData type item } {
  set result Abort

  if {[isObjectHandle $item] && $item ne "null"} then {
    set result Omit

    if {[$item OperationCode] ne "Delete"} then {
      if {[isObjectHandle $type] && $type ne "null" && \
          [$type ToString] in [list Data Conflict]} then {
        set result Replace
      }
    }
  }

  lappend ::callbackResults [object invoke -create Enum Parse \
      System.Data.SQLite.SQLiteChangeSetConflictResult $result false]

  return [lindex $::callbackResults end]
}

###############################################################################

runTest {test session-1.1 {basic extension usage} -setup {
  setupDb [set fileName(0) session-1.1.db]

  set fileName(1) [getChangeSetFileName 1]
  set fileName(2) [getChangeSetFileName 2]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert insert]

  set connection [getDbConnection]

  set session [$connection -alias CreateSession main]
  $session AttachTable null

  makeSomeChanges $db t1 [list insert update delete]

  set rawData [createMemoryChangeSetForSession $session]
  object removeref $rawData

  writeRawDataToFile $fileName(1) $rawData
  writeStreamChangeSetForSession $session $fileName(2)
  openStreamChangeSetForConnection $connection $fileName(2) "" state

  list [expr {[file size $fileName(1)] > 0}] \
      [string equal [readFile $fileName(1)] [readFile $fileName(2)]] \
      [changeSetToString $state(changeSet) true]
} -cleanup {
  cleanupSomeText

  unset -nocomplain state rawData byteArray session

  freeDbConnection

  unset -nocomplain connection

  cleanupFile $fileName(2)
  cleanupFile $fileName(1)

  cleanupDb $fileName(0)

  unset -nocomplain db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result {True True\
{{TableName t1 NumberOfColumns 2 OperationCode Delete Indirect False\
PrimaryKeyColumns {[True, False]} OldValue 0 1 NewValue 0 <nullObject>\
ConflictValue 0 <nullObject> OldValue 1 {"inserted: Alpha Bravo Charlie Delta\
Echo"} NewValue 1 <nullObject> ConflictValue 1 <nullObject>} {TableName t1\
NumberOfColumns 2 OperationCode Update Indirect False PrimaryKeyColumns {[True,\
False]} OldValue 0 2 NewValue 0 <nullObject> ConflictValue 0 <nullObject>\
OldValue 1 {"inserted: Foxtrot Golf Hotel India Juliet"} NewValue 1 {"updated:\
Papa Quebec Romeo Sierra Tango"} ConflictValue 1 <nullObject>} {TableName t1\
NumberOfColumns 2 OperationCode Insert Indirect False PrimaryKeyColumns {[True,\
False]} OldValue 0 <nullObject> NewValue 0 3 ConflictValue 0 <nullObject>\
OldValue 1 <nullObject> NewValue 1 {"inserted: Kilo Lima Mike November Oscar"}\
ConflictValue 1 <nullObject>}}}}

###############################################################################

runTest {test session-1.2.1 {change set read/write/invert (memory)} -setup {
  setupDb [set fileName session-1.2.1.db]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert insert insert]

  set connection [getDbConnection]

  set session [$connection -alias CreateSession main]
  $session AttachTable null

  makeSomeChanges $db t1 [list insert update delete]

  set rawData [createMemoryChangeSetForSession $session]
  object removeref $rawData

  set changeSet(1) \
      [createMemoryChangeSetForConnection $connection $rawData]

  object removeref $changeSet(1)

  set changeSet(2) [$changeSet(1) -alias Invert]

  list [changeSetToString $changeSet(2) true]
} -cleanup {
  cleanupSomeText

  unset -nocomplain changeSet rawData byteArray session

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName

  unset -nocomplain db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result \
{{{TableName t1 NumberOfColumns 2 OperationCode Insert Indirect False\
PrimaryKeyColumns {[True, False]} OldValue 0 <nullObject> NewValue 0 1\
ConflictValue 0 <nullObject> OldValue 1 <nullObject> NewValue 1 {"inserted:\
Alpha Bravo Charlie Delta Echo"} ConflictValue 1 <nullObject>} {TableName t1\
NumberOfColumns 2 OperationCode Update Indirect False PrimaryKeyColumns {[True,\
False]} OldValue 0 2 NewValue 0 <nullObject> ConflictValue 0 <nullObject>\
OldValue 1 {"updated: Uniform Victor Whiskey X-ray Yankee"} NewValue 1\
{"inserted: Foxtrot Golf Hotel India Juliet"} ConflictValue 1 <nullObject>}\
{TableName t1 NumberOfColumns 2 OperationCode Update Indirect False\
PrimaryKeyColumns {[True, False]} OldValue 0 3 NewValue 0 <nullObject>\
ConflictValue 0 <nullObject> OldValue 1 {"updated: Uniform Victor Whiskey X-ray\
Yankee"} NewValue 1 {"inserted: Kilo Lima Mike November Oscar"} ConflictValue 1\
<nullObject>} {TableName t1 NumberOfColumns 2 OperationCode Delete Indirect\
False PrimaryKeyColumns {[True, False]} OldValue 0 4 NewValue 0 <nullObject>\
ConflictValue 0 <nullObject> OldValue 1 {"inserted: Papa Quebec Romeo Sierra\
Tango"} NewValue 1 <nullObject> ConflictValue 1 <nullObject>}}}}

###############################################################################

runTest {test session-1.2.2 {change set read/write/invert (stream)} -setup {
  setupDb [set fileName(0) session-1.2.2.db]

  set fileName(1) [getChangeSetFileName 1]
  set fileName(2) [getChangeSetFileName 2]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert insert insert]

  set connection [getDbConnection]

  set session [$connection -alias CreateSession main]
  $session AttachTable null

  makeSomeChanges $db t1 [list insert update delete]

  writeStreamChangeSetForSession $session $fileName(1)

  openStreamChangeSetForConnection \
      $connection $fileName(1) $fileName(2) state

  $state(changeSet) -alias Invert; unset state
  list [changeSetFileToString $connection $fileName(2) true]
} -cleanup {
  cleanupSomeText

  unset -nocomplain state byteArray session

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName(0)

  unset -nocomplain db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result \
{{{TableName t1 NumberOfColumns 2 OperationCode Insert Indirect False\
PrimaryKeyColumns {[True, False]} OldValue 0 <nullObject> NewValue 0 1\
ConflictValue 0 <nullObject> OldValue 1 <nullObject> NewValue 1 {"inserted:\
Alpha Bravo Charlie Delta Echo"} ConflictValue 1 <nullObject>} {TableName t1\
NumberOfColumns 2 OperationCode Update Indirect False PrimaryKeyColumns {[True,\
False]} OldValue 0 2 NewValue 0 <nullObject> ConflictValue 0 <nullObject>\
OldValue 1 {"updated: Uniform Victor Whiskey X-ray Yankee"} NewValue 1\
{"inserted: Foxtrot Golf Hotel India Juliet"} ConflictValue 1 <nullObject>}\
{TableName t1 NumberOfColumns 2 OperationCode Update Indirect False\
PrimaryKeyColumns {[True, False]} OldValue 0 3 NewValue 0 <nullObject>\
ConflictValue 0 <nullObject> OldValue 1 {"updated: Uniform Victor Whiskey X-ray\
Yankee"} NewValue 1 {"inserted: Kilo Lima Mike November Oscar"} ConflictValue 1\
<nullObject>} {TableName t1 NumberOfColumns 2 OperationCode Delete Indirect\
False PrimaryKeyColumns {[True, False]} OldValue 0 4 NewValue 0 <nullObject>\
ConflictValue 0 <nullObject> OldValue 1 {"inserted: Papa Quebec Romeo Sierra\
Tango"} NewValue 1 <nullObject> ConflictValue 1 <nullObject>}}}}

###############################################################################

runTest {test session-1.3 {enabled/disabled state} -setup {
  setupDb [set fileName session-1.3.db]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert]

  set connection [getDbConnection]

  set session [$connection -alias CreateSession main]
  lappend result IsEnabled [$session IsEnabled]

  $session AttachTable null
  lappend result IsEnabled [$session IsEnabled]

  $session SetToDisabled
  lappend result IsEnabled [$session IsEnabled]

  makeSomeChanges $db t1 [list insert]
  lappend result IsEmpty [$session IsEmpty]

  set rawData [createMemoryChangeSetForSession $session]
  object removeref $rawData

  lappend result Length [$rawData Length]

  $session SetToEnabled
  lappend result IsEnabled [$session IsEnabled]

  makeSomeChanges $db t1 [list insert]
  lappend result IsEmpty [$session IsEmpty]

  set rawData [createMemoryChangeSetForSession $session]
  object removeref $rawData

  set changeSet(1) \
      [createMemoryChangeSetForConnection $connection $rawData]

  object removeref $changeSet(1)

  lappend result [changeSetToString $changeSet(1) false]
} -cleanup {
  cleanupSomeText

  unset -nocomplain result changeSet rawData byteArray session

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName

  unset -nocomplain db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result {IsEnabled\
True IsEnabled True IsEnabled False IsEmpty True Length 0 IsEnabled True\
IsEmpty False {{TableName t1 NumberOfColumns 2 OperationCode Insert Indirect\
False PrimaryKeyColumns {[True, False]}}}}}

###############################################################################

runTest {test session-1.4 {direct/indirect state} -setup {
  setupDb [set fileName session-1.4.db]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert]

  set connection [getDbConnection]

  set session [$connection -alias CreateSession main]
  lappend result IsIndirect [$session IsIndirect]

  $session AttachTable null
  lappend result IsIndirect [$session IsIndirect]

  $session SetToIndirect
  lappend result IsIndirect [$session IsIndirect]

  makeSomeChanges $db t1 [list insert]
  lappend result IsEmpty [$session IsEmpty]

  set rawData [createMemoryChangeSetForSession $session]
  object removeref $rawData

  $session SetToDirect
  lappend result IsIndirect [$session IsIndirect]

  makeSomeChanges $db t1 [list insert]
  lappend result IsEmpty [$session IsEmpty]

  set rawData [createMemoryChangeSetForSession $session]
  object removeref $rawData

  set changeSet(1) \
      [createMemoryChangeSetForConnection $connection $rawData]

  object removeref $changeSet(1)

  lappend result [changeSetToString $changeSet(1) false]
} -cleanup {
  cleanupSomeText

  unset -nocomplain result changeSet rawData byteArray session

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName

  unset -nocomplain db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result \
{IsIndirect False IsIndirect False IsIndirect True IsEmpty False IsIndirect\
False IsEmpty False {{TableName t1 NumberOfColumns 2 OperationCode Insert\
Indirect True PrimaryKeyColumns {[True, False]}} {TableName t1 NumberOfColumns\
2 OperationCode Insert Indirect False PrimaryKeyColumns {[True, False]}}}}}

###############################################################################

runTest {test session-1.5 {table filter} -setup {
  setupDb [set fileName session-1.5.db]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert]

  set connection [getDbConnection]

  set session [$connection -alias CreateSession main]

  $session -marshalflags +DynamicCallback \
      SetTableFilter tableFilterCallbackT1 null

  makeSomeChanges $db t2 [list insert]
  lappend result IsEmpty [$session IsEmpty]

  lappend result MatchT2 [matchSession $connection $session {
    [$item TableName] eq "t2"
  }]

  makeSomeChanges $db t1 [list insert]
  lappend result IsEmpty [$session IsEmpty]

  lappend result MatchT1 [matchSession $connection $session {
    [$item TableName] eq "t1"
  }]

  $session SetTableFilter null null

  makeSomeChanges $db t2 [list insert]
  lappend result IsEmpty [$session IsEmpty]

  lappend result MatchT2 [matchSession $connection $session {
    [$item TableName] eq "t2"
  }]

  makeSomeChanges $db t1 [list insert]
  lappend result IsEmpty [$session IsEmpty]

  lappend result MatchT1 [matchSession $connection $session {
    [$item TableName] eq "t1"
  }]

  set result
} -cleanup {
  cleanupSomeText

  unset -nocomplain result session

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName

  catch {object removecallback tableFilterCallbackT1}

  catch {
    foreach callbackResult $callbackResults {
      catch {object dispose $callbackResult}
    }
  }

  unset -nocomplain callbackResult callbackResults db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result {IsEmpty\
True MatchT2 false IsEmpty False MatchT1 true IsEmpty False MatchT2 true\
IsEmpty False MatchT1 true}}

###############################################################################

runTest {test session-1.6.1 {combine/apply change sets (memory)} -setup {
  setupDb [set fileName session-1.6.1.db]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert insert]

  set connection [getDbConnection]

  set rawData(1) [captureChangeSetRawData $connection main null {
    makeSomeChanges $db t1 [list delete] 1
  }]; object removeref $rawData(1)

  makeSomeChanges $db t1 [list insert] 1

  set rawData(2) [captureChangeSetRawData $connection main null {
    makeSomeChanges $db t1 [list insert]
  }]; object removeref $rawData(2)

  set changeSet(1) \
      [createMemoryChangeSetForConnection $connection $rawData(1)]

  object removeref $changeSet(1)

  set changeSet(2) \
      [createMemoryChangeSetForConnection $connection $rawData(2)]

  object removeref $changeSet(2)

  set changeSet(3) [$changeSet(1) -alias CombineWith $changeSet(2)]

  $changeSet(3) -marshalflags +DynamicCallback \
      Apply conflictCallback null

  list [changeSetToString $changeSet(3) true] Data \
      [sql execute -execute reader -format list $db \
      {SELECT x, y FROM t1 ORDER BY x;}]
} -cleanup {
  cleanupSomeText

  unset -nocomplain changeSet rawData

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName

  catch {object removecallback conflictCallback}

  catch {
    foreach callbackResult $callbackResults {
      catch {object dispose $callbackResult}
    }
  }

  unset -nocomplain callbackResult callbackResults db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result \
{{{TableName t1 NumberOfColumns 2 OperationCode Delete Indirect False\
PrimaryKeyColumns {[True, False]} OldValue 0 1 NewValue 0 <nullObject>\
ConflictValue 0 <nullObject> OldValue 1 {"inserted: Alpha Bravo Charlie Delta\
Echo"} NewValue 1 <nullObject> ConflictValue 1 <nullObject>} {TableName t1\
NumberOfColumns 2 OperationCode Insert Indirect False PrimaryKeyColumns {[True,\
False]} OldValue 0 <nullObject> NewValue 0 3 ConflictValue 0 <nullObject>\
OldValue 1 <nullObject> NewValue 1 {"inserted: Papa Quebec Romeo Sierra Tango"}\
ConflictValue 1 <nullObject>}} Data {1 {inserted: Kilo Lima Mike November\
Oscar} 2 {inserted: Foxtrot Golf Hotel India Juliet} 3 {inserted: Papa Quebec\
Romeo Sierra Tango}}}}

###############################################################################

runTest {test session-1.6.2 {combine/apply change sets (stream)} -setup {
  setupDb [set fileName(0) session-1.6.2.db]

  set fileName(1) [getChangeSetFileName 1]
  set fileName(2) [getChangeSetFileName 2]
  set fileName(3) [getChangeSetFileName 3]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert insert]

  set connection [getDbConnection]

  captureChangeSetFile $connection main null {
    makeSomeChanges $db t1 [list delete] 1
  } $fileName(1)

  makeSomeChanges $db t1 [list insert] 1

  captureChangeSetFile $connection main null {
    makeSomeChanges $db t1 [list insert]
  } $fileName(2)

  openStreamChangeSetForConnection \
      $connection $fileName(1) $fileName(3) state1

  openStreamChangeSetForConnection \
      $connection $fileName(2) "" state2

  $state1(changeSet) CombineWith $state2(changeSet); unset state1

  openStreamChangeSetForConnection \
      $connection $fileName(3) "" state3

  $state3(changeSet) -marshalflags +DynamicCallback \
      Apply conflictCallback null; unset state3

  openStreamChangeSetForConnection \
      $connection $fileName(3) "" state4

  list [changeSetToString $state4(changeSet) true] Data \
      [sql execute -execute reader -format list $db \
      {SELECT x, y FROM t1 ORDER BY x;}]
} -cleanup {
  cleanupSomeText

  unset -nocomplain state4 state3 state2 state1

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName(0)

  catch {object removecallback conflictCallback}

  catch {
    foreach callbackResult $callbackResults {
      catch {object dispose $callbackResult}
    }
  }

  unset -nocomplain callbackResult callbackResults db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result \
{{{TableName t1 NumberOfColumns 2 OperationCode Delete Indirect False\
PrimaryKeyColumns {[True, False]} OldValue 0 1 NewValue 0 <nullObject>\
ConflictValue 0 <nullObject> OldValue 1 {"inserted: Alpha Bravo Charlie Delta\
Echo"} NewValue 1 <nullObject> ConflictValue 1 <nullObject>} {TableName t1\
NumberOfColumns 2 OperationCode Insert Indirect False PrimaryKeyColumns {[True,\
False]} OldValue 0 <nullObject> NewValue 0 3 ConflictValue 0 <nullObject>\
OldValue 1 <nullObject> NewValue 1 {"inserted: Papa Quebec Romeo Sierra Tango"}\
ConflictValue 1 <nullObject>}} Data {1 {inserted: Kilo Lima Mike November\
Oscar} 2 {inserted: Foxtrot Golf Hotel India Juliet} 3 {inserted: Papa Quebec\
Romeo Sierra Tango}}}}

###############################################################################

runTest {test session-1.7.1 {combine/apply patch sets (memory)} -setup {
  setupDb [set fileName session-1.7.1.db]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert insert]

  set connection [getDbConnection]

  set rawData(1) [captureChangeSetRawData $connection main null {
    makeSomeChanges $db t1 [list delete] 1
  } true]; object removeref $rawData(1)

  makeSomeChanges $db t1 [list insert] 1

  set rawData(2) [captureChangeSetRawData $connection main null {
    makeSomeChanges $db t1 [list insert]
  } true]; object removeref $rawData(2)

  set changeSet(1) \
      [createMemoryChangeSetForConnection $connection $rawData(1)]

  object removeref $changeSet(1)

  set changeSet(2) \
      [createMemoryChangeSetForConnection $connection $rawData(2)]

  object removeref $changeSet(2)

  set changeSet(3) [$changeSet(1) -alias CombineWith $changeSet(2)]

  $changeSet(3) -marshalflags +DynamicCallback \
      Apply conflictCallback null

  list [changeSetToString $changeSet(3) true] Data \
      [sql execute -execute reader -format list $db \
      {SELECT x, y FROM t1 ORDER BY x;}]
} -cleanup {
  cleanupSomeText

  unset -nocomplain changeSet rawData

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName

  catch {object removecallback conflictCallback}

  catch {
    foreach callbackResult $callbackResults {
      catch {object dispose $callbackResult}
    }
  }

  unset -nocomplain callbackResult callbackResults db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result \
{{{TableName t1 NumberOfColumns 2 OperationCode Delete Indirect False\
PrimaryKeyColumns {[True, False]} OldValue 0 1 NewValue 0 <nullObject>\
ConflictValue 0 <nullObject> OldValue 1 <nullObject> NewValue 1 <nullObject>\
ConflictValue 1 <nullObject>} {TableName t1 NumberOfColumns 2 OperationCode\
Insert Indirect False PrimaryKeyColumns {[True, False]} OldValue 0 <nullObject>\
NewValue 0 3 ConflictValue 0 <nullObject> OldValue 1 <nullObject> NewValue 1\
{"inserted: Papa Quebec Romeo Sierra Tango"} ConflictValue 1 <nullObject>}}\
Data {2 {inserted: Foxtrot Golf Hotel India Juliet} 3 {inserted: Papa Quebec\
Romeo Sierra Tango}}}}

###############################################################################

runTest {test session-1.7.2 {combine/apply patch sets (stream)} -setup {
  setupDb [set fileName(0) session-1.7.2.db]

  set fileName(1) [getChangeSetFileName 1]
  set fileName(2) [getChangeSetFileName 2]
  set fileName(3) [getChangeSetFileName 3]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert insert]

  set connection [getDbConnection]

  captureChangeSetFile $connection main null {
    makeSomeChanges $db t1 [list delete] 1
  } $fileName(1) true

  makeSomeChanges $db t1 [list insert] 1

  captureChangeSetFile $connection main null {
    makeSomeChanges $db t1 [list insert]
  } $fileName(2) true

  openStreamChangeSetForConnection \
      $connection $fileName(1) $fileName(3) state1

  openStreamChangeSetForConnection \
      $connection $fileName(2) "" state2

  $state1(changeSet) CombineWith $state2(changeSet); unset state1

  openStreamChangeSetForConnection \
      $connection $fileName(3) "" state3

  $state3(changeSet) -marshalflags +DynamicCallback \
      Apply conflictCallback null; unset state3

  openStreamChangeSetForConnection \
      $connection $fileName(3) "" state4

  list [changeSetToString $state4(changeSet) true] Data \
      [sql execute -execute reader -format list $db \
      {SELECT x, y FROM t1 ORDER BY x;}]
} -cleanup {
  cleanupSomeText

  unset -nocomplain state4 state3 state2 state1

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName(0)

  catch {object removecallback conflictCallback}

  catch {
    foreach callbackResult $callbackResults {
      catch {object dispose $callbackResult}
    }
  }

  unset -nocomplain callbackResult callbackResults db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result \
{{{TableName t1 NumberOfColumns 2 OperationCode Delete Indirect False\
PrimaryKeyColumns {[True, False]} OldValue 0 1 NewValue 0 <nullObject>\
ConflictValue 0 <nullObject> OldValue 1 <nullObject> NewValue 1 <nullObject>\
ConflictValue 1 <nullObject>} {TableName t1 NumberOfColumns 2 OperationCode\
Insert Indirect False PrimaryKeyColumns {[True, False]} OldValue 0 <nullObject>\
NewValue 0 3 ConflictValue 0 <nullObject> OldValue 1 <nullObject> NewValue 1\
{"inserted: Papa Quebec Romeo Sierra Tango"} ConflictValue 1 <nullObject>}}\
Data {2 {inserted: Foxtrot Golf Hotel India Juliet} 3 {inserted: Papa Quebec\
Romeo Sierra Tango}}}}

###############################################################################

runTest {test session-1.8 {differences between tables} -setup {
  setupDb [set fileName session-1.8.db]

  cleanupSomeText
} -body {
  createTheSchema $db main
  makeSomeChanges $db t1 [list insert insert]

  set result [list]

  lappend result [sql execute -execute reader -format list $db \
      {SELECT x, y FROM t1 ORDER BY x;}]

  createTheSchema $db temp
  sql execute $db {INSERT INTO temp.t1 SELECT * FROM main.t1;}
  makeSomeChanges $db temp.t1 [list insert insert]

  set connection [getDbConnection]

  set session [$connection -alias CreateSession main]
  $session AttachTable null
  $session LoadDifferencesFromTable temp t1

  lappend result [sql execute -execute reader -format list $db \
      {SELECT x, y FROM t1 ORDER BY x;}]
} -cleanup {
  cleanupSomeText

  unset -nocomplain result session

  freeDbConnection

  unset -nocomplain connection

  cleanupDb $fileName

  unset -nocomplain db fileName
} -constraints {eagle command.object monoBug28 command.sql compile.DATA SQLite\
System.Data.SQLite SQLiteInterop\
defineConstant.System.Data.SQLite.INTEROP_SESSION_EXTENSION} -result {{1\
{inserted: Alpha Bravo Charlie Delta Echo} 2 {inserted: Foxtrot Golf Hotel\
India Juliet}} {1 {inserted: Alpha Bravo Charlie Delta Echo} 2 {inserted:\
Foxtrot Golf Hotel India Juliet} 3 {inserted: Kilo Lima Mike November Oscar} 4\
{inserted: Papa Quebec Romeo Sierra Tango}}}}

###############################################################################

rename conflictCallback ""
rename tableFilterCallbackT1 ""
rename createByteArray ""
rename arrayToList ""
rename getChangeSetFileName ""
rename captureChangeSetFile ""
rename captureChangeSetRawData ""
rename makeSomeChanges ""
rename createTheSchema ""
rename matchChangeSet ""
rename matchSession ""
rename changeSetToString ""
rename metadataItemToString ""
rename changeSetFileToString ""
rename writeStreamChangeSetForSession ""
rename openStreamChangeSetForConnection ""
rename writeRawDataToFile ""
rename createMemoryChangeSetForSession ""
rename createMemoryChangeSetForConnection ""
rename forDisplay ""
rename cleanupSomeText ""
rename getSomeText ""

###############################################################################

runSQLiteTestEpilogue
runTestEpilogue

Changes to data/exclude_src.txt.

34
35
36
37
38
39
40

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

62
63
64
65
66
67
68
Externals/Eagle/lib/Eagle1.0/file3.eagle
Externals/Eagle/lib/Eagle1.0/info.eagle
Externals/Eagle/lib/Eagle1.0/init.eagle
Externals/Eagle/lib/Eagle1.0/list.eagle
Externals/Eagle/lib/Eagle1.0/object.eagle
Externals/Eagle/lib/Eagle1.0/pkgIndex.eagle
Externals/Eagle/lib/Eagle1.0/pkgIndex.tcl

Externals/Eagle/lib/Eagle1.0/platform.eagle
Externals/Eagle/lib/Eagle1.0/process.eagle
Externals/Eagle/lib/Eagle1.0/runopt.eagle
Externals/Eagle/lib/Eagle1.0/safe.eagle
Externals/Eagle/lib/Eagle1.0/shell.eagle
Externals/Eagle/lib/Eagle1.0/shim.eagle
Externals/Eagle/lib/Eagle1.0/test.eagle
Externals/Eagle/lib/Eagle1.0/testlog.eagle
Externals/Eagle/lib/Eagle1.0/unkobj.eagle
Externals/Eagle/lib/Eagle1.0/update.eagle
Externals/Eagle/lib/Eagle1.0/word.tcl
Externals/Eagle/lib/Test1.0/all.eagle
Externals/Eagle/lib/Test1.0/constraints.eagle
Externals/Eagle/lib/Test1.0/epilogue.eagle
Externals/Eagle/lib/Test1.0/pkgIndex.eagle
Externals/Eagle/lib/Test1.0/pkgIndex.tcl
Externals/Eagle/lib/Test1.0/prologue.eagle
Externals/EntityFramework/*
Externals/HtmlHelp/*
Externals/MSVCPP/*
Externals/NDoc3/*

obj/*
Setup/Output/*
Setup/set_user_*.bat
SQLite.Designer/obj/*
SQLite.Designer/Properties/*
SQLite.Designer/VSDesign/*
System.Data.SQLite.Linq/obj/*







>









|
|
|
<
<
<
|
<




>







34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53



54

55
56
57
58
59
60
61
62
63
64
65
66
Externals/Eagle/lib/Eagle1.0/file3.eagle
Externals/Eagle/lib/Eagle1.0/info.eagle
Externals/Eagle/lib/Eagle1.0/init.eagle
Externals/Eagle/lib/Eagle1.0/list.eagle
Externals/Eagle/lib/Eagle1.0/object.eagle
Externals/Eagle/lib/Eagle1.0/pkgIndex.eagle
Externals/Eagle/lib/Eagle1.0/pkgIndex.tcl
Externals/Eagle/lib/Eagle1.0/pkgt.eagle
Externals/Eagle/lib/Eagle1.0/platform.eagle
Externals/Eagle/lib/Eagle1.0/process.eagle
Externals/Eagle/lib/Eagle1.0/runopt.eagle
Externals/Eagle/lib/Eagle1.0/safe.eagle
Externals/Eagle/lib/Eagle1.0/shell.eagle
Externals/Eagle/lib/Eagle1.0/shim.eagle
Externals/Eagle/lib/Eagle1.0/test.eagle
Externals/Eagle/lib/Eagle1.0/testlog.eagle
Externals/Eagle/lib/Eagle1.0/unkobj.eagle
Externals/Eagle/lib/Eagle1.0/unzip.eagle
Externals/Eagle/lib/Eagle1.0/update.eagle
Externals/Eagle/lib/Eagle1.0/word.tcl



Externals/Eagle/lib/Test1.0/*

Externals/EntityFramework/*
Externals/HtmlHelp/*
Externals/MSVCPP/*
Externals/NDoc3/*
Externals/vswhere/*
obj/*
Setup/Output/*
Setup/set_user_*.bat
SQLite.Designer/obj/*
SQLite.Designer/Properties/*
SQLite.Designer/VSDesign/*
System.Data.SQLite.Linq/obj/*

Changes to lib/System.Data.SQLite/common.eagle.

1534
1535
1536
1537
1538
1539
1540

1541
1542
1543
1544
1545
1546
1547
1548
1549
....
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
        }

        if {![info exists ::no(shimSQLiteDefineConstantConstraints)]} then {
          foreach defineConstant [list \
              INTEROP_EXTENSION_FUNCTIONS INTEROP_FTS5_EXTENSION \
              INTEROP_JSON1_EXTENSION INTEROP_PERCENTILE_EXTENSION \
              INTEROP_REGEXP_EXTENSION INTEROP_TEST_EXTENSION \

              INTEROP_SHA1_EXTENSION INTEROP_TOTYPE_EXTENSION \
              INTEROP_VIRTUAL_TABLE USE_INTEROP_DLL] {
            addConstraint [appendArgs \
                [getSQLiteDefineConstantPrefix] $defineConstant]
          }
        }

        if {![info exists ::no(shimSQLiteVisualStudioConstraints)]} then {
          addConstraint [appendArgs visualStudio [getBuildYear]]
................................................................................
        #
        foreach defineConstant [list \
            CHECK_STATE COUNT_HANDLE DEBUG INTEROP_CODEC INTEROP_DEBUG \
            INTEROP_EXTENSION_FUNCTIONS INTEROP_FTS5_EXTENSION \
            INTEROP_INCLUDE_CEROD INTEROP_INCLUDE_EXTRA INTEROP_INCLUDE_SEE \
            INTEROP_INCLUDE_ZIPVFS INTEROP_JSON1_EXTENSION \
            INTEROP_LEGACY_CLOSE INTEROP_LOG INTEROP_PERCENTILE_EXTENSION \
            INTEROP_REGEXP_EXTENSION INTEROP_SHA1_EXTENSION \
            INTEROP_TEST_EXTENSION INTEROP_TOTYPE_EXTENSION \
            INTEROP_VIRTUAL_TABLE \
            NET_20 NET_35 NET_40 NET_45 NET_451 NET_452 NET_46 NET_461 \
            NET_462 NET_47 NET_COMPACT_20 PLATFORM_COMPACTFRAMEWORK \
            PRELOAD_NATIVE_LIBRARY RETARGETABLE SQLITE_STANDARD \
            THROW_ON_DISPOSED TRACE TRACE_CONNECTION TRACE_DETECTION \
            TRACE_HANDLE TRACE_PRELOAD TRACE_SHARED TRACE_STATEMENT \
            TRACE_WARNING TRACK_MEMORY_BYTES USE_ENTITY_FRAMEWORK_6 \
            USE_INTEROP_DLL USE_PREPARE_V2 WINDOWS] {







>
|
|







 







|
|
|







1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
....
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
        }

        if {![info exists ::no(shimSQLiteDefineConstantConstraints)]} then {
          foreach defineConstant [list \
              INTEROP_EXTENSION_FUNCTIONS INTEROP_FTS5_EXTENSION \
              INTEROP_JSON1_EXTENSION INTEROP_PERCENTILE_EXTENSION \
              INTEROP_REGEXP_EXTENSION INTEROP_TEST_EXTENSION \
              INTEROP_SESSION_EXTENSION INTEROP_SHA1_EXTENSION \
              INTEROP_TOTYPE_EXTENSION INTEROP_VIRTUAL_TABLE \
              USE_INTEROP_DLL] {
            addConstraint [appendArgs \
                [getSQLiteDefineConstantPrefix] $defineConstant]
          }
        }

        if {![info exists ::no(shimSQLiteVisualStudioConstraints)]} then {
          addConstraint [appendArgs visualStudio [getBuildYear]]
................................................................................
        #
        foreach defineConstant [list \
            CHECK_STATE COUNT_HANDLE DEBUG INTEROP_CODEC INTEROP_DEBUG \
            INTEROP_EXTENSION_FUNCTIONS INTEROP_FTS5_EXTENSION \
            INTEROP_INCLUDE_CEROD INTEROP_INCLUDE_EXTRA INTEROP_INCLUDE_SEE \
            INTEROP_INCLUDE_ZIPVFS INTEROP_JSON1_EXTENSION \
            INTEROP_LEGACY_CLOSE INTEROP_LOG INTEROP_PERCENTILE_EXTENSION \
            INTEROP_REGEXP_EXTENSION INTEROP_SESSION_EXTENSION \
            INTEROP_SHA1_EXTENSION INTEROP_TEST_EXTENSION \
            INTEROP_TOTYPE_EXTENSION INTEROP_VIRTUAL_TABLE \
            NET_20 NET_35 NET_40 NET_45 NET_451 NET_452 NET_46 NET_461 \
            NET_462 NET_47 NET_COMPACT_20 PLATFORM_COMPACTFRAMEWORK \
            PRELOAD_NATIVE_LIBRARY RETARGETABLE SQLITE_STANDARD \
            THROW_ON_DISPOSED TRACE TRACE_CONNECTION TRACE_DETECTION \
            TRACE_HANDLE TRACE_PRELOAD TRACE_SHARED TRACE_STATEMENT \
            TRACE_WARNING TRACK_MEMORY_BYTES USE_ENTITY_FRAMEWORK_6 \
            USE_INTEROP_DLL USE_PREPARE_V2 WINDOWS] {

Changes to readme.htm.

208
209
210
211
212
213
214

215
216
217
218
219
220
221
<h2><b>Version History</b></h2>

<p>
    <b>1.0.106.0 - October XX, 2017 <font color="red">(release scheduled)</font></b>
</p>
<ul>
    <li>Updated to <a href="https://www.sqlite.org/releaselog/3_20_1.html">SQLite 3.20.1</a>.</li>

    <li>Add BindDecimalAsText and GetDecimalAsText connection flags to force binding and returning of decimal values as text. Pursuant to [b167206ad3].</li>
    <li>Add preliminary support for Visual Studio 2017 and the .NET Framework 4.7. This does <b>not</b> include support for the design-time components for Visual Studio, see [8292431f51].</li>
</ul>
<p>
    <b>1.0.105.2 - June 12, 2017</b>
</p>
<ul>







>







208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<h2><b>Version History</b></h2>

<p>
    <b>1.0.106.0 - October XX, 2017 <font color="red">(release scheduled)</font></b>
</p>
<ul>
    <li>Updated to <a href="https://www.sqlite.org/releaselog/3_20_1.html">SQLite 3.20.1</a>.</li>
    <li>Add full support for the native <a href="https://www.sqlite.org/sessionintro.html">session</a> extension.</li>
    <li>Add BindDecimalAsText and GetDecimalAsText connection flags to force binding and returning of decimal values as text. Pursuant to [b167206ad3].</li>
    <li>Add preliminary support for Visual Studio 2017 and the .NET Framework 4.7. This does <b>not</b> include support for the design-time components for Visual Studio, see [8292431f51].</li>
</ul>
<p>
    <b>1.0.105.2 - June 12, 2017</b>
</p>
<ul>

Changes to www/news.wiki.

45
46
47
48
49
50
51

52
53
54
55
56
57
58
<div align="center"><h2><b>Version History</b></h2></div>

<p>
    <b>1.0.106.0 - October XX, 2017 <font color="red">(release scheduled)</font></b>
</p>
<ul>
    <li>Updated to [https://www.sqlite.org/releaselog/3_20_1.html|SQLite 3.20.1].</li>

    <li>Add BindDecimalAsText and GetDecimalAsText connection flags to force binding and returning of decimal values as text. Pursuant to [b167206ad3].</li>
    <li>Add preliminary support for Visual Studio 2017 and the .NET Framework 4.7. This does <b>not</b> include support for the design-time components for Visual Studio, see [8292431f51].</li>
</ul>
<p>
    <b>1.0.105.2 - June 12, 2017</b>
</p>
<ul>







>







45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<div align="center"><h2><b>Version History</b></h2></div>

<p>
    <b>1.0.106.0 - October XX, 2017 <font color="red">(release scheduled)</font></b>
</p>
<ul>
    <li>Updated to [https://www.sqlite.org/releaselog/3_20_1.html|SQLite 3.20.1].</li>
    <li>Add full support for the native [https://www.sqlite.org/sessionintro.html|session] extension.</li>
    <li>Add BindDecimalAsText and GetDecimalAsText connection flags to force binding and returning of decimal values as text. Pursuant to [b167206ad3].</li>
    <li>Add preliminary support for Visual Studio 2017 and the .NET Framework 4.7. This does <b>not</b> include support for the design-time components for Visual Studio, see [8292431f51].</li>
</ul>
<p>
    <b>1.0.105.2 - June 12, 2017</b>
</p>
<ul>