System.Data.SQLite
Check-in [9bc8258798]
Not logged in

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

Overview
Comment:no message
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | sourceforge
Files: files | file ages | folders
SHA1: 9bc8258798fb19f12c2f6c98d2a0c91de1fe647a
User & Date: rmsimpson 2006-01-10 18:38:02
Context
2006-01-10
18:38
no message check-in: 8dc721be16 user: rmsimpson tags: sourceforge
18:38
no message check-in: 9bc8258798 user: rmsimpson tags: sourceforge
2006-01-06
16:46
Fix Connection property to allow setting to null, and fix Dispose method to erase the command from the connection check-in: 5514a73a4e user: rmsimpson tags: sourceforge
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to SQLite.Interop/SQLite.Interop.vcproj.

    32     32   			CharacterSet="2"
    33     33   			ManagedExtensions="0"
    34     34   			WholeProgramOptimization="1"
    35     35   			>
    36     36   			<Tool
    37     37   				Name="VCPreBuildEventTool"
    38     38   				Description="Building SQLite netmodule ..."
    39         -				CommandLine="cd ..\System.Data.SQLite&#x0D;&#x0A;csc /target:module /out:..\SQLite.Interop\SQlite.netmodule /o SQLite3.cs SQLite3_UTF16.cs SQLiteBase.cs SQLiteCommand.cs SQLiteCommandBuilder.cs SQLiteConnection.cs SQLiteConnectionStringBuilder.cs SQLiteConvert.cs SQLiteDataAdapter.cs SQLiteDataReader.cs SQLiteException.cs SQLiteFactory.cs SQLiteFunction.cs SQLiteFunctionAttribute.cs SQLiteParameter.cs SQLiteParameterCollection.cs SQLiteStatement.cs SQLiteTransaction.cs UnsafeNativeMethods.cs assemblyinfo.cs&#x0D;&#x0A;cd ..\SQLite.Interop&#x0D;&#x0A;"
           39  +				CommandLine="CScript //nologo fixsource.vbs&#x0D;&#x0A;cd ..\System.Data.SQLite&#x0D;&#x0A;resgen /compile SR.resx&#x0D;&#x0A;csc /target:module /out:..\SQLite.Interop\SQlite.netmodule /debug- /o+  SQLite3.cs SQLite3_UTF16.cs SQLiteBase.cs SQLiteCommand.cs SQLiteCommandBuilder.cs SQLiteConnection.cs SQLiteConnectionStringBuilder.cs SQLiteConvert.cs SQLiteDataAdapter.cs SQLiteDataReader.cs SQLiteException.cs SQLiteFactory.cs SQLiteFunction.cs SQLiteFunctionAttribute.cs SQLiteParameter.cs SQLiteParameterCollection.cs SQLiteStatement.cs SQLiteTransaction.cs UnsafeNativeMethods.cs AssemblyInfo.cs SR.Designer.cs&#x0D;&#x0A;cd ..\SQLite.Interop&#x0D;&#x0A;"
    40     40   			/>
    41     41   			<Tool
    42     42   				Name="VCCustomBuildTool"
    43     43   			/>
    44     44   			<Tool
    45     45   				Name="VCXMLDataGeneratorTool"
    46     46   			/>
................................................................................
    51     51   				Name="VCMIDLTool"
    52     52   			/>
    53     53   			<Tool
    54     54   				Name="VCCLCompilerTool"
    55     55   				AdditionalOptions="/GS-"
    56     56   				Optimization="3"
    57     57   				FavorSizeOrSpeed="1"
    58         -				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;NO_TCL;THREADSAFE"
           58  +				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;NO_TCL;THREADSAFE;SQLITE_HAS_CODEC"
    59     59   				StringPooling="true"
    60     60   				RuntimeLibrary="2"
    61     61   				DebugInformationFormat="3"
    62     62   			/>
    63     63   			<Tool
    64     64   				Name="VCManagedResourceCompilerTool"
    65     65   			/>
................................................................................
    67     67   				Name="VCResourceCompilerTool"
    68     68   			/>
    69     69   			<Tool
    70     70   				Name="VCPreLinkEventTool"
    71     71   			/>
    72     72   			<Tool
    73     73   				Name="VCLinkerTool"
    74         -				AdditionalDependencies="SQLite.netmodule  $(NOINHERIT)"
    75         -				OutputFile="$(SolutionDir)bin/System.Data.SQLite.DLL"
           74  +				AdditionalDependencies="advapi32.lib SQLite.netmodule $(NOINHERIT)"
           75  +				OutputFile="../bin/System.Data.SQLite.DLL"
    76     76   				ModuleDefinitionFile="src\sqlite3.def"
           77  +				EmbedManagedResourceFile="&quot;..\System.Data.SQLite\SR.resources,System.Data.SQLite.SR.resources&quot;"
           78  +				DelayLoadDLLs="advapi32.dll"
    77     79   				GenerateDebugInformation="true"
    78     80   				ImportLibrary="$(TargetDir)$(TargetName).lib"
    79     81   				TargetMachine="1"
    80     82   				KeyFile="..\System.Data.SQLite\System.Data.SQLite.snk"
    81     83   			/>
    82     84   			<Tool
    83     85   				Name="VCALinkTool"
................................................................................
   112    114   			ConfigurationType="2"
   113    115   			CharacterSet="1"
   114    116   			WholeProgramOptimization="0"
   115    117   			>
   116    118   			<Tool
   117    119   				Name="VCPreBuildEventTool"
   118    120   				Description="Building SQLite netmodule ..."
   119         -				CommandLine="cd ..\System.Data.SQLite&#x0D;&#x0A;csc /target:module /out:..\SQLite.Interop\SQlite.netmodule /o SQLite3.cs SQLite3_UTF16.cs SQLiteBase.cs SQLiteCommand.cs SQLiteCommandBuilder.cs SQLiteConnection.cs SQLiteConnectionStringBuilder.cs SQLiteConvert.cs SQLiteDataAdapter.cs SQLiteDataReader.cs SQLiteException.cs SQLiteFactory.cs SQLiteFunction.cs SQLiteFunctionAttribute.cs SQLiteParameter.cs SQLiteParameterCollection.cs SQLiteStatement.cs SQLiteTransaction.cs UnsafeNativeMethods.cs AssemblyInfo.cs&#x0D;&#x0A;cd ..\SQLite.Interop&#x0D;&#x0A;"
          121  +				CommandLine="CScript //nologo fixsource.vbs&#x0D;&#x0A;cd ..\System.Data.SQLite&#x0D;&#x0A;resgen /compile SR.resx&#x0D;&#x0A;csc /target:module /out:..\SQLite.Interop\SQlite.netmodule /debug- /o+  SQLite3.cs SQLite3_UTF16.cs SQLiteBase.cs SQLiteCommand.cs SQLiteCommandBuilder.cs SQLiteConnection.cs SQLiteConnectionStringBuilder.cs SQLiteConvert.cs SQLiteDataAdapter.cs SQLiteDataReader.cs SQLiteException.cs SQLiteFactory.cs SQLiteFunction.cs SQLiteFunctionAttribute.cs SQLiteParameter.cs SQLiteParameterCollection.cs SQLiteStatement.cs SQLiteTransaction.cs UnsafeNativeMethods.cs AssemblyInfo.cs SR.Designer.cs&#x0D;&#x0A;cd ..\SQLite.Interop&#x0D;&#x0A;"
   120    122   				ExcludedFromBuild="true"
   121    123   			/>
   122    124   			<Tool
   123    125   				Name="VCCustomBuildTool"
   124    126   			/>
   125    127   			<Tool
   126    128   				Name="VCXMLDataGeneratorTool"
................................................................................
   132    134   				Name="VCMIDLTool"
   133    135   			/>
   134    136   			<Tool
   135    137   				Name="VCCLCompilerTool"
   136    138   				ExecutionBucket="7"
   137    139   				AdditionalOptions="/GS-"
   138    140   				Optimization="3"
   139         -				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_WINDOWS;_USRDLL;CPPSMART_EXPORTS;$(ARCHFAM);$(_ARCHFAM_);UNICODE;_UNICODE"
          141  +				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_WINDOWS;_USRDLL;CPPSMART_EXPORTS;$(ARCHFAM);$(_ARCHFAM_);UNICODE;_UNICODE;SQLITE_HAS_CODEC"
   140    142   				StringPooling="true"
   141    143   				RuntimeLibrary="2"
   142    144   				DebugInformationFormat="3"
   143    145   			/>
   144    146   			<Tool
   145    147   				Name="VCManagedResourceCompilerTool"
   146    148   			/>
................................................................................
   153    155   			<Tool
   154    156   				Name="VCPreLinkEventTool"
   155    157   			/>
   156    158   			<Tool
   157    159   				Name="VCLinkerTool"
   158    160   				IgnoreImportLibrary="true"
   159    161   				AdditionalOptions=" /subsystem:windowsce,4.20 /machine:ARM /ARMPADCODE"
   160         -				OutputFile="$(SolutionDir)bin/CompactFramework/$(ProjectName).DLL"
          162  +				OutputFile="../bin/CompactFramework/$(ProjectName).DLL"
   161    163   				IgnoreDefaultLibraryNames="oldnames.lib"
   162    164   				ModuleDefinitionFile="src\sqlite3.def"
   163    165   				AddModuleNamesToAssembly=""
          166  +				EmbedManagedResourceFile=""
   164    167   				GenerateDebugInformation="true"
   165    168   				ImportLibrary="$(TargetDir)$(TargetName).lib"
   166    169   				TargetMachine="3"
   167    170   			/>
   168    171   			<Tool
   169    172   				Name="VCALinkTool"
   170    173   			/>
................................................................................
   178    181   				Name="VCCodeSignTool"
   179    182   			/>
   180    183   			<Tool
   181    184   				Name="VCPostBuildEventTool"
   182    185   			/>
   183    186   			<DeploymentTool
   184    187   				ForceDirty="-1"
   185         -				RemoteDirectory="%CSIDL_WINDOWS%"
          188  +				RemoteDirectory="\Program Files\testce\old"
   186    189   				RegisterOutput="0"
   187    190   				AdditionalFiles=""
   188    191   			/>
   189    192   			<DebuggerTool
   190    193   			/>
   191    194   		</Configuration>
   192    195   		<Configuration
................................................................................
   197    200   			CharacterSet="2"
   198    201   			ManagedExtensions="0"
   199    202   			WholeProgramOptimization="1"
   200    203   			>
   201    204   			<Tool
   202    205   				Name="VCPreBuildEventTool"
   203    206   				Description="Building SQLite netmodule ..."
   204         -				CommandLine="cd ..\System.Data.SQLite&#x0D;&#x0A;csc /target:module /out:..\SQLite.Interop\SQlite.netmodule /o SQLite3.cs SQLite3_UTF16.cs SQLiteBase.cs SQLiteCommand.cs SQLiteCommandBuilder.cs SQLiteConnection.cs SQLiteConnectionStringBuilder.cs SQLiteConvert.cs SQLiteDataAdapter.cs SQLiteDataReader.cs SQLiteException.cs SQLiteFactory.cs SQLiteFunction.cs SQLiteFunctionAttribute.cs SQLiteParameter.cs SQLiteParameterCollection.cs SQLiteStatement.cs SQLiteTransaction.cs UnsafeNativeMethods.cs AssemblyInfo.cs&#x0D;&#x0A;cd ..\SQLite.Interop&#x0D;&#x0A;"
          207  +				CommandLine="CScript //nologo fixsource.vbs&#x0D;&#x0A;cd ..\System.Data.SQLite&#x0D;&#x0A;resgen /compile SR.resx&#x0D;&#x0A;csc /target:module /out:..\SQLite.Interop\SQlite.netmodule /debug- /o+  SQLite3.cs SQLite3_UTF16.cs SQLiteBase.cs SQLiteCommand.cs SQLiteCommandBuilder.cs SQLiteConnection.cs SQLiteConnectionStringBuilder.cs SQLiteConvert.cs SQLiteDataAdapter.cs SQLiteDataReader.cs SQLiteException.cs SQLiteFactory.cs SQLiteFunction.cs SQLiteFunctionAttribute.cs SQLiteParameter.cs SQLiteParameterCollection.cs SQLiteStatement.cs SQLiteTransaction.cs UnsafeNativeMethods.cs AssemblyInfo.cs SR.Designer.cs&#x0D;&#x0A;cd ..\SQLite.Interop&#x0D;&#x0A;"
   205    208   			/>
   206    209   			<Tool
   207    210   				Name="VCCustomBuildTool"
   208    211   			/>
   209    212   			<Tool
   210    213   				Name="VCXMLDataGeneratorTool"
   211    214   			/>
................................................................................
   217    220   				TargetEnvironment="2"
   218    221   			/>
   219    222   			<Tool
   220    223   				Name="VCCLCompilerTool"
   221    224   				AdditionalOptions="/GS-"
   222    225   				Optimization="3"
   223    226   				FavorSizeOrSpeed="1"
   224         -				PreprocessorDefinitions="NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;NO_TCL;THREADSAFE;WIN64"
          227  +				PreprocessorDefinitions="NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;NO_TCL;THREADSAFE;WIN64;SQLITE_HAS_CODEC"
   225    228   				StringPooling="true"
   226    229   				RuntimeLibrary="2"
   227    230   				DebugInformationFormat="3"
   228    231   			/>
   229    232   			<Tool
   230    233   				Name="VCManagedResourceCompilerTool"
   231    234   			/>
................................................................................
   233    236   				Name="VCResourceCompilerTool"
   234    237   			/>
   235    238   			<Tool
   236    239   				Name="VCPreLinkEventTool"
   237    240   			/>
   238    241   			<Tool
   239    242   				Name="VCLinkerTool"
   240         -				AdditionalDependencies="SQLite.netmodule $(NOINHERIT)"
   241         -				OutputFile="$(SolutionDir)bin/Itanium/System.Data.SQLite.DLL"
          243  +				AdditionalDependencies="advapi32.lib SQLite.netmodule $(NOINHERIT)"
          244  +				OutputFile="../bin/Itanium/System.Data.SQLite.DLL"
   242    245   				ModuleDefinitionFile="src\sqlite3.def"
          246  +				EmbedManagedResourceFile="&quot;..\System.Data.SQLite\SR.resources,System.Data.SQLite.SR.resources&quot;"
          247  +				DelayLoadDLLs="advapi32.dll"
   243    248   				GenerateDebugInformation="true"
   244    249   				ImportLibrary="$(TargetDir)$(TargetName).lib"
   245    250   				TargetMachine="5"
   246    251   				KeyFile="..\System.Data.SQLite\System.Data.SQLite.IA64.snk"
   247    252   			/>
   248    253   			<Tool
   249    254   				Name="VCALinkTool"
................................................................................
   279    284   			CharacterSet="2"
   280    285   			ManagedExtensions="0"
   281    286   			WholeProgramOptimization="1"
   282    287   			>
   283    288   			<Tool
   284    289   				Name="VCPreBuildEventTool"
   285    290   				Description="Building SQLite netmodule ..."
   286         -				CommandLine="cd ..\System.Data.SQLite&#x0D;&#x0A;csc /target:module /out:..\SQLite.Interop\SQlite.netmodule /o SQLite3.cs SQLite3_UTF16.cs SQLiteBase.cs SQLiteCommand.cs SQLiteCommandBuilder.cs SQLiteConnection.cs SQLiteConnectionStringBuilder.cs SQLiteConvert.cs SQLiteDataAdapter.cs SQLiteDataReader.cs SQLiteException.cs SQLiteFactory.cs SQLiteFunction.cs SQLiteFunctionAttribute.cs SQLiteParameter.cs SQLiteParameterCollection.cs SQLiteStatement.cs SQLiteTransaction.cs UnsafeNativeMethods.cs AssemblyInfo.cs&#x0D;&#x0A;cd ..\SQLite.Interop&#x0D;&#x0A;"
          291  +				CommandLine="CScript //nologo fixsource.vbs&#x0D;&#x0A;cd ..\System.Data.SQLite&#x0D;&#x0A;resgen /compile SR.resx&#x0D;&#x0A;csc /target:module /out:..\SQLite.Interop\SQlite.netmodule /debug- /o+  SQLite3.cs SQLite3_UTF16.cs SQLiteBase.cs SQLiteCommand.cs SQLiteCommandBuilder.cs SQLiteConnection.cs SQLiteConnectionStringBuilder.cs SQLiteConvert.cs SQLiteDataAdapter.cs SQLiteDataReader.cs SQLiteException.cs SQLiteFactory.cs SQLiteFunction.cs SQLiteFunctionAttribute.cs SQLiteParameter.cs SQLiteParameterCollection.cs SQLiteStatement.cs SQLiteTransaction.cs UnsafeNativeMethods.cs AssemblyInfo.cs SR.Designer.cs&#x0D;&#x0A;cd ..\SQLite.Interop&#x0D;&#x0A;"
   287    292   			/>
   288    293   			<Tool
   289    294   				Name="VCCustomBuildTool"
   290    295   			/>
   291    296   			<Tool
   292    297   				Name="VCXMLDataGeneratorTool"
   293    298   			/>
................................................................................
   299    304   				TargetEnvironment="3"
   300    305   			/>
   301    306   			<Tool
   302    307   				Name="VCCLCompilerTool"
   303    308   				AdditionalOptions="/GS-"
   304    309   				Optimization="3"
   305    310   				FavorSizeOrSpeed="1"
   306         -				PreprocessorDefinitions="NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;NO_TCL;THREADSAFE;WIN64"
          311  +				PreprocessorDefinitions="NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;NO_TCL;THREADSAFE;WIN64;SQLITE_HAS_CODEC"
   307    312   				StringPooling="true"
   308    313   				RuntimeLibrary="2"
   309    314   				DebugInformationFormat="3"
   310    315   			/>
   311    316   			<Tool
   312    317   				Name="VCManagedResourceCompilerTool"
   313    318   			/>
................................................................................
   315    320   				Name="VCResourceCompilerTool"
   316    321   			/>
   317    322   			<Tool
   318    323   				Name="VCPreLinkEventTool"
   319    324   			/>
   320    325   			<Tool
   321    326   				Name="VCLinkerTool"
   322         -				AdditionalDependencies="SQLite.netmodule $(NOINHERIT)"
   323         -				OutputFile="$(SolutionDir)bin/x64/System.Data.SQLite.DLL"
          327  +				AdditionalDependencies="advapi32.lib SQLite.netmodule $(NOINHERIT)"
          328  +				OutputFile="../bin/x64/System.Data.SQLite.DLL"
   324    329   				ModuleDefinitionFile="src\sqlite3.def"
          330  +				EmbedManagedResourceFile="&quot;..\System.Data.SQLite\SR.resources,System.Data.SQLite.SR.resources&quot;"
          331  +				DelayLoadDLLs="advapi32.dll"
   325    332   				GenerateDebugInformation="true"
   326    333   				ImportLibrary="$(TargetDir)$(TargetName).lib"
   327    334   				TargetMachine="17"
   328    335   				KeyFile="..\System.Data.SQLite\System.Data.SQLite.X64.snk"
   329    336   			/>
   330    337   			<Tool
   331    338   				Name="VCALinkTool"
................................................................................
   425    432   			<File
   426    433   				RelativePath=".\src\main.c"
   427    434   				>
   428    435   			</File>
   429    436   			<File
   430    437   				RelativePath=".\src\opcodes.c"
   431    438   				>
          439  +			</File>
          440  +			<File
          441  +				RelativePath=".\src\os.c"
          442  +				>
   432    443   			</File>
   433    444   			<File
   434    445   				RelativePath=".\src\os_win.c"
   435    446   				>
   436         -			</File>
   437         -			<File
   438         -				RelativePath=".\src\os_wince.c"
   439         -				>
          447  +				<FileConfiguration
          448  +					Name="Release|Win32"
          449  +					>
          450  +					<Tool
          451  +						Name="VCCLCompilerTool"
          452  +					/>
          453  +				</FileConfiguration>
          454  +				<FileConfiguration
          455  +					Name="Release|Pocket PC 2003 (ARMV4)"
          456  +					>
          457  +					<Tool
          458  +						Name="VCCLCompilerTool"
          459  +					/>
          460  +				</FileConfiguration>
          461  +				<FileConfiguration
          462  +					Name="Release|Itanium"
          463  +					>
          464  +					<Tool
          465  +						Name="VCCLCompilerTool"
          466  +					/>
          467  +				</FileConfiguration>
          468  +				<FileConfiguration
          469  +					Name="Release|x64"
          470  +					>
          471  +					<Tool
          472  +						Name="VCCLCompilerTool"
          473  +					/>
          474  +				</FileConfiguration>
   440    475   			</File>
   441    476   			<File
   442    477   				RelativePath=".\src\pager.c"
   443    478   				>
          479  +				<FileConfiguration
          480  +					Name="Release|Win32"
          481  +					ExcludedFromBuild="true"
          482  +					>
          483  +					<Tool
          484  +						Name="VCCLCompilerTool"
          485  +					/>
          486  +				</FileConfiguration>
          487  +				<FileConfiguration
          488  +					Name="Release|Pocket PC 2003 (ARMV4)"
          489  +					ExcludedFromBuild="true"
          490  +					>
          491  +					<Tool
          492  +						Name="VCCLCompilerTool"
          493  +					/>
          494  +				</FileConfiguration>
          495  +				<FileConfiguration
          496  +					Name="Release|Itanium"
          497  +					ExcludedFromBuild="true"
          498  +					>
          499  +					<Tool
          500  +						Name="VCCLCompilerTool"
          501  +					/>
          502  +				</FileConfiguration>
          503  +				<FileConfiguration
          504  +					Name="Release|x64"
          505  +					ExcludedFromBuild="true"
          506  +					>
          507  +					<Tool
          508  +						Name="VCCLCompilerTool"
          509  +					/>
          510  +				</FileConfiguration>
   444    511   			</File>
   445    512   			<File
   446    513   				RelativePath=".\src\parse.c"
   447    514   				>
   448    515   			</File>
   449    516   			<File
   450    517   				RelativePath=".\src\pragma.c"
................................................................................
   461    528   			<File
   462    529   				RelativePath=".\src\random.c"
   463    530   				>
   464    531   			</File>
   465    532   			<File
   466    533   				RelativePath=".\src\select.c"
   467    534   				>
          535  +				<FileConfiguration
          536  +					Name="Release|Win32"
          537  +					ExcludedFromBuild="true"
          538  +					>
          539  +					<Tool
          540  +						Name="VCCLCompilerTool"
          541  +					/>
          542  +				</FileConfiguration>
          543  +				<FileConfiguration
          544  +					Name="Release|Pocket PC 2003 (ARMV4)"
          545  +					ExcludedFromBuild="true"
          546  +					>
          547  +					<Tool
          548  +						Name="VCCLCompilerTool"
          549  +					/>
          550  +				</FileConfiguration>
          551  +				<FileConfiguration
          552  +					Name="Release|Itanium"
          553  +					ExcludedFromBuild="true"
          554  +					>
          555  +					<Tool
          556  +						Name="VCCLCompilerTool"
          557  +					/>
          558  +				</FileConfiguration>
          559  +				<FileConfiguration
          560  +					Name="Release|x64"
          561  +					ExcludedFromBuild="true"
          562  +					>
          563  +					<Tool
          564  +						Name="VCCLCompilerTool"
          565  +					/>
          566  +				</FileConfiguration>
   468    567   			</File>
   469    568   			<File
   470    569   				RelativePath=".\src\table.c"
   471    570   				>
   472    571   			</File>
   473    572   			<File
   474    573   				RelativePath=".\src\tokenize.c"
................................................................................
   521    620   		</Filter>
   522    621   		<Filter
   523    622   			Name="Header Files"
   524    623   			Filter="h;hpp;hxx;hm;inl;inc;xsd"
   525    624   			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
   526    625   			>
   527    626   			<File
   528         -				RelativePath=".\interop.h"
   529         -				FileType="0"
   530         -				>
   531         -			</File>
   532         -			<File
   533    627   				RelativePath=".\resource.h"
   534    628   				>
   535    629   			</File>
   536    630   			<File
   537    631   				RelativePath=".\src\sqlite3.h"
   538    632   				>
          633  +			</File>
          634  +		</Filter>
          635  +		<Filter
          636  +			Name="Extras"
          637  +			>
          638  +			<File
          639  +				RelativePath=".\crypt.c"
          640  +				>
          641  +			</File>
          642  +			<File
          643  +				RelativePath=".\interop.c"
          644  +				>
   539    645   			</File>
   540    646   		</Filter>
   541    647   		<File
   542    648   			RelativePath=".\SQLite.Interop.rc"
   543    649   			>
   544    650   		</File>
   545    651   	</Files>
   546    652   	<Globals>
   547    653   	</Globals>
   548    654   </VisualStudioProject>

Added SQLite.Interop/crypt.c.

            1  +#include "src/pager.c"
            2  +
            3  +#ifndef SQLITE_OMIT_DISKIO
            4  +#ifdef SQLITE_HAS_CODEC
            5  +
            6  +#include <windows.h>
            7  +#include <wincrypt.h>
            8  +
            9  +HCRYPTPROV g_hProvider = 0; // Global instance of the cryptographic provider
           10  +
           11  +#define SQLITECRYPTERROR_PROVIDER "Cryptographic provider not available"
           12  +
           13  +typedef struct _CRYPTBLOCK
           14  +{
           15  +  HCRYPTKEY hReadKey;     // Key used to read from the database and write to the journal
           16  +  HCRYPTKEY hWriteKey;    // Key used to write to the database
           17  +  DWORD     dwPageSize;   // Size of pages
           18  +  LPVOID    pvCrypt;      // A buffer for encrypting/decrypting (if necessary)
           19  +  DWORD     dwCryptSize;  // Equal to or greater than dwPageSize.  If larger, pvCrypt is valid and this is its size
           20  +} CRYPTBLOCK, *LPCRYPTBLOCK;
           21  +
           22  +// Needed for re-keying
           23  +static void * sqlite3pager_get_codecarg(Pager *pPager)
           24  +{
           25  +  return (pPager->xCodec) ? pPager->pCodecArg: NULL;
           26  +}
           27  +
           28  +// Create a cryptographic context.  Use the enhanced provider because it is available on
           29  +// most platforms
           30  +static BOOL InitializeProvider()
           31  +{
           32  +  if (g_hProvider) return TRUE;
           33  +
           34  +  if (!CryptAcquireContext(&g_hProvider, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0))
           35  +  {
           36  +    if(!CryptAcquireContext(&g_hProvider, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET))
           37  +    {
           38  +      return FALSE;
           39  +    }
           40  +  }
           41  +  return TRUE;
           42  +}
           43  +
           44  +// Create or update a cryptographic context for a pager.
           45  +// This function will automatically determine if the encryption algorithm requires
           46  +// extra padding, and if it does, will create a temp buffer big enough to provide
           47  +// space to hold it.
           48  +static LPCRYPTBLOCK CreateCryptBlock(HCRYPTKEY hKey, Pager *pager, LPCRYPTBLOCK pExisting)
           49  +{
           50  +  LPCRYPTBLOCK pBlock;
           51  +
           52  +  if (!pExisting) // Creating a new cryptblock
           53  +  {
           54  +    pBlock = malloc(sizeof(CRYPTBLOCK));
           55  +    ZeroMemory(pBlock, sizeof(CRYPTBLOCK));
           56  +    pBlock->hReadKey = hKey;
           57  +    pBlock->hWriteKey = hKey;
           58  +  }
           59  +  else // Updating an existing cryptblock
           60  +  {
           61  +    pBlock = pExisting;
           62  +  }
           63  +
           64  +  pBlock->dwPageSize = (DWORD)pager->pageSize;
           65  +  pBlock->dwCryptSize = pBlock->dwPageSize;
           66  +
           67  +  // Existing cryptblocks may have a buffer, if so, delete it
           68  +  if (pBlock->pvCrypt)
           69  +  {
           70  +    free(pBlock->pvCrypt);
           71  +    pBlock->pvCrypt = NULL;
           72  +  }
           73  +
           74  +  // Figure out if this cryptographic key requires extra buffer space, and if so, allocate 
           75  +  // enough room for it
           76  +  if (CryptEncrypt(hKey, 0, TRUE, 0, NULL, &pBlock->dwCryptSize, pBlock->dwCryptSize * 2))
           77  +  {
           78  +    if (pBlock->dwCryptSize > pBlock->dwPageSize)
           79  +    {
           80  +      pBlock->pvCrypt = malloc(pBlock->dwCryptSize);
           81  +    }
           82  +  }
           83  +  return pBlock;
           84  +}
           85  +
           86  +// Destroy a cryptographic context and any buffers and keys allocated therein
           87  +static void DestroyCryptBlock(LPCRYPTBLOCK pBlock)
           88  +{
           89  +  // Destroy the read key if there is one
           90  +  if (pBlock->hReadKey)
           91  +  {
           92  +    CryptDestroyKey(pBlock->hReadKey);
           93  +  }
           94  +
           95  +  // If there's a writekey and its not equal to the readkey, destroy it
           96  +  if (pBlock->hWriteKey && pBlock->hWriteKey != pBlock->hReadKey)
           97  +  {
           98  +    CryptDestroyKey(pBlock->hWriteKey);
           99  +  }
          100  +
          101  +  // If there's extra buffer space allocated, free it as well
          102  +  if (pBlock->pvCrypt)
          103  +  {
          104  +    free(pBlock->pvCrypt);
          105  +  }
          106  +
          107  +  // All done with this cryptblock
          108  +  free(pBlock);
          109  +}
          110  +
          111  +// Encrypt/Decrypt functionality, called by pager.c
          112  +void sqlite3Codec(void *pArg, void *data, Pgno nPageNum, int nMode)
          113  +{
          114  +  LPCRYPTBLOCK pBlock = (LPCRYPTBLOCK)pArg;
          115  +  DWORD dwPageSize;
          116  +  LPVOID pvTemp;
          117  +  PgHdr *pageHeader;
          118  +
          119  +  if (!pBlock) return;
          120  +
          121  +  // Make sure the page size for the pager is still the same as the page size
          122  +  // for the cryptblock.  If the user changed it, we need to adjust!
          123  +  pageHeader = DATA_TO_PGHDR(data);
          124  +  if (pageHeader->pPager->pageSize != pBlock->dwPageSize)
          125  +  {
          126  +    // Update the cryptblock to reflect the new page size
          127  +    CreateCryptBlock(0, pageHeader->pPager, pBlock);
          128  +  }
          129  +
          130  +  /* Block ciphers often need to write extra padding beyond the 
          131  +  data block.  We don't have that luxury for a given page of data so
          132  +  we must copy the page data to a buffer that IS large enough to hold
          133  +  the padding.  We then encrypt the block and write the buffer back to
          134  +  the page without the unnecessary padding.
          135  +  We only use the special block of memory if its absolutely necessary. */
          136  +  if (pBlock->pvCrypt)
          137  +  {
          138  +    CopyMemory(pBlock->pvCrypt, data, pBlock->dwPageSize);
          139  +    pvTemp = data;
          140  +    data = pBlock->pvCrypt;
          141  +  }
          142  +
          143  +  switch(nMode)
          144  +  {
          145  +  case 0: // Undo a "case 7" journal file encryption
          146  +  case 2: // Reload a page
          147  +  case 3: // Load a page
          148  +    if (!pBlock->hReadKey) break;
          149  +    dwPageSize = pBlock->dwCryptSize;
          150  +    CryptDecrypt(pBlock->hReadKey, 0, TRUE, 0, (LPBYTE)data, &dwPageSize);
          151  +    break;
          152  +  case 6: // Encrypt a page for the main database file
          153  +    if (!pBlock->hWriteKey) break;
          154  +    dwPageSize = pBlock->dwPageSize;
          155  +    CryptEncrypt(pBlock->hWriteKey, 0, TRUE, 0, (LPBYTE)data, &dwPageSize, pBlock->dwCryptSize);
          156  +    break;
          157  +  case 7: // Encrypt a page for the journal file
          158  +    /* Under normal circumstances, the readkey is the same as the writekey.  However,
          159  +    when the database is being rekeyed, the readkey is not the same as the writekey.
          160  +    The rollback journal must be written using the original key for the
          161  +    database file because it is, by nature, a rollback journal.
          162  +    Therefore, for case 7, when the rollback is being written, always encrypt using
          163  +    the database's readkey, which is guaranteed to be the same key that was used to
          164  +    read the original data.
          165  +    */
          166  +    if (!pBlock->hReadKey) break;
          167  +    dwPageSize = pBlock->dwPageSize;
          168  +    CryptEncrypt(pBlock->hReadKey, 0, TRUE, 0, (LPBYTE)data, &dwPageSize, pBlock->dwCryptSize);
          169  +    break;
          170  +  }
          171  +
          172  +  // If the encryption algorithm required extra padding and we were forced to encrypt or
          173  +  // decrypt a copy of the page data to a temp buffer, then write the contents of the temp
          174  +  // buffer back to the page data minus any padding applied.
          175  +  if (pBlock->pvCrypt)
          176  +  {
          177  +    CopyMemory(pvTemp, data, pBlock->dwPageSize);
          178  +  }
          179  +}
          180  +
          181  +// Derive an encryption key from a user-supplied buffer
          182  +static HCRYPTKEY DeriveKey(const void *pKey, int nKeyLen)
          183  +{
          184  +  HCRYPTHASH hHash = 0;
          185  +  HCRYPTKEY  hKey;
          186  +
          187  +  if (!pKey || !nKeyLen) return 0;
          188  +
          189  +  if (!InitializeProvider())
          190  +  {
          191  +    return MAXDWORD;
          192  +  }
          193  +
          194  +  if (CryptCreateHash(g_hProvider, CALG_SHA1, 0, 0, &hHash))
          195  +  {
          196  +    if (CryptHashData(hHash, (LPBYTE)pKey, nKeyLen, 0))
          197  +    {
          198  +      CryptDeriveKey(g_hProvider, CALG_RC4, hHash, 0, &hKey);
          199  +    }
          200  +    CryptDestroyHash(hHash);
          201  +  }  
          202  +  return hKey;
          203  +}
          204  +
          205  +// Called by sqlite and sqlite3_key_interop to attach a key to a database.
          206  +int sqlite3CodecAttach(sqlite3 *db, int nDb, const void *pKey, int nKeyLen)
          207  +{
          208  +  int rc = SQLITE_ERROR;
          209  +  HCRYPTKEY hKey = 0;
          210  +
          211  +  // No key specified, could mean either use the main db's encryption or no encryption
          212  +  if (!pKey || !nKeyLen)
          213  +  {
          214  +    if (!nDb)
          215  +    {
          216  +      return SQLITE_OK; // Main database, no key specified so not encrypted
          217  +    }
          218  +    else // Attached database, use the main database's key
          219  +    {
          220  +      // Get the encryption block for the main database and attempt to duplicate the key
          221  +      // for use by the attached database
          222  +      LPCRYPTBLOCK pBlock = (LPCRYPTBLOCK)sqlite3pager_get_codecarg(sqlite3BtreePager(db->aDb[0].pBt));
          223  +
          224  +      if (!pBlock) return SQLITE_OK; // Main database is not encrypted so neither will be any attached database
          225  +      if (!pBlock->hReadKey) return SQLITE_OK; // Not encrypted
          226  +
          227  +      if (!CryptDuplicateKey(pBlock->hReadKey, NULL, 0, &hKey))
          228  +        return rc; // Unable to duplicate the key
          229  +    }
          230  +  }
          231  +  else // User-supplied passphrase, so create a cryptographic key out of it
          232  +  {
          233  +    hKey = DeriveKey(pKey, nKeyLen);
          234  +    if (hKey == MAXDWORD)
          235  +    {
          236  +      sqlite3Error(db, rc, SQLITECRYPTERROR_PROVIDER);
          237  +      return rc;
          238  +    }
          239  +  }
          240  +
          241  +  // Create a new encryption block and assign the codec to the new attached database
          242  +  if (hKey)
          243  +  {
          244  +    LPCRYPTBLOCK pBlock = CreateCryptBlock(hKey, sqlite3BtreePager(db->aDb[nDb].pBt), NULL);
          245  +    sqlite3pager_set_codec(sqlite3BtreePager(db->aDb[nDb].pBt), sqlite3Codec, pBlock);
          246  +    rc = SQLITE_OK;
          247  +  }
          248  +  return rc;
          249  +}
          250  +
          251  +// Once a password has been supplied and a key created, we don't keep the 
          252  +// original password for security purposes.  Therefore return NULL.
          253  +void sqlite3CodecGetKey(sqlite3 *db, int nDb, void **ppKey, int *pnKeyLen)
          254  +{
          255  +  *ppKey = NULL;
          256  +  *pnKeyLen = 0;
          257  +}
          258  +
          259  +// We do not attach this key to the temp store, only the main database.
          260  +__declspec(dllexport) int __stdcall sqlite3_key_interop(sqlite3 *db, const void *pKey, int nKeySize)
          261  +{
          262  +  return sqlite3CodecAttach(db, 0, pKey, nKeySize);
          263  +}
          264  +
          265  +// Changes the encryption key for an existing database.
          266  +__declspec(dllexport) int __stdcall sqlite3_rekey_interop(sqlite3 *db, const void *pKey, int nKeySize)
          267  +{
          268  +  Btree *pbt = db->aDb[0].pBt;
          269  +  Pager *p = sqlite3BtreePager(pbt);
          270  +  LPCRYPTBLOCK pBlock = (LPCRYPTBLOCK)sqlite3pager_get_codecarg(p);
          271  +  HCRYPTKEY hKey = DeriveKey(pKey, nKeySize);
          272  +  int rc = SQLITE_ERROR;
          273  +
          274  +  if (hKey == MAXDWORD)
          275  +  {
          276  +    sqlite3Error(db, rc, SQLITECRYPTERROR_PROVIDER);
          277  +    return rc;
          278  +  }
          279  +
          280  +  if (!pBlock && !hKey) return SQLITE_OK; // Wasn't encrypted to begin with
          281  +
          282  +  // To rekey a database, we change the writekey for the pager.  The readkey remains
          283  +  // the same
          284  +  if (!pBlock) // Encrypt an unencrypted database
          285  +  {
          286  +    pBlock = CreateCryptBlock(hKey, p, NULL);
          287  +    pBlock->hReadKey = 0; // Original database is not encrypted
          288  +    sqlite3pager_set_codec(sqlite3BtreePager(pbt), sqlite3Codec, pBlock);
          289  +  }
          290  +  else // Change the writekey for an already-encrypted database
          291  +  {
          292  +    pBlock->hWriteKey = hKey;
          293  +  }
          294  +
          295  +  // Start a transaction
          296  +  rc = sqlite3BtreeBeginTrans(pbt, 1);
          297  +
          298  +  if (!rc)
          299  +  {
          300  +    // Rewrite all the pages in the database using the new encryption key
          301  +    int nPage = sqlite3pager_pagecount(p);
          302  +    void *pPage;
          303  +    int n;
          304  +
          305  +    for(n = 1; rc == SQLITE_OK && n <= nPage; n ++)
          306  +    {
          307  +      rc = sqlite3pager_get(p, n, &pPage);
          308  +      if(!rc)
          309  +      {
          310  +        rc = sqlite3pager_write(pPage);
          311  +        sqlite3pager_unref(pPage);
          312  +      }
          313  +    }
          314  +  }
          315  +
          316  +  // If we succeeded, try and commit the transaction
          317  +  if (!rc)
          318  +  {
          319  +    rc = sqlite3BtreeCommit(pbt);
          320  +  }
          321  +
          322  +  // If we failed, rollback
          323  +  if (rc)
          324  +  {
          325  +    sqlite3BtreeRollback(pbt);
          326  +  }
          327  +
          328  +  // If we succeeded, destroy any previous read key this database used
          329  +  // and make the readkey equal to the writekey
          330  +  if (!rc)
          331  +  {
          332  +    if (pBlock->hReadKey)
          333  +    {
          334  +      CryptDestroyKey(pBlock->hReadKey);
          335  +    }
          336  +    pBlock->hReadKey = pBlock->hWriteKey;
          337  +  }
          338  +  // We failed.  Destroy the new writekey (if there was one) and revert it back to
          339  +  // the original readkey
          340  +  else
          341  +  {
          342  +    if (pBlock->hWriteKey)
          343  +    {
          344  +      CryptDestroyKey(pBlock->hWriteKey);
          345  +    }
          346  +    pBlock->hWriteKey = pBlock->hReadKey;
          347  +  }
          348  +
          349  +  // If the readkey and writekey are both empty, there's no need for a codec on this
          350  +  // pager anymore.  Destroy the crypt block and remove the codec from the pager.
          351  +  if (!pBlock->hReadKey && !pBlock->hWriteKey)
          352  +  {
          353  +    sqlite3pager_set_codec(p, NULL, NULL);
          354  +    DestroyCryptBlock(pBlock);
          355  +  }
          356  +
          357  +  return rc;
          358  +}
          359  +
          360  +int sqlite3_key(sqlite3 *db, const void *pKey, int nKey)
          361  +{
          362  +  return sqlite3_key_interop(db, pKey, nKey);
          363  +}
          364  +
          365  +int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey)
          366  +{
          367  +  return sqlite3_rekey_interop(db, pKey, nKey);
          368  +}
          369  +
          370  +#endif // SQLITE_HAS_CODEC
          371  +
          372  +#endif // SQLITE_OMIT_DISKIO

Added SQLite.Interop/fixsource.vbs.

            1  +' VBScript source code
            2  +Main
            3  +
            4  +Sub Main()
            5  +  Dim WshShell
            6  +  Set WshShell = WScript.CreateObject("WScript.Shell")
            7  +  
            8  +  Dim fso
            9  +  Set fso = WScript.CreateObject("Scripting.FileSystemObject")
           10  +  
           11  +  Dim srcFile
           12  +  Dim srcFileContents
           13  +  dim newFileContents
           14  +  
           15  +  Set srcFile = fso.OpenTextFile("src\select.c", 1)
           16  +  
           17  +  srcFileContents = srcFile.ReadAll()
           18  +  srcFile.Close()
           19  +  
           20  +  newFileContents = Replace(srcFileContents, "static void generateColumnNames(", "static void _generateColumnNames(")
           21  +  
           22  +  If (newFileContents <> srcFileContents) Then
           23  +    WScript.StdOut.WriteLine "Updating select.c"
           24  +    Set srcFile = fso.CreateTextFile("src\select.c", true)
           25  +    srcFile.Write(newFileContents)
           26  +    srcFile.Close()
           27  +  End If
           28  +  
           29  +  Set srcFile = fso.OpenTextFile("src\tokenize.c", 1)
           30  +  
           31  +  srcFileContents = srcFile.ReadAll()
           32  +  srcFile.Close()
           33  +  
           34  +  newFileContents = Replace(srcFileContents, "    case ':': {", "    case '@': case ':': {")
           35  +
           36  +  If (newFileContents <> srcFileContents) Then
           37  +    WScript.StdOut.WriteLine "Updating tokenize.c"
           38  +    Set srcFile = fso.CreateTextFile("src\tokenize.c", true)
           39  +    srcFile.Write(newFileContents)
           40  +    srcFile.Close()
           41  +  End If
           42  +
           43  +End Sub
           44  +  

Added SQLite.Interop/interop.c.

            1  +/*
            2  +   This interop file must be included at or near the top of the select.c file of the SQLite3 source distribution.
            3  +
            4  +   generateColumnNames() in the select.c must be renamed to _generateColumnNames
            5  +
            6  +*/
            7  +
            8  +#include "src/sqliteint.h"
            9  +#include "src\os.h"
           10  +
           11  +// Forward declare this function, we're implementing it later
           12  +static void generateColumnNames(
           13  +  Parse *pParse,      /* Parser context */
           14  +  SrcList *pTabList,  /* List of tables */
           15  +  ExprList *pEList    /* Expressions defining the result set */
           16  +);
           17  +
           18  +#include "src\select.c"
           19  +
           20  +/*
           21  +** Generate code that will tell the VDBE the names of columns
           22  +** in the result set.  This information is used to provide the
           23  +** azCol[] values in the callback.
           24  +*/
           25  +static void generateColumnNames(
           26  +  Parse *pParse,      /* Parser context */
           27  +  SrcList *pTabList,  /* List of tables */
           28  +  ExprList *pEList    /* Expressions defining the result set */
           29  +){
           30  +  Vdbe *v = pParse->pVdbe;
           31  +  int i, j;
           32  +  sqlite3 *db = pParse->db;
           33  +  int fullNames, shortNames;
           34  +  int realNames;                                     /*** ADDED - SQLite.Interop ***/
           35  +
           36  +  realNames = (db->flags & 0x01000000)!=0;           /*** ADDED - SQLite.Interop ***/
           37  +  if (!realNames) // Default to normal Sqlite3       /*** ADDED - SQLite.Interop ***/
           38  +  {                                                  /*** ADDED - SQLite.Interop ***/
           39  +    _generateColumnNames(pParse, pTabList, pEList);  /*** ADDED - SQLite.Interop ***/
           40  +    return;                                          /*** ADDED - SQLite.Interop ***/
           41  +  }                                                  /*** ADDED - SQLite.Interop ***/
           42  +
           43  +#ifndef SQLITE_OMIT_EXPLAIN
           44  +  /* If this is an EXPLAIN, skip this step */
           45  +  if( pParse->explain ){
           46  +    return;
           47  +  }
           48  +#endif
           49  +
           50  +  assert( v!=0 );
           51  +  if( pParse->colNamesSet || v==0 || sqlite3ThreadData()->mallocFailed ) return;
           52  +  pParse->colNamesSet = 1;
           53  +  fullNames = (db->flags & SQLITE_FullColNames)!=0;
           54  +  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
           55  +  if (realNames) fullNames = 1;                      /*** ADDED - SQLite.Interop ***/
           56  +
           57  +  sqlite3VdbeSetNumCols(v, pEList->nExpr);
           58  +  for(i=0; i<pEList->nExpr; i++){
           59  +    Expr *p;
           60  +    p = pEList->a[i].pExpr;
           61  +    if( p==0 ) continue;
           62  +    if( pEList->a[i].zName && (realNames == 0 || p->op != TK_COLUMN)){   /*** CHANGED - SQLite.Interop ***/
           63  +      char *zName = pEList->a[i].zName;
           64  +      sqlite3VdbeSetColName(v, i, zName, strlen(zName));
           65  +      continue;
           66  +    }
           67  +    if( p->op==TK_COLUMN && pTabList ){
           68  +      Table *pTab;
           69  +      char *zCol;
           70  +      int iCol = p->iColumn;
           71  +      for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
           72  +      assert( j<pTabList->nSrc );
           73  +      pTab = pTabList->a[j].pTab;
           74  +      if( iCol<0 ) iCol = pTab->iPKey;
           75  +      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
           76  +      if( iCol<0 ){
           77  +        zCol = "rowid";
           78  +      }else{
           79  +        zCol = pTab->aCol[iCol].zName;
           80  +      }
           81  +      if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
           82  +        sqlite3VdbeSetColName(v, i, (char*)p->span.z, p->span.n);
           83  +      }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
           84  +        char *zName = 0;
           85  +        char *zTab;
           86  +        char *zDb = 0;                                                          /*** ADDED - SQLite.Interop ***/
           87  +        int iDb;
           88  +
           89  +        iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
           90  +
           91  +        zTab = pTabList->a[j].zAlias;
           92  +        if( fullNames || zTab==0 ){
           93  +          if (iDb > 1) zDb = db->aDb[iDb].zName;                    /*** ADDED - SQLite.Interop ***/
           94  +          zTab = pTab->zName;
           95  +        }
           96  +        if (!zDb || !realNames) sqlite3SetString(&zName, zTab, "\x01", zCol, 0);   /*** CHANGED - SQLite.Interop ***/
           97  +        else sqlite3SetString(&zName, zDb, "\x01", zTab, "\x01", zCol, 0);            /*** ADDED - SQLite.Interop ***/
           98  +        sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
           99  +      }else{
          100  +        sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
          101  +      }
          102  +    }else if( p->span.z && p->span.z[0] ){
          103  +      sqlite3VdbeSetColName(v, i, (char*)p->span.z, p->span.n);
          104  +      /* sqlite3VdbeCompressSpace(v, addr); */
          105  +    }else{
          106  +      char zName[30];
          107  +      assert( p->op!=TK_COLUMN || pTabList==0 );
          108  +      sprintf(zName, "column%d", i+1);
          109  +      sqlite3VdbeSetColName(v, i, zName, 0);
          110  +    }
          111  +  }
          112  +  generateColumnTypes(pParse, pTabList, pEList);
          113  +}
          114  +
          115  +#ifdef OS_WIN
          116  +
          117  +#include <tchar.h>
          118  +
          119  +typedef void (__stdcall *SQLITEUSERFUNC)(void *, int, void **);
          120  +typedef int  (__stdcall *SQLITECOLLATION)(int, const void *, int, const void*);
          121  +
          122  +typedef int (__stdcall *ENCRYPTFILEW)(const wchar_t *);
          123  +typedef int (__stdcall *ENCRYPTEDSTATUSW)(const wchar_t *, unsigned long *);
          124  +typedef int (__stdcall *DECRYPTFILEW)(const wchar_t *, unsigned long);
          125  +
          126  +typedef HANDLE (__stdcall *CREATEFILEW)(
          127  +    LPCWSTR,
          128  +    DWORD,
          129  +    DWORD,
          130  +    LPSECURITY_ATTRIBUTES,
          131  +    DWORD,
          132  +    DWORD,
          133  +    HANDLE);
          134  +
          135  +// Callback wrappers
          136  +int sqlite3_interop_collationfunc(void *pv, int len1, const void *pv1, int len2, const void *pv2)
          137  +{
          138  +  SQLITECOLLATION *p = (SQLITECOLLATION *)pv;
          139  +  return p[0](len1, pv1, len2, pv2);
          140  +}
          141  +
          142  +void sqlite3_interop_func(sqlite3_context *pctx, int n, sqlite3_value **pv)
          143  +{
          144  +  SQLITEUSERFUNC *pf = (SQLITEUSERFUNC *)sqlite3_user_data(pctx);
          145  +  pf[0](pctx, n, (void **)pv);
          146  +}
          147  +
          148  +void sqlite3_interop_step(sqlite3_context *pctx, int n, sqlite3_value **pv)
          149  +{
          150  +  SQLITEUSERFUNC *pf = (SQLITEUSERFUNC *)sqlite3_user_data(pctx);
          151  +  pf[1](pctx, n, (void **)pv);
          152  +}
          153  +
          154  +void sqlite3_interop_final(sqlite3_context *pctx)
          155  +{
          156  +  SQLITEUSERFUNC *pf = (SQLITEUSERFUNC *)sqlite3_user_data(pctx);
          157  +  pf[2](pctx, 0, 0);
          158  +}
          159  +
          160  +__declspec(dllexport) void __stdcall sqlite3_sleep_interop(int milliseconds)
          161  +{
          162  +  Sleep(milliseconds);
          163  +}
          164  +
          165  +__declspec(dllexport) int sqlite3_encryptfile(const wchar_t *pwszFilename)
          166  +{
          167  +  HMODULE hMod = LoadLibrary(_T("ADVAPI32"));
          168  +  ENCRYPTFILEW pfunc;
          169  +  int n;
          170  +
          171  +  if (hMod == NULL)
          172  +  {
          173  +    SetLastError(ERROR_NOT_SUPPORTED);
          174  +    return 0;
          175  +  }
          176  +  
          177  +  pfunc = (ENCRYPTFILEW)GetProcAddress(hMod, _T("EncryptFileW"));
          178  +  if (pfunc == NULL)
          179  +  {
          180  +    SetLastError(ERROR_NOT_SUPPORTED);
          181  +    return 0;
          182  +  }
          183  +
          184  +  n = pfunc(pwszFilename);
          185  +
          186  +  FreeLibrary(hMod);
          187  +
          188  +  return n;
          189  +}
          190  +
          191  +__declspec(dllexport) int sqlite3_decryptfile(const wchar_t *pwszFilename)
          192  +{
          193  +  HMODULE hMod = LoadLibrary(_T("ADVAPI32"));
          194  +  DECRYPTFILEW pfunc;
          195  +  int n;
          196  +
          197  +  if (hMod == NULL)
          198  +  {
          199  +    SetLastError(ERROR_NOT_SUPPORTED);
          200  +    return 0;
          201  +  }
          202  +
          203  +  pfunc = (DECRYPTFILEW)GetProcAddress(hMod, _T("DecryptFileW"));
          204  +  if (pfunc == NULL)
          205  +  {
          206  +    SetLastError(ERROR_NOT_SUPPORTED);
          207  +    return 0;
          208  +  }
          209  +
          210  +  n = pfunc(pwszFilename, 0);
          211  +
          212  +  FreeLibrary(hMod);
          213  +
          214  +  return n;
          215  +}
          216  +
          217  +__declspec(dllexport) unsigned long sqlite3_encryptedstatus(const wchar_t *pwszFilename, unsigned long *pdwStatus)
          218  +{
          219  +  HMODULE hMod = LoadLibrary(_T("ADVAPI32"));
          220  +  ENCRYPTEDSTATUSW pfunc;
          221  +  int n;
          222  +
          223  +  if (hMod == NULL)
          224  +  {
          225  +    SetLastError(ERROR_NOT_SUPPORTED);
          226  +    return 0;
          227  +  }
          228  +
          229  +  pfunc = (ENCRYPTEDSTATUSW)GetProcAddress(hMod, _T("FileEncryptionStatusW"));
          230  +  if (pfunc == NULL)
          231  +  {
          232  +    SetLastError(ERROR_NOT_SUPPORTED);
          233  +    return 0;
          234  +  }
          235  +
          236  +  n = pfunc(pwszFilename, pdwStatus);
          237  +
          238  +  FreeLibrary(hMod);
          239  +
          240  +  return n;
          241  +}
          242  +
          243  +int SetCompression(const wchar_t *pwszFilename, unsigned short ufLevel)
          244  +{
          245  +#ifdef FSCTL_SET_COMPRESSION
          246  +  HMODULE hMod = GetModuleHandle(_T("KERNEL32"));
          247  +  CREATEFILEW pfunc;
          248  +  HANDLE hFile;
          249  +  unsigned long dw = 0;
          250  +  int n;
          251  +
          252  +  if (hMod == NULL)
          253  +  {
          254  +    SetLastError(ERROR_NOT_SUPPORTED);
          255  +    return 0;
          256  +  }
          257  +
          258  +  pfunc = (CREATEFILEW)GetProcAddress(hMod, _T("CreateFileW"));
          259  +  if (pfunc == NULL)
          260  +  {
          261  +    SetLastError(ERROR_NOT_SUPPORTED);
          262  +    return 0;
          263  +  }
          264  +
          265  +  hFile = pfunc(pwszFilename, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
          266  +  if (hFile == NULL)
          267  +    return 0;
          268  +
          269  +  n = DeviceIoControl(hFile, FSCTL_SET_COMPRESSION, &ufLevel, sizeof(ufLevel), NULL, 0, &dw, NULL);
          270  +
          271  +  CloseHandle(hFile);
          272  +
          273  +  return n;
          274  +#else
          275  +  SetLastError(ERROR_NOT_SUPPORTED);
          276  +  return 0;
          277  +#endif
          278  +}
          279  +
          280  +__declspec(dllexport) int __stdcall sqlite3_compressfile(const wchar_t *pwszFilename)
          281  +{
          282  +  return SetCompression(pwszFilename, COMPRESSION_FORMAT_DEFAULT);
          283  +}
          284  +
          285  +__declspec(dllexport) int __stdcall sqlite3_decompressfile(const wchar_t *pwszFilename)
          286  +{
          287  +  return SetCompression(pwszFilename, COMPRESSION_FORMAT_NONE);
          288  +}
          289  +
          290  +__declspec(dllexport) void __stdcall sqlite3_function_free_callbackcookie(void *pCookie)
          291  +{
          292  +  if (pCookie)
          293  +    free(pCookie);
          294  +}
          295  +
          296  +// sqlite3 wrappers
          297  +__declspec(dllexport) const char * __stdcall sqlite3_libversion_interop(int *plen)
          298  +{
          299  +  const char *val = sqlite3_libversion();
          300  +  *plen = (val != 0) ? strlen(val) : 0;
          301  +
          302  +  return val;
          303  +}
          304  +
          305  +__declspec(dllexport) int __stdcall sqlite3_libversion_number_interop(void)
          306  +{
          307  +  return sqlite3_libversion_number();
          308  +}
          309  +
          310  +__declspec(dllexport) int __stdcall sqlite3_close_interop(sqlite3 *db)
          311  +{
          312  +  return sqlite3_close(db);
          313  +}
          314  +
          315  +__declspec(dllexport) int __stdcall sqlite3_exec_interop(sqlite3 *db, const char *sql, sqlite3_callback cb, void *pv, char **errmsg, int *plen)
          316  +{
          317  +  int n = sqlite3_exec(db, sql, cb, pv, errmsg);
          318  +  *plen = (*errmsg != 0) ? strlen(*errmsg) : 0;
          319  +  return n;
          320  +}
          321  +
          322  +__declspec(dllexport) sqlite_int64 __stdcall sqlite3_last_insert_rowid_interop(sqlite3 *db)
          323  +{
          324  +  return sqlite3_last_insert_rowid(db);
          325  +}
          326  +
          327  +__declspec(dllexport) int __stdcall sqlite3_changes_interop(sqlite3 *db)
          328  +{
          329  +  return sqlite3_changes(db);
          330  +}
          331  +
          332  +__declspec(dllexport) int __stdcall sqlite3_total_changes_interop(sqlite3 *db)
          333  +{
          334  +  return sqlite3_total_changes(db);
          335  +}
          336  +
          337  +__declspec(dllexport) void __stdcall sqlite3_interrupt_interop(sqlite3 *db)
          338  +{
          339  +  sqlite3_interrupt(db);
          340  +}
          341  +
          342  +__declspec(dllexport) int __stdcall sqlite3_complete_interop(const char *sql)
          343  +{
          344  +  return sqlite3_complete(sql);
          345  +}
          346  +
          347  +__declspec(dllexport) int __stdcall sqlite3_complete16_interop(const void *sql)
          348  +{
          349  +  return sqlite3_complete16(sql);
          350  +}
          351  +
          352  +__declspec(dllexport) int __stdcall sqlite3_busy_handler_interop(sqlite3 *db, int(*cb)(void *, int), void *pv)
          353  +{
          354  +  return sqlite3_busy_handler(db, cb, pv);
          355  +}
          356  +
          357  +__declspec(dllexport) int __stdcall sqlite3_busy_timeout_interop(sqlite3 *db, int ms)
          358  +{
          359  +  return sqlite3_busy_timeout(db, ms);
          360  +}
          361  +
          362  +__declspec(dllexport) int __stdcall sqlite3_get_table_interop(sqlite3 *db, const char *sql, char ***resultp, int *nrow, int *ncolumn, char **errmsg, int *plen)
          363  +{
          364  +  int n = sqlite3_get_table(db, sql, resultp, nrow, ncolumn, errmsg);
          365  +  *plen = (*errmsg != 0) ? strlen((char *)*errmsg) : 0;
          366  +  return n;
          367  +}
          368  +
          369  +__declspec(dllexport) void __stdcall sqlite3_free_table_interop(char **result)
          370  +{
          371  +  sqlite3_free_table(result);
          372  +}
          373  +
          374  +__declspec(dllexport) void __stdcall sqlite3_free_interop(char *z)
          375  +{
          376  +  sqlite3_free(z);
          377  +}
          378  +
          379  +__declspec(dllexport) int __stdcall sqlite3_open_interop(const char*filename, sqlite3 **ppdb)
          380  +{
          381  +  return sqlite3_open(filename, ppdb);
          382  +}
          383  +
          384  +__declspec(dllexport) int __stdcall sqlite3_open16_interop(const void *filename, sqlite3 **ppdb)
          385  +{
          386  +  return sqlite3_open16(filename, ppdb);
          387  +}
          388  +
          389  +__declspec(dllexport) int __stdcall sqlite3_errcode_interop(sqlite3 *db)
          390  +{
          391  +  return sqlite3_errcode(db);
          392  +}
          393  +
          394  +__declspec(dllexport) const char * __stdcall sqlite3_errmsg_interop(sqlite3 *db, int *plen)
          395  +{
          396  +  const char *pval = sqlite3_errmsg(db);
          397  +  *plen = (pval != 0) ? strlen(pval) : 0;
          398  +  return pval;
          399  +}
          400  +
          401  +__declspec(dllexport) const void * __stdcall sqlite3_errmsg16_interop(sqlite3 *db, int *plen)
          402  +{
          403  +  const void *pval = sqlite3_errmsg16(db);
          404  +  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t): 0;
          405  +  return pval;
          406  +}
          407  +
          408  +__declspec(dllexport) int __stdcall sqlite3_prepare_interop(sqlite3 *db, const char *sql, int nbytes, sqlite3_stmt **ppstmt, const char **pztail, int *plen)
          409  +{
          410  +  int n = sqlite3_prepare(db, sql, nbytes, ppstmt, pztail);
          411  +  *plen = (*pztail != 0) ? strlen(*pztail) : 0;
          412  +  return n;
          413  +}
          414  +
          415  +__declspec(dllexport) int __stdcall sqlite3_prepare16_interop(sqlite3 *db, const void *sql, int nbytes, sqlite3_stmt **ppstmt, const void **pztail, int *plen)
          416  +{
          417  +  int n = sqlite3_prepare16(db, sql, nbytes, ppstmt, pztail);
          418  +  *plen = (*pztail != 0) ? wcslen((wchar_t *)*pztail) * sizeof(wchar_t) : 0;
          419  +  return n;
          420  +}
          421  +
          422  +__declspec(dllexport) int __stdcall sqlite3_bind_blob_interop(sqlite3_stmt *stmt, int iCol, const void *pv, int n, void(*cb)(void*))
          423  +{
          424  +  return sqlite3_bind_blob(stmt, iCol, pv, n, cb);
          425  +}
          426  +
          427  +__declspec(dllexport) int __stdcall sqlite3_bind_double_interop(sqlite3_stmt *stmt, int iCol, double *val)
          428  +{
          429  +	return sqlite3_bind_double(stmt,iCol,*val);
          430  +}
          431  +
          432  +__declspec(dllexport) int __stdcall sqlite3_bind_int_interop(sqlite3_stmt *stmt, int iCol, int val)
          433  +{
          434  +  return sqlite3_bind_int(stmt, iCol, val);
          435  +}
          436  +
          437  +__declspec(dllexport) int __stdcall sqlite3_bind_int64_interop(sqlite3_stmt *stmt, int iCol, sqlite_int64 *val)
          438  +{
          439  +	return sqlite3_bind_int64(stmt,iCol,*val);
          440  +}
          441  +
          442  +__declspec(dllexport) int __stdcall sqlite3_bind_null_interop(sqlite3_stmt *stmt, int iCol)
          443  +{
          444  +  return sqlite3_bind_null(stmt, iCol);
          445  +}
          446  +
          447  +__declspec(dllexport) int __stdcall sqlite3_bind_text_interop(sqlite3_stmt *stmt, int iCol, const char *val, int n, void(*cb)(void *))
          448  +{
          449  +  return sqlite3_bind_text(stmt, iCol, val, n, cb);
          450  +}
          451  +
          452  +__declspec(dllexport) int __stdcall sqlite3_bind_text16_interop(sqlite3_stmt *stmt, int iCol, const void *val, int n, void(*cb)(void *))
          453  +{
          454  +  return sqlite3_bind_text16(stmt, iCol, val, n, cb);
          455  +}
          456  +
          457  +__declspec(dllexport) int __stdcall sqlite3_bind_parameter_count_interop(sqlite3_stmt *stmt)
          458  +{
          459  +  return sqlite3_bind_parameter_count(stmt);
          460  +}
          461  +
          462  +__declspec(dllexport) const char * __stdcall sqlite3_bind_parameter_name_interop(sqlite3_stmt *stmt, int iCol, int *plen)
          463  +{
          464  +  const char *pval = sqlite3_bind_parameter_name(stmt, iCol);
          465  +  *plen = (pval != 0) ? strlen(pval) : 0;
          466  +  return pval;
          467  +}
          468  +
          469  +__declspec(dllexport) int __stdcall sqlite3_bind_parameter_index_interop(sqlite3_stmt *stmt, const char *zName)
          470  +{
          471  +  return sqlite3_bind_parameter_index(stmt, zName);
          472  +}
          473  +
          474  +__declspec(dllexport) int __stdcall sqlite3_column_count_interop(sqlite3_stmt *stmt)
          475  +{
          476  +  return sqlite3_column_count(stmt);
          477  +}
          478  +
          479  +__declspec(dllexport) const char * __stdcall sqlite3_column_name_interop(sqlite3_stmt *stmt, int iCol, int *plen)
          480  +{
          481  +  const char *pval = sqlite3_column_name(stmt, iCol);
          482  +  *plen = (pval != 0) ? strlen(pval) : 0;
          483  +  return pval;
          484  +}
          485  +
          486  +__declspec(dllexport) const void * __stdcall sqlite3_column_name16_interop(sqlite3_stmt *stmt, int iCol, int *plen)
          487  +{
          488  +  const void *pval = sqlite3_column_name16(stmt, iCol);
          489  +  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t) : 0;
          490  +  return pval;
          491  +}
          492  +
          493  +__declspec(dllexport) const char * __stdcall sqlite3_column_decltype_interop(sqlite3_stmt *stmt, int iCol, int *plen)
          494  +{
          495  +  const char *pval = sqlite3_column_decltype(stmt, iCol);
          496  +  *plen = (pval != 0) ? strlen(pval) : 0;
          497  +  return pval;
          498  +}
          499  +
          500  +__declspec(dllexport) const void * __stdcall sqlite3_column_decltype16_interop(sqlite3_stmt *stmt, int iCol, int *plen)
          501  +{
          502  +  const void *pval = sqlite3_column_decltype16(stmt, iCol);
          503  +  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t) : 0;
          504  +  return pval;
          505  +}
          506  +
          507  +__declspec(dllexport) int __stdcall sqlite3_step_interop(sqlite3_stmt *stmt)
          508  +{
          509  +  return sqlite3_step(stmt);
          510  +}
          511  +
          512  +__declspec(dllexport) int __stdcall sqlite3_data_count_interop(sqlite3_stmt *stmt)
          513  +{
          514  +  return sqlite3_data_count(stmt);
          515  +}
          516  +
          517  +__declspec(dllexport) const void * __stdcall sqlite3_column_blob_interop(sqlite3_stmt *stmt, int iCol)
          518  +{
          519  +  return sqlite3_column_blob(stmt, iCol);
          520  +}
          521  +
          522  +__declspec(dllexport) int __stdcall sqlite3_column_bytes_interop(sqlite3_stmt *stmt, int iCol)
          523  +{
          524  +  return sqlite3_column_bytes(stmt, iCol);
          525  +}
          526  +
          527  +__declspec(dllexport) int __stdcall sqlite3_column_bytes16_interop(sqlite3_stmt *stmt, int iCol)
          528  +{
          529  +  return sqlite3_column_bytes16(stmt, iCol);
          530  +}
          531  +
          532  +__declspec(dllexport) void __stdcall sqlite3_column_double_interop(sqlite3_stmt *stmt, int iCol, double *val)
          533  +{
          534  +	*val = sqlite3_column_double(stmt,iCol);
          535  +}
          536  +
          537  +__declspec(dllexport) int __stdcall sqlite3_column_int_interop(sqlite3_stmt *stmt, int iCol)
          538  +{
          539  +  return sqlite3_column_int(stmt, iCol);
          540  +}
          541  +
          542  +__declspec(dllexport) void __stdcall sqlite3_column_int64_interop(sqlite3_stmt *stmt, int iCol, sqlite_int64 *val)
          543  +{
          544  +	*val = sqlite3_column_int64(stmt,iCol);
          545  +}
          546  +
          547  +__declspec(dllexport) const unsigned char * __stdcall sqlite3_column_text_interop(sqlite3_stmt *stmt, int iCol, int *plen)
          548  +{
          549  +  const unsigned char *pval = sqlite3_column_text(stmt, iCol);
          550  +  *plen = (pval != 0) ? strlen((char *)pval) : 0;
          551  +  return pval;
          552  +}
          553  +
          554  +__declspec(dllexport) const void * __stdcall sqlite3_column_text16_interop(sqlite3_stmt *stmt, int iCol, int *plen)
          555  +{
          556  +  const void *pval = sqlite3_column_text16(stmt, iCol);
          557  +  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t): 0;
          558  +  return pval;
          559  +}
          560  +
          561  +__declspec(dllexport) int __stdcall sqlite3_column_type_interop(sqlite3_stmt *stmt, int iCol)
          562  +{
          563  +  return sqlite3_column_type(stmt, iCol);
          564  +}
          565  +
          566  +__declspec(dllexport) int __stdcall sqlite3_finalize_interop(sqlite3_stmt *stmt)
          567  +{
          568  +  return sqlite3_finalize(stmt);
          569  +}
          570  +
          571  +__declspec(dllexport) int __stdcall sqlite3_reset_interop(sqlite3_stmt *stmt)
          572  +{
          573  +  return sqlite3_reset(stmt);
          574  +}
          575  +
          576  +__declspec(dllexport) int __stdcall sqlite3_create_function_interop(sqlite3 *psql, const char *zFunctionName, int nArg, int eTextRep, SQLITEUSERFUNC func, SQLITEUSERFUNC funcstep, SQLITEUSERFUNC funcfinal, void **ppCookie)
          577  +{
          578  +  int n;
          579  +  SQLITEUSERFUNC *p = (SQLITEUSERFUNC *)malloc(sizeof(SQLITEUSERFUNC) * 3);
          580  +
          581  +  p[0] = func;
          582  +  p[1] = funcstep;
          583  +  p[2] = funcfinal;
          584  +
          585  +  *ppCookie = 0;
          586  +
          587  +  n = sqlite3_create_function(psql, zFunctionName, nArg, eTextRep, p, (func != 0) ? sqlite3_interop_func : 0, (funcstep != 0) ? sqlite3_interop_step : 0, (funcfinal != 0) ? sqlite3_interop_final : 0);
          588  +  if (n != 0)
          589  +    free(p);
          590  +  else
          591  +    *ppCookie = p;
          592  +
          593  +  return n;
          594  +}
          595  +
          596  +__declspec(dllexport) int __stdcall sqlite3_create_function16_interop(sqlite3 *psql, void *zFunctionName, int nArg, int eTextRep, SQLITEUSERFUNC func, SQLITEUSERFUNC funcstep, SQLITEUSERFUNC funcfinal, void **ppCookie)
          597  +{
          598  +  int n;
          599  +  SQLITEUSERFUNC *p = (SQLITEUSERFUNC *)malloc(sizeof(SQLITEUSERFUNC) * 3);
          600  +
          601  +  p[0] = func;
          602  +  p[1] = funcstep;
          603  +  p[2] = funcfinal;
          604  +
          605  +  *ppCookie = 0;
          606  +
          607  +  n = sqlite3_create_function16(psql, zFunctionName, nArg, eTextRep, p, (func != 0) ? sqlite3_interop_func : 0, (funcstep != 0) ? sqlite3_interop_step : 0, (funcfinal != 0) ? sqlite3_interop_final : 0);
          608  +  if (n != 0)
          609  +    free(p);
          610  +  else
          611  +    *ppCookie = p;
          612  +
          613  +  return n;
          614  +}
          615  +
          616  +__declspec(dllexport) int __stdcall sqlite3_create_collation_interop(sqlite3* db, const char *zName, int eTextRep, void* pvUser, SQLITECOLLATION func, void **ppCookie)
          617  +{
          618  +  int n;
          619  +  SQLITECOLLATION *p = (SQLITECOLLATION *)malloc(sizeof(SQLITECOLLATION));
          620  +  
          621  +  p[0] = func;
          622  +
          623  +  *ppCookie = 0;
          624  +
          625  +  n = sqlite3_create_collation(db, zName, eTextRep, p, sqlite3_interop_collationfunc);
          626  +  if (n != 0)
          627  +    free(p);
          628  +  else
          629  +    *ppCookie = p;
          630  +
          631  +  return n;
          632  +}
          633  +
          634  +__declspec(dllexport) int __stdcall sqlite3_create_collation16_interop(sqlite3* db, const void *zName, int eTextRep, void* pvUser, SQLITECOLLATION func, void **ppCookie)
          635  +{
          636  +  int n;
          637  +  SQLITECOLLATION *p = (SQLITECOLLATION *)malloc(sizeof(SQLITECOLLATION));
          638  +  
          639  +  p[0] = func;
          640  +
          641  +  *ppCookie = 0;
          642  +
          643  +  n = sqlite3_create_collation16(db, (const char *)zName, eTextRep, p, sqlite3_interop_collationfunc);
          644  +  if (n != 0)
          645  +    free(p);
          646  +  else
          647  +    *ppCookie = p;
          648  +
          649  +  return n;
          650  +}
          651  +
          652  +__declspec(dllexport) int __stdcall sqlite3_aggregate_count_interop(sqlite3_context *pctx)
          653  +{
          654  +  return sqlite3_aggregate_count(pctx);
          655  +}
          656  +
          657  +__declspec(dllexport) const void * __stdcall sqlite3_value_blob_interop(sqlite3_value *val)
          658  +{
          659  +  return sqlite3_value_blob(val);
          660  +}
          661  +
          662  +__declspec(dllexport) int __stdcall sqlite3_value_bytes_interop(sqlite3_value *val)
          663  +{
          664  +  return sqlite3_value_bytes(val);
          665  +}
          666  +
          667  +__declspec(dllexport) int __stdcall sqlite3_value_bytes16_interop(sqlite3_value *val)
          668  +{
          669  +  return sqlite3_value_bytes16(val);
          670  +}
          671  +
          672  +__declspec(dllexport) void __stdcall sqlite3_value_double_interop(sqlite3_value *pval, double *val)
          673  +{
          674  +  *val = sqlite3_value_double(pval);
          675  +}
          676  +
          677  +__declspec(dllexport) int __stdcall sqlite3_value_int_interop(sqlite3_value *val)
          678  +{
          679  +  return sqlite3_value_int(val);
          680  +}
          681  +
          682  +__declspec(dllexport) void __stdcall sqlite3_value_int64_interop(sqlite3_value *pval, sqlite_int64 *val)
          683  +{
          684  +  *val = sqlite3_value_int64(pval);
          685  +}
          686  +
          687  +__declspec(dllexport) const unsigned char * __stdcall sqlite3_value_text_interop(sqlite3_value *val, int *plen)
          688  +{
          689  +  const unsigned char *pval = sqlite3_value_text(val);
          690  +  *plen = (pval != 0) ? strlen((char *)pval) : 0;
          691  +  return pval;
          692  +}
          693  +
          694  +__declspec(dllexport) const void * __stdcall sqlite3_value_text16_interop(sqlite3_value *val, int *plen)
          695  +{
          696  +  const void *pval = sqlite3_value_text16(val);
          697  +  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t) : 0;
          698  +  return pval;
          699  +}
          700  +
          701  +__declspec(dllexport) int __stdcall sqlite3_value_type_interop(sqlite3_value *val)
          702  +{
          703  +  return sqlite3_value_type(val);
          704  +}
          705  +
          706  +__declspec(dllexport) void * __stdcall sqlite3_aggregate_context_interop(sqlite3_context *pctx, int n)
          707  +{
          708  +  return sqlite3_aggregate_context(pctx, n);
          709  +}
          710  +
          711  +__declspec(dllexport) void __stdcall sqlite3_result_blob_interop(sqlite3_context *ctx, const void *pv, int n, void(*cb)(void *))
          712  +{
          713  +  sqlite3_result_blob(ctx, pv, n, cb);
          714  +}
          715  +
          716  +__declspec(dllexport) void __stdcall sqlite3_result_double_interop(sqlite3_context *pctx, double *val)
          717  +{
          718  +  sqlite3_result_double(pctx, *val);
          719  +}
          720  +
          721  +__declspec(dllexport) void __stdcall sqlite3_result_int_interop(sqlite3_context *pctx, int val)
          722  +{
          723  +  sqlite3_result_int(pctx, val);
          724  +}
          725  +
          726  +__declspec(dllexport) void __stdcall sqlite3_result_int64_interop(sqlite3_context *pctx, sqlite_int64 *val)
          727  +{
          728  +  sqlite3_result_int64(pctx, *val);
          729  +}
          730  +
          731  +__declspec(dllexport) void __stdcall sqlite3_result_null_interop(sqlite3_context *pctx)
          732  +{
          733  +  sqlite3_result_null(pctx);
          734  +}
          735  +
          736  +__declspec(dllexport) void __stdcall sqlite3_result_error_interop(sqlite3_context *ctx, const char *pv, int n)
          737  +{
          738  +  sqlite3_result_error(ctx, pv, n);
          739  +}
          740  +
          741  +__declspec(dllexport) void __stdcall sqlite3_result_error16_interop(sqlite3_context *ctx, const void *pv, int n)
          742  +{
          743  +  sqlite3_result_error16(ctx, pv, n);
          744  +}
          745  +
          746  +__declspec(dllexport) void __stdcall sqlite3_result_text_interop(sqlite3_context *ctx, const char *pv, int n, void(*cb)(void *))
          747  +{
          748  +  sqlite3_result_text(ctx, pv, n, cb);
          749  +}
          750  +
          751  +__declspec(dllexport) void __stdcall sqlite3_result_text16_interop(sqlite3_context *ctx, const void *pv, int n, void(*cb)(void *))
          752  +{
          753  +  sqlite3_result_text16(ctx, pv, n, cb);
          754  +}
          755  +
          756  +__declspec(dllexport) void __stdcall sqlite3_realcolnames(sqlite3 *db, int bOn)
          757  +{
          758  +  if (bOn)
          759  +    db->flags |= 0x01000000;
          760  +  else
          761  +    db->flags &= (~0x01000000);
          762  +}
          763  +
          764  +#endif // OS_WIN

Deleted SQLite.Interop/interop.h.

     1         -/*
     2         -   This interop file must be included at or near the top of the select.c file of the SQLite3 source distribution.
     3         -
     4         -   generateColumnNames() in the select.c must be renamed to _generateColumnNames
     5         -
     6         -*/
     7         -#include "os.h"
     8         -#include "sqliteint.h"
     9         -
    10         -static void generateColumnTypes(
    11         -  Parse *pParse,      /* Parser context */
    12         -  SrcList *pTabList,  /* List of tables */
    13         -  ExprList *pEList    /* Expressions defining the result set */
    14         -);
    15         -
    16         -static void _generateColumnNames(
    17         -  Parse *pParse,      /* Parser context */
    18         -  SrcList *pTabList,  /* List of tables */
    19         -  ExprList *pEList    /* Expressions defining the result set */
    20         -);
    21         -
    22         -/*
    23         -** Generate code that will tell the VDBE the names of columns
    24         -** in the result set.  This information is used to provide the
    25         -** azCol[] values in the callback.
    26         -*/
    27         -static void generateColumnNames(
    28         -  Parse *pParse,      /* Parser context */
    29         -  SrcList *pTabList,  /* List of tables */
    30         -  ExprList *pEList    /* Expressions defining the result set */
    31         -){
    32         -  Vdbe *v = pParse->pVdbe;
    33         -  int i, j;
    34         -  sqlite3 *db = pParse->db;
    35         -  int fullNames, shortNames;
    36         -  int realNames;                                     /*** ADDED - SQLite.Interop ***/
    37         -
    38         -  realNames = (db->flags & 0x01000000)!=0;           /*** ADDED - SQLite.Interop ***/
    39         -  if (!realNames) // Default to normal Sqlite3       /*** ADDED - SQLite.Interop ***/
    40         -  {                                                  /*** ADDED - SQLite.Interop ***/
    41         -    _generateColumnNames(pParse, pTabList, pEList);  /*** ADDED - SQLite.Interop ***/
    42         -    return;                                          /*** ADDED - SQLite.Interop ***/
    43         -  }                                                  /*** ADDED - SQLite.Interop ***/
    44         -
    45         -#ifndef SQLITE_OMIT_EXPLAIN
    46         -  /* If this is an EXPLAIN, skip this step */
    47         -  if( pParse->explain ){
    48         -    return;
    49         -  }
    50         -#endif
    51         -
    52         -  assert( v!=0 );
    53         -  if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
    54         -  pParse->colNamesSet = 1;
    55         -  fullNames = (db->flags & SQLITE_FullColNames)!=0;
    56         -  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
    57         -  if (realNames) fullNames = 1;                      /*** ADDED - SQLite.Interop ***/
    58         -
    59         -  sqlite3VdbeSetNumCols(v, pEList->nExpr);
    60         -  for(i=0; i<pEList->nExpr; i++){
    61         -    Expr *p;
    62         -    p = pEList->a[i].pExpr;
    63         -    if( p==0 ) continue;
    64         -    if( pEList->a[i].zName && (realNames == 0 || p->op != TK_COLUMN)){   /*** CHANGED - SQLite.Interop ***/
    65         -      char *zName = pEList->a[i].zName;
    66         -      sqlite3VdbeSetColName(v, i, zName, strlen(zName));
    67         -      continue;
    68         -    }
    69         -    if( p->op==TK_COLUMN && pTabList ){
    70         -      Table *pTab;
    71         -      char *zCol;
    72         -      int iCol = p->iColumn;
    73         -      for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
    74         -      assert( j<pTabList->nSrc );
    75         -      pTab = pTabList->a[j].pTab;
    76         -      if( iCol<0 ) iCol = pTab->iPKey;
    77         -      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
    78         -      if( iCol<0 ){
    79         -        zCol = "rowid";
    80         -      }else{
    81         -        zCol = pTab->aCol[iCol].zName;
    82         -      }
    83         -      if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
    84         -        sqlite3VdbeSetColName(v, i, (char *)p->span.z, p->span.n);
    85         -      }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
    86         -        char *zName = 0;
    87         -        char *zTab;
    88         -        char *zDb = 0;                                                          /*** ADDED - SQLite.Interop ***/
    89         - 
    90         -        zTab = pTabList->a[j].zAlias;
    91         -        if( fullNames || zTab==0 ){
    92         -          if (pTab->iDb > 1) zDb = db->aDb[pTab->iDb].zName;                    /*** ADDED - SQLite.Interop ***/
    93         -          zTab = pTab->zName;
    94         -        }
    95         -        if (!zDb || !realNames) sqlite3SetString(&zName, zTab, ".", zCol, 0);   /*** CHANGED - SQLite.Interop ***/
    96         -        else sqlite3SetString(&zName, zDb, ".", zTab, ".", zCol, 0);            /*** ADDED - SQLite.Interop ***/
    97         -        sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
    98         -      }else{
    99         -        sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
   100         -      }
   101         -    }else if( p->span.z && p->span.z[0] ){
   102         -      sqlite3VdbeSetColName(v, i, (char *)p->span.z, p->span.n);
   103         -      /* sqlite3VdbeCompressSpace(v, addr); */
   104         -    }else{
   105         -      char zName[30];
   106         -      assert( p->op!=TK_COLUMN || pTabList==0 );
   107         -      sprintf(zName, "column%d", i+1);
   108         -      sqlite3VdbeSetColName(v, i, zName, 0);
   109         -    }
   110         -  }
   111         -  generateColumnTypes(pParse, pTabList, pEList);
   112         -}
   113         -
   114         -#ifdef OS_WIN
   115         -
   116         -#include <tchar.h>
   117         -
   118         -typedef void (__stdcall *SQLITEUSERFUNC)(void *, int, void **);
   119         -typedef int  (__stdcall *SQLITECOLLATION)(int, const void *, int, const void*);
   120         -
   121         -typedef int (__stdcall *ENCRYPTFILEW)(const wchar_t *);
   122         -typedef int (__stdcall *ENCRYPTEDSTATUSW)(const wchar_t *, unsigned long *);
   123         -typedef int (__stdcall *DECRYPTFILEW)(const wchar_t *, unsigned long);
   124         -
   125         -typedef HANDLE (__stdcall *CREATEFILEW)(
   126         -    LPCWSTR,
   127         -    DWORD,
   128         -    DWORD,
   129         -    LPSECURITY_ATTRIBUTES,
   130         -    DWORD,
   131         -    DWORD,
   132         -    HANDLE);
   133         -
   134         -// Callback wrappers
   135         -int sqlite3_interop_collationfunc(void *pv, int len1, const void *pv1, int len2, const void *pv2)
   136         -{
   137         -  SQLITECOLLATION *p = (SQLITECOLLATION *)pv;
   138         -  return p[0](len1, pv1, len2, pv2);
   139         -}
   140         -
   141         -void sqlite3_interop_func(sqlite3_context *pctx, int n, sqlite3_value **pv)
   142         -{
   143         -  SQLITEUSERFUNC *pf = (SQLITEUSERFUNC *)sqlite3_user_data(pctx);
   144         -  pf[0](pctx, n, (void **)pv);
   145         -}
   146         -
   147         -void sqlite3_interop_step(sqlite3_context *pctx, int n, sqlite3_value **pv)
   148         -{
   149         -  SQLITEUSERFUNC *pf = (SQLITEUSERFUNC *)sqlite3_user_data(pctx);
   150         -  pf[1](pctx, n, (void **)pv);
   151         -}
   152         -
   153         -void sqlite3_interop_final(sqlite3_context *pctx)
   154         -{
   155         -  SQLITEUSERFUNC *pf = (SQLITEUSERFUNC *)sqlite3_user_data(pctx);
   156         -  pf[2](pctx, 0, 0);
   157         -}
   158         -
   159         -__declspec(dllexport) void __stdcall sqlite3_sleep_interop(int milliseconds)
   160         -{
   161         -  Sleep(milliseconds);
   162         -}
   163         -
   164         -__declspec(dllexport) int sqlite3_encryptfile(const wchar_t *pwszFilename)
   165         -{
   166         -  HMODULE hMod = LoadLibrary(_T("ADVAPI32"));
   167         -  ENCRYPTFILEW pfunc;
   168         -  int n;
   169         -
   170         -  if (hMod == NULL)
   171         -  {
   172         -    SetLastError(ERROR_NOT_SUPPORTED);
   173         -    return 0;
   174         -  }
   175         -  
   176         -  pfunc = (ENCRYPTFILEW)GetProcAddress(hMod, _T("EncryptFileW"));
   177         -  if (pfunc == NULL)
   178         -  {
   179         -    SetLastError(ERROR_NOT_SUPPORTED);
   180         -    return 0;
   181         -  }
   182         -
   183         -  n = pfunc(pwszFilename);
   184         -
   185         -  FreeLibrary(hMod);
   186         -
   187         -  return n;
   188         -}
   189         -
   190         -__declspec(dllexport) int sqlite3_decryptfile(const wchar_t *pwszFilename)
   191         -{
   192         -  HMODULE hMod = LoadLibrary(_T("ADVAPI32"));
   193         -  DECRYPTFILEW pfunc;
   194         -  int n;
   195         -
   196         -  if (hMod == NULL)
   197         -  {
   198         -    SetLastError(ERROR_NOT_SUPPORTED);
   199         -    return 0;
   200         -  }
   201         -
   202         -  pfunc = (DECRYPTFILEW)GetProcAddress(hMod, _T("DecryptFileW"));
   203         -  if (pfunc == NULL)
   204         -  {
   205         -    SetLastError(ERROR_NOT_SUPPORTED);
   206         -    return 0;
   207         -  }
   208         -
   209         -  n = pfunc(pwszFilename, 0);
   210         -
   211         -  FreeLibrary(hMod);
   212         -
   213         -  return n;
   214         -}
   215         -
   216         -__declspec(dllexport) unsigned long sqlite3_encryptedstatus(const wchar_t *pwszFilename, unsigned long *pdwStatus)
   217         -{
   218         -  HMODULE hMod = LoadLibrary(_T("ADVAPI32"));
   219         -  ENCRYPTEDSTATUSW pfunc;
   220         -  int n;
   221         -
   222         -  if (hMod == NULL)
   223         -  {
   224         -    SetLastError(ERROR_NOT_SUPPORTED);
   225         -    return 0;
   226         -  }
   227         -
   228         -  pfunc = (ENCRYPTEDSTATUSW)GetProcAddress(hMod, _T("FileEncryptionStatusW"));
   229         -  if (pfunc == NULL)
   230         -  {
   231         -    SetLastError(ERROR_NOT_SUPPORTED);
   232         -    return 0;
   233         -  }
   234         -
   235         -  n = pfunc(pwszFilename, pdwStatus);
   236         -
   237         -  FreeLibrary(hMod);
   238         -
   239         -  return n;
   240         -}
   241         -
   242         -int SetCompression(const wchar_t *pwszFilename, unsigned short ufLevel)
   243         -{
   244         -#ifdef FSCTL_SET_COMPRESSION
   245         -  HMODULE hMod = GetModuleHandle(_T("KERNEL32"));
   246         -  CREATEFILEW pfunc;
   247         -  HANDLE hFile;
   248         -  unsigned long dw = 0;
   249         -  int n;
   250         -
   251         -  if (hMod == NULL)
   252         -  {
   253         -    SetLastError(ERROR_NOT_SUPPORTED);
   254         -    return 0;
   255         -  }
   256         -
   257         -  pfunc = (CREATEFILEW)GetProcAddress(hMod, _T("CreateFileW"));
   258         -  if (pfunc == NULL)
   259         -  {
   260         -    SetLastError(ERROR_NOT_SUPPORTED);
   261         -    return 0;
   262         -  }
   263         -
   264         -  hFile = pfunc(pwszFilename, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
   265         -  if (hFile == NULL)
   266         -    return 0;
   267         -
   268         -  n = DeviceIoControl(hFile, FSCTL_SET_COMPRESSION, &ufLevel, sizeof(ufLevel), NULL, 0, &dw, NULL);
   269         -
   270         -  CloseHandle(hFile);
   271         -
   272         -  return n;
   273         -#else
   274         -  SetLastError(ERROR_NOT_SUPPORTED);
   275         -  return 0;
   276         -#endif
   277         -}
   278         -
   279         -__declspec(dllexport) int __stdcall sqlite3_compressfile(const wchar_t *pwszFilename)
   280         -{
   281         -  return SetCompression(pwszFilename, COMPRESSION_FORMAT_DEFAULT);
   282         -}
   283         -
   284         -__declspec(dllexport) int __stdcall sqlite3_decompressfile(const wchar_t *pwszFilename)
   285         -{
   286         -  return SetCompression(pwszFilename, COMPRESSION_FORMAT_NONE);
   287         -}
   288         -
   289         -__declspec(dllexport) void __stdcall sqlite3_function_free_callbackcookie(void *pCookie)
   290         -{
   291         -  if (pCookie)
   292         -    free(pCookie);
   293         -}
   294         -
   295         -// sqlite3 wrappers
   296         -__declspec(dllexport) const char * __stdcall sqlite3_libversion_interop(int *plen)
   297         -{
   298         -  const char *val = sqlite3_libversion();
   299         -  *plen = (val != 0) ? strlen(val) : 0;
   300         -
   301         -  return val;
   302         -}
   303         -
   304         -__declspec(dllexport) int __stdcall sqlite3_libversion_number_interop(void)
   305         -{
   306         -  return sqlite3_libversion_number();
   307         -}
   308         -
   309         -__declspec(dllexport) int __stdcall sqlite3_close_interop(sqlite3 *db)
   310         -{
   311         -  return sqlite3_close(db);
   312         -}
   313         -
   314         -__declspec(dllexport) int __stdcall sqlite3_exec_interop(sqlite3 *db, const char *sql, sqlite3_callback cb, void *pv, char **errmsg, int *plen)
   315         -{
   316         -  int n = sqlite3_exec(db, sql, cb, pv, errmsg);
   317         -  *plen = (*errmsg != 0) ? strlen(*errmsg) : 0;
   318         -  return n;
   319         -}
   320         -
   321         -__declspec(dllexport) sqlite_int64 __stdcall sqlite3_last_insert_rowid_interop(sqlite3 *db)
   322         -{
   323         -  return sqlite3_last_insert_rowid(db);
   324         -}
   325         -
   326         -__declspec(dllexport) int __stdcall sqlite3_changes_interop(sqlite3 *db)
   327         -{
   328         -  return sqlite3_changes(db);
   329         -}
   330         -
   331         -__declspec(dllexport) int __stdcall sqlite3_total_changes_interop(sqlite3 *db)
   332         -{
   333         -  return sqlite3_total_changes(db);
   334         -}
   335         -
   336         -__declspec(dllexport) void __stdcall sqlite3_interrupt_interop(sqlite3 *db)
   337         -{
   338         -  sqlite3_interrupt(db);
   339         -}
   340         -
   341         -__declspec(dllexport) int __stdcall sqlite3_complete_interop(const char *sql)
   342         -{
   343         -  return sqlite3_complete(sql);
   344         -}
   345         -
   346         -__declspec(dllexport) int __stdcall sqlite3_complete16_interop(const void *sql)
   347         -{
   348         -  return sqlite3_complete16(sql);
   349         -}
   350         -
   351         -__declspec(dllexport) int __stdcall sqlite3_busy_handler_interop(sqlite3 *db, int(*cb)(void *, int), void *pv)
   352         -{
   353         -  return sqlite3_busy_handler(db, cb, pv);
   354         -}
   355         -
   356         -__declspec(dllexport) int __stdcall sqlite3_busy_timeout_interop(sqlite3 *db, int ms)
   357         -{
   358         -  return sqlite3_busy_timeout(db, ms);
   359         -}
   360         -
   361         -__declspec(dllexport) int __stdcall sqlite3_get_table_interop(sqlite3 *db, const char *sql, char ***resultp, int *nrow, int *ncolumn, char **errmsg, int *plen)
   362         -{
   363         -  int n = sqlite3_get_table(db, sql, resultp, nrow, ncolumn, errmsg);
   364         -  *plen = (*errmsg != 0) ? strlen((char *)*errmsg) : 0;
   365         -  return n;
   366         -}
   367         -
   368         -__declspec(dllexport) void __stdcall sqlite3_free_table_interop(char **result)
   369         -{
   370         -  sqlite3_free_table(result);
   371         -}
   372         -
   373         -__declspec(dllexport) void __stdcall sqlite3_free_interop(char *z)
   374         -{
   375         -  sqlite3_free(z);
   376         -}
   377         -
   378         -__declspec(dllexport) int __stdcall sqlite3_open_interop(const char*filename, sqlite3 **ppdb)
   379         -{
   380         -  return sqlite3_open(filename, ppdb);
   381         -}
   382         -
   383         -__declspec(dllexport) int __stdcall sqlite3_open16_interop(const void *filename, sqlite3 **ppdb)
   384         -{
   385         -  return sqlite3_open16(filename, ppdb);
   386         -}
   387         -
   388         -__declspec(dllexport) int __stdcall sqlite3_errcode_interop(sqlite3 *db)
   389         -{
   390         -  return sqlite3_errcode(db);
   391         -}
   392         -
   393         -__declspec(dllexport) const char * __stdcall sqlite3_errmsg_interop(sqlite3 *db, int *plen)
   394         -{
   395         -  const char *pval = sqlite3_errmsg(db);
   396         -  *plen = (pval != 0) ? strlen(pval) : 0;
   397         -  return pval;
   398         -}
   399         -
   400         -__declspec(dllexport) const void * __stdcall sqlite3_errmsg16_interop(sqlite3 *db, int *plen)
   401         -{
   402         -  const void *pval = sqlite3_errmsg16(db);
   403         -  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t): 0;
   404         -  return pval;
   405         -}
   406         -
   407         -__declspec(dllexport) int __stdcall sqlite3_prepare_interop(sqlite3 *db, const char *sql, int nbytes, sqlite3_stmt **ppstmt, const char **pztail, int *plen)
   408         -{
   409         -  int n = sqlite3_prepare(db, sql, nbytes, ppstmt, pztail);
   410         -  *plen = (*pztail != 0) ? strlen(*pztail) : 0;
   411         -  return n;
   412         -}
   413         -
   414         -__declspec(dllexport) int __stdcall sqlite3_prepare16_interop(sqlite3 *db, const void *sql, int nbytes, sqlite3_stmt **ppstmt, const void **pztail, int *plen)
   415         -{
   416         -  int n = sqlite3_prepare16(db, sql, nbytes, ppstmt, pztail);
   417         -  *plen = (*pztail != 0) ? wcslen((wchar_t *)*pztail) * sizeof(wchar_t) : 0;
   418         -  return n;
   419         -}
   420         -
   421         -__declspec(dllexport) int __stdcall sqlite3_bind_blob_interop(sqlite3_stmt *stmt, int iCol, const void *pv, int n, void(*cb)(void*))
   422         -{
   423         -  return sqlite3_bind_blob(stmt, iCol, pv, n, cb);
   424         -}
   425         -
   426         -__declspec(dllexport) int __stdcall sqlite3_bind_double_interop(sqlite3_stmt *stmt, int iCol, double *val)
   427         -{
   428         -	return sqlite3_bind_double(stmt,iCol,*val);
   429         -}
   430         -
   431         -__declspec(dllexport) int __stdcall sqlite3_bind_int_interop(sqlite3_stmt *stmt, int iCol, int val)
   432         -{
   433         -  return sqlite3_bind_int(stmt, iCol, val);
   434         -}
   435         -
   436         -__declspec(dllexport) int __stdcall sqlite3_bind_int64_interop(sqlite3_stmt *stmt, int iCol, sqlite_int64 *val)
   437         -{
   438         -	return sqlite3_bind_int64(stmt,iCol,*val);
   439         -}
   440         -
   441         -__declspec(dllexport) int __stdcall sqlite3_bind_null_interop(sqlite3_stmt *stmt, int iCol)
   442         -{
   443         -  return sqlite3_bind_null(stmt, iCol);
   444         -}
   445         -
   446         -__declspec(dllexport) int __stdcall sqlite3_bind_text_interop(sqlite3_stmt *stmt, int iCol, const char *val, int n, void(*cb)(void *))
   447         -{
   448         -  return sqlite3_bind_text(stmt, iCol, val, n, cb);
   449         -}
   450         -
   451         -__declspec(dllexport) int __stdcall sqlite3_bind_text16_interop(sqlite3_stmt *stmt, int iCol, const void *val, int n, void(*cb)(void *))
   452         -{
   453         -  return sqlite3_bind_text16(stmt, iCol, val, n, cb);
   454         -}
   455         -
   456         -__declspec(dllexport) int __stdcall sqlite3_bind_parameter_count_interop(sqlite3_stmt *stmt)
   457         -{
   458         -  return sqlite3_bind_parameter_count(stmt);
   459         -}
   460         -
   461         -__declspec(dllexport) const char * __stdcall sqlite3_bind_parameter_name_interop(sqlite3_stmt *stmt, int iCol, int *plen)
   462         -{
   463         -  const char *pval = sqlite3_bind_parameter_name(stmt, iCol);
   464         -  *plen = (pval != 0) ? strlen(pval) : 0;
   465         -  return pval;
   466         -}
   467         -
   468         -__declspec(dllexport) int __stdcall sqlite3_bind_parameter_index_interop(sqlite3_stmt *stmt, const char *zName)
   469         -{
   470         -  return sqlite3_bind_parameter_index(stmt, zName);
   471         -}
   472         -
   473         -__declspec(dllexport) int __stdcall sqlite3_column_count_interop(sqlite3_stmt *stmt)
   474         -{
   475         -  return sqlite3_column_count(stmt);
   476         -}
   477         -
   478         -__declspec(dllexport) const char * __stdcall sqlite3_column_name_interop(sqlite3_stmt *stmt, int iCol, int *plen)
   479         -{
   480         -  const char *pval = sqlite3_column_name(stmt, iCol);
   481         -  *plen = (pval != 0) ? strlen(pval) : 0;
   482         -  return pval;
   483         -}
   484         -
   485         -__declspec(dllexport) const void * __stdcall sqlite3_column_name16_interop(sqlite3_stmt *stmt, int iCol, int *plen)
   486         -{
   487         -  const void *pval = sqlite3_column_name16(stmt, iCol);
   488         -  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t) : 0;
   489         -  return pval;
   490         -}
   491         -
   492         -__declspec(dllexport) const char * __stdcall sqlite3_column_decltype_interop(sqlite3_stmt *stmt, int iCol, int *plen)
   493         -{
   494         -  const char *pval = sqlite3_column_decltype(stmt, iCol);
   495         -  *plen = (pval != 0) ? strlen(pval) : 0;
   496         -  return pval;
   497         -}
   498         -
   499         -__declspec(dllexport) const void * __stdcall sqlite3_column_decltype16_interop(sqlite3_stmt *stmt, int iCol, int *plen)
   500         -{
   501         -  const void *pval = sqlite3_column_decltype16(stmt, iCol);
   502         -  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t) : 0;
   503         -  return pval;
   504         -}
   505         -
   506         -__declspec(dllexport) int __stdcall sqlite3_step_interop(sqlite3_stmt *stmt)
   507         -{
   508         -  return sqlite3_step(stmt);
   509         -}
   510         -
   511         -__declspec(dllexport) int __stdcall sqlite3_data_count_interop(sqlite3_stmt *stmt)
   512         -{
   513         -  return sqlite3_data_count(stmt);
   514         -}
   515         -
   516         -__declspec(dllexport) const void * __stdcall sqlite3_column_blob_interop(sqlite3_stmt *stmt, int iCol)
   517         -{
   518         -  return sqlite3_column_blob(stmt, iCol);
   519         -}
   520         -
   521         -__declspec(dllexport) int __stdcall sqlite3_column_bytes_interop(sqlite3_stmt *stmt, int iCol)
   522         -{
   523         -  return sqlite3_column_bytes(stmt, iCol);
   524         -}
   525         -
   526         -__declspec(dllexport) int __stdcall sqlite3_column_bytes16_interop(sqlite3_stmt *stmt, int iCol)
   527         -{
   528         -  return sqlite3_column_bytes16(stmt, iCol);
   529         -}
   530         -
   531         -__declspec(dllexport) void __stdcall sqlite3_column_double_interop(sqlite3_stmt *stmt, int iCol, double *val)
   532         -{
   533         -	*val = sqlite3_column_double(stmt,iCol);
   534         -}
   535         -
   536         -__declspec(dllexport) int __stdcall sqlite3_column_int_interop(sqlite3_stmt *stmt, int iCol)
   537         -{
   538         -  return sqlite3_column_int(stmt, iCol);
   539         -}
   540         -
   541         -__declspec(dllexport) void __stdcall sqlite3_column_int64_interop(sqlite3_stmt *stmt, int iCol, sqlite_int64 *val)
   542         -{
   543         -	*val = sqlite3_column_int64(stmt,iCol);
   544         -}
   545         -
   546         -__declspec(dllexport) const unsigned char * __stdcall sqlite3_column_text_interop(sqlite3_stmt *stmt, int iCol, int *plen)
   547         -{
   548         -  const unsigned char *pval = sqlite3_column_text(stmt, iCol);
   549         -  *plen = (pval != 0) ? strlen((char *)pval) : 0;
   550         -  return pval;
   551         -}
   552         -
   553         -__declspec(dllexport) const void * __stdcall sqlite3_column_text16_interop(sqlite3_stmt *stmt, int iCol, int *plen)
   554         -{
   555         -  const void *pval = sqlite3_column_text16(stmt, iCol);
   556         -  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t): 0;
   557         -  return pval;
   558         -}
   559         -
   560         -__declspec(dllexport) int __stdcall sqlite3_column_type_interop(sqlite3_stmt *stmt, int iCol)
   561         -{
   562         -  return sqlite3_column_type(stmt, iCol);
   563         -}
   564         -
   565         -__declspec(dllexport) int __stdcall sqlite3_finalize_interop(sqlite3_stmt *stmt)
   566         -{
   567         -  return sqlite3_finalize(stmt);
   568         -}
   569         -
   570         -__declspec(dllexport) int __stdcall sqlite3_reset_interop(sqlite3_stmt *stmt)
   571         -{
   572         -  return sqlite3_reset(stmt);
   573         -}
   574         -
   575         -__declspec(dllexport) int __stdcall sqlite3_create_function_interop(sqlite3 *psql, const char *zFunctionName, int nArg, int eTextRep, SQLITEUSERFUNC func, SQLITEUSERFUNC funcstep, SQLITEUSERFUNC funcfinal, void **ppCookie)
   576         -{
   577         -  int n;
   578         -  SQLITEUSERFUNC *p = (SQLITEUSERFUNC *)malloc(sizeof(SQLITEUSERFUNC) * 3);
   579         -
   580         -  p[0] = func;
   581         -  p[1] = funcstep;
   582         -  p[2] = funcfinal;
   583         -
   584         -  *ppCookie = 0;
   585         -
   586         -  n = sqlite3_create_function(psql, zFunctionName, nArg, eTextRep, p, (func != 0) ? sqlite3_interop_func : 0, (funcstep != 0) ? sqlite3_interop_step : 0, (funcfinal != 0) ? sqlite3_interop_final : 0);
   587         -  if (n != 0)
   588         -    free(p);
   589         -  else
   590         -    *ppCookie = p;
   591         -
   592         -  return n;
   593         -}
   594         -
   595         -__declspec(dllexport) int __stdcall sqlite3_create_function16_interop(sqlite3 *psql, void *zFunctionName, int nArg, int eTextRep, SQLITEUSERFUNC func, SQLITEUSERFUNC funcstep, SQLITEUSERFUNC funcfinal, void **ppCookie)
   596         -{
   597         -  int n;
   598         -  SQLITEUSERFUNC *p = (SQLITEUSERFUNC *)malloc(sizeof(SQLITEUSERFUNC) * 3);
   599         -
   600         -  p[0] = func;
   601         -  p[1] = funcstep;
   602         -  p[2] = funcfinal;
   603         -
   604         -  *ppCookie = 0;
   605         -
   606         -  n = sqlite3_create_function16(psql, zFunctionName, nArg, eTextRep, p, (func != 0) ? sqlite3_interop_func : 0, (funcstep != 0) ? sqlite3_interop_step : 0, (funcfinal != 0) ? sqlite3_interop_final : 0);
   607         -  if (n != 0)
   608         -    free(p);
   609         -  else
   610         -    *ppCookie = p;
   611         -
   612         -  return n;
   613         -}
   614         -
   615         -__declspec(dllexport) int __stdcall sqlite3_create_collation_interop(sqlite3* db, const char *zName, int eTextRep, void* pvUser, SQLITECOLLATION func, void **ppCookie)
   616         -{
   617         -  int n;
   618         -  SQLITECOLLATION *p = (SQLITECOLLATION *)malloc(sizeof(SQLITECOLLATION));
   619         -  
   620         -  p[0] = func;
   621         -
   622         -  *ppCookie = 0;
   623         -
   624         -  n = sqlite3_create_collation(db, zName, eTextRep, p, sqlite3_interop_collationfunc);
   625         -  if (n != 0)
   626         -    free(p);
   627         -  else
   628         -    *ppCookie = p;
   629         -
   630         -  return n;
   631         -}
   632         -
   633         -__declspec(dllexport) int __stdcall sqlite3_create_collation16_interop(sqlite3* db, const void *zName, int eTextRep, void* pvUser, SQLITECOLLATION func, void **ppCookie)
   634         -{
   635         -  int n;
   636         -  SQLITECOLLATION *p = (SQLITECOLLATION *)malloc(sizeof(SQLITECOLLATION));
   637         -  
   638         -  p[0] = func;
   639         -
   640         -  *ppCookie = 0;
   641         -
   642         -  n = sqlite3_create_collation16(db, (const char *)zName, eTextRep, p, sqlite3_interop_collationfunc);
   643         -  if (n != 0)
   644         -    free(p);
   645         -  else
   646         -    *ppCookie = p;
   647         -
   648         -  return n;
   649         -}
   650         -
   651         -__declspec(dllexport) int __stdcall sqlite3_aggregate_count_interop(sqlite3_context *pctx)
   652         -{
   653         -  return sqlite3_aggregate_count(pctx);
   654         -}
   655         -
   656         -__declspec(dllexport) const void * __stdcall sqlite3_value_blob_interop(sqlite3_value *val)
   657         -{
   658         -  return sqlite3_value_blob(val);
   659         -}
   660         -
   661         -__declspec(dllexport) int __stdcall sqlite3_value_bytes_interop(sqlite3_value *val)
   662         -{
   663         -  return sqlite3_value_bytes(val);
   664         -}
   665         -
   666         -__declspec(dllexport) int __stdcall sqlite3_value_bytes16_interop(sqlite3_value *val)
   667         -{
   668         -  return sqlite3_value_bytes16(val);
   669         -}
   670         -
   671         -__declspec(dllexport) void __stdcall sqlite3_value_double_interop(sqlite3_value *pval, double *val)
   672         -{
   673         -  *val = sqlite3_value_double(pval);
   674         -}
   675         -
   676         -__declspec(dllexport) int __stdcall sqlite3_value_int_interop(sqlite3_value *val)
   677         -{
   678         -  return sqlite3_value_int(val);
   679         -}
   680         -
   681         -__declspec(dllexport) void __stdcall sqlite3_value_int64_interop(sqlite3_value *pval, sqlite_int64 *val)
   682         -{
   683         -  *val = sqlite3_value_int64(pval);
   684         -}
   685         -
   686         -__declspec(dllexport) const unsigned char * __stdcall sqlite3_value_text_interop(sqlite3_value *val, int *plen)
   687         -{
   688         -  const unsigned char *pval = sqlite3_value_text(val);
   689         -  *plen = (pval != 0) ? strlen((char *)pval) : 0;
   690         -  return pval;
   691         -}
   692         -
   693         -__declspec(dllexport) const void * __stdcall sqlite3_value_text16_interop(sqlite3_value *val, int *plen)
   694         -{
   695         -  const void *pval = sqlite3_value_text16(val);
   696         -  *plen = (pval != 0) ? wcslen((wchar_t *)pval) * sizeof(wchar_t) : 0;
   697         -  return pval;
   698         -}
   699         -
   700         -__declspec(dllexport) int __stdcall sqlite3_value_type_interop(sqlite3_value *val)
   701         -{
   702         -  return sqlite3_value_type(val);
   703         -}
   704         -
   705         -__declspec(dllexport) void * __stdcall sqlite3_aggregate_context_interop(sqlite3_context *pctx, int n)
   706         -{
   707         -  return sqlite3_aggregate_context(pctx, n);
   708         -}
   709         -
   710         -__declspec(dllexport) void __stdcall sqlite3_result_blob_interop(sqlite3_context *ctx, const void *pv, int n, void(*cb)(void *))
   711         -{
   712         -  sqlite3_result_blob(ctx, pv, n, cb);
   713         -}
   714         -
   715         -__declspec(dllexport) void __stdcall sqlite3_result_double_interop(sqlite3_context *pctx, double *val)
   716         -{
   717         -  sqlite3_result_double(pctx, *val);
   718         -}
   719         -
   720         -__declspec(dllexport) void __stdcall sqlite3_result_int_interop(sqlite3_context *pctx, int val)
   721         -{
   722         -  sqlite3_result_int(pctx, val);
   723         -}
   724         -
   725         -__declspec(dllexport) void __stdcall sqlite3_result_int64_interop(sqlite3_context *pctx, sqlite_int64 *val)
   726         -{
   727         -  sqlite3_result_int64(pctx, *val);
   728         -}
   729         -
   730         -__declspec(dllexport) void __stdcall sqlite3_result_null_interop(sqlite3_context *pctx)
   731         -{
   732         -  sqlite3_result_null(pctx);
   733         -}
   734         -
   735         -__declspec(dllexport) void __stdcall sqlite3_result_error_interop(sqlite3_context *ctx, const char *pv, int n)
   736         -{
   737         -  sqlite3_result_error(ctx, pv, n);
   738         -}
   739         -
   740         -__declspec(dllexport) void __stdcall sqlite3_result_error16_interop(sqlite3_context *ctx, const void *pv, int n)
   741         -{
   742         -  sqlite3_result_error16(ctx, pv, n);
   743         -}
   744         -
   745         -__declspec(dllexport) void __stdcall sqlite3_result_text_interop(sqlite3_context *ctx, const char *pv, int n, void(*cb)(void *))
   746         -{
   747         -  sqlite3_result_text(ctx, pv, n, cb);
   748         -}
   749         -
   750         -__declspec(dllexport) void __stdcall sqlite3_result_text16_interop(sqlite3_context *ctx, const void *pv, int n, void(*cb)(void *))
   751         -{
   752         -  sqlite3_result_text16(ctx, pv, n, cb);
   753         -}
   754         -
   755         -__declspec(dllexport) void __stdcall sqlite3_realcolnames(sqlite3 *db, int bOn)
   756         -{
   757         -  if (bOn)
   758         -    db->flags |= 0x01000000;
   759         -  else
   760         -    db->flags &= (~0x01000000);
   761         -}
   762         -
   763         -#endif // OS_WIN

Changes to SQLite.Interop/src/alter.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains C code routines that used to generate VDBE code
    13     13   ** that implements the ALTER TABLE command.
    14     14   **
    15         -** $Id: alter.c,v 1.10 2005/12/19 17:57:46 rmsimpson Exp $
           15  +** $Id: alter.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   #include <ctype.h>
    19     19   
    20     20   /*
    21     21   ** The code in this file only exists if we are not omitting the
    22     22   ** ALTER TABLE logic from the build.
................................................................................
    43     43     sqlite3_value **argv
    44     44   ){
    45     45     unsigned char const *zSql = sqlite3_value_text(argv[0]);
    46     46     unsigned char const *zTableName = sqlite3_value_text(argv[1]);
    47     47   
    48     48     int token;
    49     49     Token tname;
    50         -  char const *zCsr = zSql;
           50  +  unsigned char const *zCsr = zSql;
    51     51     int len = 0;
    52     52     char *zRet;
    53     53   
    54     54     /* The principle used to locate the table name in the CREATE TABLE 
    55     55     ** statement is that the table name is the first token that is immediatedly
    56     56     ** followed by a left parenthesis - TK_LP.
    57     57     */
................................................................................
    92     92   ){
    93     93     unsigned char const *zSql = sqlite3_value_text(argv[0]);
    94     94     unsigned char const *zTableName = sqlite3_value_text(argv[1]);
    95     95   
    96     96     int token;
    97     97     Token tname;
    98     98     int dist = 3;
    99         -  char const *zCsr = zSql;
           99  +  unsigned char const *zCsr = zSql;
   100    100     int len = 0;
   101    101     char *zRet;
   102    102   
   103    103     /* The principle used to locate the table name in the CREATE TRIGGER 
   104    104     ** statement is that the table name is the first token that is immediatedly
   105    105     ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
   106    106     ** of TK_WHEN, TK_BEGIN or TK_FOR.
................................................................................
   173    173   ** table pTab has no temporary triggers, or is itself stored in the 
   174    174   ** temporary database, NULL is returned.
   175    175   */
   176    176   static char *whereTempTriggers(Parse *pParse, Table *pTab){
   177    177     Trigger *pTrig;
   178    178     char *zWhere = 0;
   179    179     char *tmp = 0;
   180         -  if( pTab->iDb!=1 ){
          180  +  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
          181  +
          182  +  /* If the table is not located in the temp-db (in which case NULL is 
          183  +  ** returned, loop through the tables list of triggers. For each trigger
          184  +  ** that is not part of the temp-db schema, add a clause to the WHERE 
          185  +  ** expression being built up in zWhere.
          186  +  */
          187  +  if( pTab->pSchema!=pTempSchema ){
   181    188       for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
   182         -      if( pTrig->iDb==1 ){
          189  +      if( pTrig->pSchema==pTempSchema ){
   183    190           if( !zWhere ){
   184    191             zWhere = sqlite3MPrintf("name=%Q", pTrig->name);
   185    192           }else{
   186    193             tmp = zWhere;
   187    194             zWhere = sqlite3MPrintf("%s OR name=%Q", zWhere, pTrig->name);
   188    195             sqliteFree(tmp);
   189    196           }
................................................................................
   200    207   ** the time the generated code is executed. This can be different from
   201    208   ** pTab->zName if this function is being called to code part of an 
   202    209   ** "ALTER TABLE RENAME TO" statement.
   203    210   */
   204    211   static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
   205    212     Vdbe *v;
   206    213     char *zWhere;
   207         -  int iDb;
          214  +  int iDb;                   /* Index of database containing pTab */
   208    215   #ifndef SQLITE_OMIT_TRIGGER
   209    216     Trigger *pTrig;
   210    217   #endif
   211    218   
   212    219     v = sqlite3GetVdbe(pParse);
   213    220     if( !v ) return;
   214         -  iDb = pTab->iDb;
          221  +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
          222  +  assert( iDb>=0 );
   215    223   
   216    224   #ifndef SQLITE_OMIT_TRIGGER
   217    225     /* Drop any table triggers from the internal schema. */
   218    226     for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
   219         -    assert( pTrig->iDb==iDb || pTrig->iDb==1 );
   220         -    sqlite3VdbeOp3(v, OP_DropTrigger, pTrig->iDb, 0, pTrig->name, 0);
          227  +    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
          228  +    assert( iTrigDb==iDb || iTrigDb==1 );
          229  +    sqlite3VdbeOp3(v, OP_DropTrigger, iTrigDb, 0, pTrig->name, 0);
   221    230     }
   222    231   #endif
   223    232   
   224    233     /* Drop the table and index from the internal schema */
   225    234     sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
   226    235   
   227    236     /* Reload the table, index and permanent trigger schemas. */
................................................................................
   229    238     if( !zWhere ) return;
   230    239     sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC);
   231    240   
   232    241   #ifndef SQLITE_OMIT_TRIGGER
   233    242     /* Now, if the table is not stored in the temp database, reload any temp 
   234    243     ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
   235    244     */
   236         -  if( (zWhere=whereTempTriggers(pParse, pTab)) ){
          245  +  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   237    246       sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC);
   238    247     }
   239    248   #endif
   240    249   }
   241    250   
   242    251   /*
   243    252   ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
................................................................................
   254    263     char *zName = 0;          /* NULL-terminated version of pName */ 
   255    264     sqlite3 *db = pParse->db; /* Database connection */
   256    265     Vdbe *v;
   257    266   #ifndef SQLITE_OMIT_TRIGGER
   258    267     char *zWhere = 0;         /* Where clause to locate temp triggers */
   259    268   #endif
   260    269     
   261         -  if( sqlite3_malloc_failed ) goto exit_rename_table;
          270  +  if( sqlite3ThreadData()->mallocFailed ) goto exit_rename_table;
   262    271     assert( pSrc->nSrc==1 );
   263    272   
   264    273     pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   265    274     if( !pTab ) goto exit_rename_table;
   266         -  iDb = pTab->iDb;
          275  +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   267    276     zDb = db->aDb[iDb].zName;
   268    277   
   269    278     /* Get a NULL terminated version of the new table name. */
   270    279     zName = sqlite3NameFromToken(pName);
   271    280     if( !zName ) goto exit_rename_table;
   272    281   
   273    282     /* Check that a table or index named 'zName' does not already exist
................................................................................
   345    354   #endif
   346    355   
   347    356   #ifndef SQLITE_OMIT_TRIGGER
   348    357     /* If there are TEMP triggers on this table, modify the sqlite_temp_master
   349    358     ** table. Don't do this if the table being ALTERed is itself located in
   350    359     ** the temp database.
   351    360     */
   352         -  if( (zWhere=whereTempTriggers(pParse, pTab)) ){
          361  +  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   353    362       sqlite3NestedParse(pParse, 
   354    363           "UPDATE sqlite_temp_master SET "
   355    364               "sql = sqlite_rename_trigger(sql, %Q), "
   356    365               "tbl_name = %Q "
   357    366               "WHERE %s;", zName, zName, zWhere);
   358    367       sqliteFree(zWhere);
   359    368     }
................................................................................
   381    390     Table *pTab;              /* Table being altered */
   382    391     int iDb;                  /* Database number */
   383    392     const char *zDb;          /* Database name */
   384    393     const char *zTab;         /* Table name */
   385    394     char *zCol;               /* Null-terminated column definition */
   386    395     Column *pCol;             /* The new column */
   387    396     Expr *pDflt;              /* Default value for the new column */
   388         -  Vdbe *v;
   389    397   
   390    398     if( pParse->nErr ) return;
   391    399     pNew = pParse->pNewTable;
   392    400     assert( pNew );
   393    401   
   394         -  iDb = pNew->iDb;
          402  +  iDb = sqlite3SchemaToIndex(pParse->db, pNew->pSchema);
   395    403     zDb = pParse->db->aDb[iDb].zName;
   396    404     zTab = pNew->zName;
   397    405     pCol = &pNew->aCol[pNew->nCol-1];
   398    406     pDflt = pCol->pDflt;
   399    407     pTab = sqlite3FindTable(pParse->db, zTab, zDb);
   400    408     assert( pTab );
   401    409   
................................................................................
   438    446         sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
   439    447         return;
   440    448       }
   441    449       sqlite3ValueFree(pVal);
   442    450     }
   443    451   
   444    452     /* Modify the CREATE TABLE statement. */
   445         -  zCol = sqliteStrNDup(pColDef->z, pColDef->n);
          453  +  zCol = sqliteStrNDup((char*)pColDef->z, pColDef->n);
   446    454     if( zCol ){
   447    455       char *zEnd = &zCol[pColDef->n-1];
   448    456       while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
   449    457         *zEnd-- = '\0';
   450    458       }
   451    459       sqlite3NestedParse(pParse, 
   452    460           "UPDATE %Q.%s SET "
................................................................................
   458    466       sqliteFree(zCol);
   459    467     }
   460    468   
   461    469     /* If the default value of the new column is NULL, then set the file
   462    470     ** format to 2. If the default value of the new column is not NULL,
   463    471     ** the file format becomes 3.
   464    472     */
   465         -  if( (v=sqlite3GetVdbe(pParse)) ){
   466         -    int f = (pDflt?3:2);
   467         -
   468         -    /* Only set the file format to $f if it is currently less than $f. */
   469         -    sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
   470         -    sqlite3VdbeAddOp(v, OP_Integer, f, 0);
   471         -    sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
   472         -    sqlite3VdbeAddOp(v, OP_Integer, f, 0);
   473         -    sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
   474         -  }
          473  +  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
   475    474   
   476    475     /* Reload the schema of the modified table. */
   477    476     reloadTableSchema(pParse, pTab, pTab->zName);
   478    477   }
   479         -
   480    478   
   481    479   /*
   482    480   ** This function is called by the parser after the table-name in
   483    481   ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
   484    482   ** pSrc is the full-name of the table being altered.
   485    483   **
   486    484   ** This routine makes a (partial) copy of the Table structure
................................................................................
   497    495     Table *pNew;
   498    496     Table *pTab;
   499    497     Vdbe *v;
   500    498     int iDb;
   501    499     int i;
   502    500     int nAlloc;
   503    501   
   504         -
   505    502     /* Look up the table being altered. */
   506    503     assert( pParse->pNewTable==0 );
   507         -  if( sqlite3_malloc_failed ) goto exit_begin_add_column;
          504  +  if( sqlite3ThreadData()->mallocFailed ) goto exit_begin_add_column;
   508    505     pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   509    506     if( !pTab ) goto exit_begin_add_column;
   510    507   
   511    508     /* Make sure this is not an attempt to ALTER a view. */
   512    509     if( pTab->pSelect ){
   513    510       sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
   514    511       goto exit_begin_add_column;
   515    512     }
   516    513   
   517    514     assert( pTab->addColOffset>0 );
   518         -  iDb = pTab->iDb;
          515  +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   519    516   
   520    517     /* Put a copy of the Table struct in Parse.pNewTable for the
   521    518     ** sqlite3AddColumn() function and friends to modify.
   522    519     */
   523    520     pNew = (Table *)sqliteMalloc(sizeof(Table));
   524    521     if( !pNew ) goto exit_begin_add_column;
   525    522     pParse->pNewTable = pNew;
................................................................................
   536    533     memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
   537    534     for(i=0; i<pNew->nCol; i++){
   538    535       Column *pCol = &pNew->aCol[i];
   539    536       pCol->zName = sqliteStrDup(pCol->zName);
   540    537       pCol->zType = 0;
   541    538       pCol->pDflt = 0;
   542    539     }
   543         -  pNew->iDb = iDb;
          540  +  pNew->pSchema = pParse->db->aDb[iDb].pSchema;
   544    541     pNew->addColOffset = pTab->addColOffset;
   545    542     pNew->nRef = 1;
   546    543   
   547    544     /* Begin a transaction and increment the schema cookie.  */
   548    545     sqlite3BeginWriteOperation(pParse, 0, iDb);
   549    546     v = sqlite3GetVdbe(pParse);
   550    547     if( !v ) goto exit_begin_add_column;

Changes to SQLite.Interop/src/analyze.c.

     7      7   **    May you do good and not evil.
     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains code associated with the ANALYZE command.
    13     13   **
    14         -** @(#) $Id: analyze.c,v 1.4 2005/12/19 17:57:46 rmsimpson Exp $
           14  +** @(#) $Id: analyze.c,v 1.5 2006/01/10 18:40:37 rmsimpson Exp $
    15     15   */
    16     16   #ifndef SQLITE_OMIT_ANALYZE
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   /*
    20     20   ** This routine generates code that opens the sqlite_stat1 table on cursor
    21     21   ** iStatCur.
................................................................................
    57     57       iRootPage = pStat->tnum;
    58     58     }else{
    59     59       /* The sqlite_stat1 table already exists.  Delete all rows. */
    60     60       iRootPage = pStat->tnum;
    61     61       sqlite3VdbeAddOp(v, OP_Clear, pStat->tnum, iDb);
    62     62     }
    63     63   
    64         -  /* Open the sqlite_stat1 table for writing.
           64  +  /* Open the sqlite_stat1 table for writing. Unless it was created
           65  +  ** by this vdbe program, lock it for writing at the shared-cache level. 
           66  +  ** If this vdbe did create the sqlite_stat1 table, then it must have 
           67  +  ** already obtained a schema-lock, making the write-lock redundant.
    65     68     */
           69  +  if( iRootPage>0 ){
           70  +    sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
           71  +  }
    66     72     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
    67     73     sqlite3VdbeAddOp(v, OP_OpenWrite, iStatCur, iRootPage);
    68     74     sqlite3VdbeAddOp(v, OP_SetNumColumns, iStatCur, 3);
    69     75   }
    70     76   
    71     77   /*
    72     78   ** Generate code to do an analysis of all indices associated with
................................................................................
    82     88     int iIdxCur;     /* Cursor number for index being analyzed */
    83     89     int nCol;        /* Number of columns in the index */
    84     90     Vdbe *v;         /* The virtual machine being built up */
    85     91     int i;           /* Loop counter */
    86     92     int topOfLoop;   /* The top of the loop */
    87     93     int endOfLoop;   /* The end of the loop */
    88     94     int addr;        /* The address of an instruction */
           95  +  int iDb;         /* Index of database containing pTab */
    89     96   
    90     97     v = sqlite3GetVdbe(pParse);
    91     98     if( pTab==0 || pTab->pIndex==0 ){
    92     99       /* Do no analysis for tables that have no indices */
    93    100       return;
    94    101     }
    95    102   
          103  +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
          104  +  assert( iDb>=0 );
    96    105   #ifndef SQLITE_OMIT_AUTHORIZATION
    97    106     if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
    98         -      pParse->db->aDb[pTab->iDb].zName ) ){
          107  +      pParse->db->aDb[iDb].zName ) ){
    99    108       return;
   100    109     }
   101    110   #endif
          111  +
          112  +  /* Establish a read-lock on the table at the shared-cache level. */
          113  +  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   102    114   
   103    115     iIdxCur = pParse->nTab;
   104    116     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   105    117       /* Open a cursor to the index to be analyzed
   106    118       */
   107         -    sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
          119  +    assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
          120  +    sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
   108    121       VdbeComment((v, "# %s", pIdx->zName));
   109    122       sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum,
   110    123                        (char*)&pIdx->keyInfo, P3_KEYINFO);
   111    124       nCol = pIdx->nColumn;
   112    125       if( iMem+nCol*2>=pParse->nMem ){
   113    126         pParse->nMem = iMem+nCol*2+1;
   114    127       }
................................................................................
   135    148       }
   136    149   
   137    150       /* Do the analysis.
   138    151       */
   139    152       endOfLoop = sqlite3VdbeMakeLabel(v);
   140    153       sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, endOfLoop);
   141    154       topOfLoop = sqlite3VdbeCurrentAddr(v);
   142         -    sqlite3VdbeAddOp(v, OP_MemIncr, iMem, 0);
          155  +    sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem);
   143    156       for(i=0; i<nCol; i++){
   144    157         sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
   145    158         sqlite3VdbeAddOp(v, OP_MemLoad, iMem+nCol+i+1, 0);
   146    159         sqlite3VdbeAddOp(v, OP_Ne, 0x100, 0);
   147    160       }
   148    161       sqlite3VdbeAddOp(v, OP_Goto, 0, endOfLoop);
   149    162       for(i=0; i<nCol; i++){
   150         -      addr = sqlite3VdbeAddOp(v, OP_MemIncr, iMem+i+1, 0);
          163  +      addr = sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem+i+1);
   151    164         sqlite3VdbeChangeP2(v, topOfLoop + 3*i + 3, addr);
   152    165         sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
   153    166         sqlite3VdbeAddOp(v, OP_MemStore, iMem+nCol+i+1, 1);
   154    167       }
   155    168       sqlite3VdbeResolveLabel(v, endOfLoop);
   156    169       sqlite3VdbeAddOp(v, OP_Next, iIdxCur, topOfLoop);
   157    170       sqlite3VdbeAddOp(v, OP_Close, iIdxCur, 0);
................................................................................
   184    197       for(i=0; i<nCol; i++){
   185    198         sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
   186    199         sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
   187    200         sqlite3VdbeAddOp(v, OP_Add, 0, 0);
   188    201         sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
   189    202         sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
   190    203         sqlite3VdbeAddOp(v, OP_Divide, 0, 0);
          204  +      sqlite3VdbeAddOp(v, OP_ToInt, 0, 0);
   191    205         if( i==nCol-1 ){
   192    206           sqlite3VdbeAddOp(v, OP_Concat, nCol*2-1, 0);
   193    207         }else{
   194    208           sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
   195    209         }
   196    210       }
   197         -    sqlite3VdbeOp3(v, OP_MakeRecord, 3, 0, "ttt", 0);
          211  +    sqlite3VdbeOp3(v, OP_MakeRecord, 3, 0, "aaa", 0);
   198    212       sqlite3VdbeAddOp(v, OP_Insert, iStatCur, 0);
   199    213       sqlite3VdbeJumpHere(v, addr);
   200    214     }
   201    215   }
   202    216   
   203    217   /*
   204    218   ** Generate code that will cause the most recent index analysis to
................................................................................
   210    224   }
   211    225   
   212    226   /*
   213    227   ** Generate code that will do an analysis of an entire database
   214    228   */
   215    229   static void analyzeDatabase(Parse *pParse, int iDb){
   216    230     sqlite3 *db = pParse->db;
          231  +  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
   217    232     HashElem *k;
   218    233     int iStatCur;
   219    234     int iMem;
   220    235   
   221    236     sqlite3BeginWriteOperation(pParse, 0, iDb);
   222    237     iStatCur = pParse->nTab++;
   223    238     openStatTable(pParse, iDb, iStatCur, 0);
   224    239     iMem = pParse->nMem;
   225         -  for(k=sqliteHashFirst(&db->aDb[iDb].tblHash);  k; k=sqliteHashNext(k)){
          240  +  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
   226    241       Table *pTab = (Table*)sqliteHashData(k);
   227    242       analyzeOneTable(pParse, pTab, iStatCur, iMem);
   228    243     }
   229    244     loadAnalysis(pParse, iDb);
   230    245   }
   231    246   
   232    247   /*
................................................................................
   234    249   ** a database.
   235    250   */
   236    251   static void analyzeTable(Parse *pParse, Table *pTab){
   237    252     int iDb;
   238    253     int iStatCur;
   239    254   
   240    255     assert( pTab!=0 );
   241         -  iDb = pTab->iDb;
          256  +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   242    257     sqlite3BeginWriteOperation(pParse, 0, iDb);
   243    258     iStatCur = pParse->nTab++;
   244    259     openStatTable(pParse, iDb, iStatCur, pTab->zName);
   245    260     analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem);
   246    261     loadAnalysis(pParse, iDb);
   247    262   }
   248    263   
................................................................................
   356    371   */
   357    372   void sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   358    373     analysisInfo sInfo;
   359    374     HashElem *i;
   360    375     char *zSql;
   361    376   
   362    377     /* Clear any prior statistics */
   363         -  for(i=sqliteHashFirst(&db->aDb[iDb].idxHash); i; i=sqliteHashNext(i)){
          378  +  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
   364    379       Index *pIdx = sqliteHashData(i);
   365    380       sqlite3DefaultRowEst(pIdx);
   366    381     }
   367    382   
   368    383     /* Check to make sure the sqlite_stat1 table existss */
   369    384     sInfo.db = db;
   370    385     sInfo.zDatabase = db->aDb[iDb].zName;

Changes to SQLite.Interop/src/attach.c.

     7      7   **    May you do good and not evil.
     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains code used to implement the ATTACH and DETACH commands.
    13     13   **
    14         -** $Id: attach.c,v 1.10 2005/12/19 17:57:46 rmsimpson Exp $
           14  +** $Id: attach.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    15     15   */
    16     16   #include "sqliteInt.h"
    17     17   
    18     18   /*
    19         -** This routine is called by the parser to process an ATTACH statement:
           19  +** Resolve an expression that was part of an ATTACH or DETACH statement. This
           20  +** is slightly different from resolving a normal SQL expression, because simple
           21  +** identifiers are treated as strings, not possible column names or aliases.
           22  +**
           23  +** i.e. if the parser sees:
           24  +**
           25  +**     ATTACH DATABASE abc AS def
           26  +**
           27  +** it treats the two expressions as literal strings 'abc' and 'def' instead of
           28  +** looking for columns of the same name.
           29  +**
           30  +** This only applies to the root node of pExpr, so the statement:
           31  +**
           32  +**     ATTACH DATABASE abc||def AS 'db2'
           33  +**
           34  +** will fail because neither abc or def can be resolved.
           35  +*/
           36  +int resolveAttachExpr(NameContext *pName, Expr *pExpr)
           37  +{
           38  +  int rc = SQLITE_OK;
           39  +  if( pExpr ){
           40  +    if( pExpr->op!=TK_ID ){
           41  +      rc = sqlite3ExprResolveNames(pName, pExpr);
           42  +    }else{
           43  +      pExpr->op = TK_STRING;
           44  +    }
           45  +  }
           46  +  return rc;
           47  +}
           48  +
           49  +/*
           50  +** An SQL user-function registered to do the work of an ATTACH statement. The
           51  +** three arguments to the function come directly from an attach statement:
           52  +**
           53  +**     ATTACH DATABASE x AS y KEY z
    20     54   **
    21         -**     ATTACH DATABASE filename AS dbname
           55  +**     SELECT sqlite_attach(x, y, z)
    22     56   **
    23         -** The pFilename and pDbname arguments are the tokens that define the
    24         -** filename and dbname in the ATTACH statement.
           57  +** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
           58  +** third argument.
    25     59   */
    26         -void sqlite3Attach(
    27         -  Parse *pParse,       /* The parser context */
    28         -  Token *pFilename,    /* Name of database file */
    29         -  Token *pDbname,      /* Name of the database to use internally */
    30         -  int keyType,         /* 0: no key.  1: TEXT,  2: BLOB */
    31         -  Token *pKey          /* Text of the key for keytype 1 and 2 */
           60  +static void attachFunc(
           61  +  sqlite3_context *context,
           62  +  int argc,
           63  +  sqlite3_value **argv
    32     64   ){
           65  +  int i;
           66  +  int rc = 0;
           67  +  sqlite3 *db = sqlite3_user_data(context);
           68  +  const char *zName;
           69  +  const char *zFile;
    33     70     Db *aNew;
    34         -  int rc, i;
    35         -  char *zFile = 0;
    36         -  char *zName = 0;
    37         -  sqlite3 *db;
    38         -  Vdbe *v;
           71  +  char zErr[128];
           72  +  char *zErrDyn = 0;
    39     73   
    40         -  v = sqlite3GetVdbe(pParse);
    41         -  if( !v ) return;
    42         -  sqlite3VdbeAddOp(v, OP_Expire, 1, 0);
    43         -  sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
    44         -  if( pParse->explain ) return;
    45         -  db = pParse->db;
           74  +  zFile = (const char *)sqlite3_value_text(argv[0]);
           75  +  zName = (const char *)sqlite3_value_text(argv[1]);
           76  +
           77  +  /* Check for the following errors:
           78  +  **
           79  +  **     * Too many attached databases,
           80  +  **     * Transaction currently open
           81  +  **     * Specified database name already being used.
           82  +  */
    46     83     if( db->nDb>=MAX_ATTACHED+2 ){
    47         -    sqlite3ErrorMsg(pParse, "too many attached databases - max %d", 
    48         -       MAX_ATTACHED);
    49         -    pParse->rc = SQLITE_ERROR;
    50         -    return;
           84  +    sqlite3_snprintf(
           85  +      127, zErr, "too many attached databases - max %d", MAX_ATTACHED
           86  +    );
           87  +    goto attach_error;
    51     88     }
    52         -
    53     89     if( !db->autoCommit ){
    54         -    sqlite3ErrorMsg(pParse, "cannot ATTACH database within transaction");
    55         -    pParse->rc = SQLITE_ERROR;
    56         -    return;
    57         -  }
    58         -
    59         -  zFile = sqlite3NameFromToken(pFilename);
    60         -  if( zFile==0 ){
    61         -    goto attach_end;
    62         -  }
    63         -#ifndef SQLITE_OMIT_AUTHORIZATION
    64         -  if( sqlite3AuthCheck(pParse, SQLITE_ATTACH, zFile, 0, 0)!=SQLITE_OK ){
    65         -    goto attach_end;
    66         -  }
    67         -#endif /* SQLITE_OMIT_AUTHORIZATION */
    68         -
    69         -  zName = sqlite3NameFromToken(pDbname);
    70         -  if( zName==0 ){
    71         -    goto attach_end;
           90  +    strcpy(zErr, "cannot ATTACH database within transaction");
           91  +    goto attach_error;
    72     92     }
    73     93     for(i=0; i<db->nDb; i++){
    74     94       char *z = db->aDb[i].zName;
    75     95       if( z && sqlite3StrICmp(z, zName)==0 ){
    76         -      sqlite3ErrorMsg(pParse, "database %s is already in use", zName);
    77         -      pParse->rc = SQLITE_ERROR;
    78         -      goto attach_end;
           96  +      sqlite3_snprintf(127, zErr, "database %s is already in use", zName);
           97  +      goto attach_error;
    79     98       }
    80     99     }
    81    100   
          101  +  /* Allocate the new entry in the db->aDb[] array and initialise the schema
          102  +  ** hash tables.
          103  +  */
    82    104     if( db->aDb==db->aDbStatic ){
    83    105       aNew = sqliteMalloc( sizeof(db->aDb[0])*3 );
    84    106       if( aNew==0 ){
    85         -      goto attach_end;
          107  +      return;
    86    108       }
    87    109       memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
    88    110     }else{
    89    111       aNew = sqliteRealloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
    90    112       if( aNew==0 ){
    91         -      goto attach_end;
          113  +      return;
    92    114       } 
    93    115     }
    94    116     db->aDb = aNew;
    95    117     aNew = &db->aDb[db->nDb++];
    96    118     memset(aNew, 0, sizeof(*aNew));
    97         -  sqlite3HashInit(&aNew->tblHash, SQLITE_HASH_STRING, 0);
    98         -  sqlite3HashInit(&aNew->idxHash, SQLITE_HASH_STRING, 0);
    99         -  sqlite3HashInit(&aNew->trigHash, SQLITE_HASH_STRING, 0);
   100         -  sqlite3HashInit(&aNew->aFKey, SQLITE_HASH_STRING, 1);
   101         -  aNew->zName = zName;
   102         -  zName = 0;
   103         -  aNew->safety_level = 3;
          119  +
          120  +  /* Open the database file. If the btree is successfully opened, use
          121  +  ** it to obtain the database schema. At this point the schema may
          122  +  ** or may not be initialised.
          123  +  */
   104    124     rc = sqlite3BtreeFactory(db, zFile, 0, MAX_PAGES, &aNew->pBt);
   105         -  if( rc ){
   106         -    sqlite3ErrorMsg(pParse, "unable to open database: %s", zFile);
          125  +  if( rc==SQLITE_OK ){
          126  +    aNew->pSchema = sqlite3SchemaGet(aNew->pBt);
          127  +    if( !aNew->pSchema ){
          128  +      rc = SQLITE_NOMEM;
          129  +    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
          130  +      strcpy(zErr, 
          131  +        "attached databases must use the same text encoding as main database");
          132  +      goto attach_error;
          133  +    }
   107    134     }
          135  +  aNew->zName = sqliteStrDup(zName);
          136  +  aNew->safety_level = 3;
          137  +
   108    138   #if SQLITE_HAS_CODEC
   109    139     {
   110    140       extern int sqlite3CodecAttach(sqlite3*, int, void*, int);
   111         -    char *zKey;
          141  +    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   112    142       int nKey;
   113         -    if( keyType==0 ){
   114         -      /* No key specified.  Use the key from the main database */
   115         -      extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   116         -      sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   117         -    }else if( keyType==1 ){
   118         -      /* Key specified as text */
   119         -      zKey = sqlite3NameFromToken(pKey);
   120         -      nKey = strlen(zKey);
   121         -    }else{
   122         -      /* Key specified as a BLOB */
   123         -      char *zTemp;
   124         -      assert( keyType==2 );
   125         -      pKey->z++;
   126         -      pKey->n--;
   127         -      zTemp = sqlite3NameFromToken(pKey);
   128         -      zKey = sqlite3HexToBlob(zTemp);
   129         -      sqliteFree(zTemp);
   130         -    }
   131         -    sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   132         -    if( keyType ){
   133         -      sqliteFree(zKey);
          143  +    char *zKey;
          144  +    int t = sqlite3_value_type(argv[2]);
          145  +    switch( t ){
          146  +      case SQLITE_INTEGER:
          147  +      case SQLITE_FLOAT:
          148  +        zErrDyn = sqliteStrDup("Invalid key value");
          149  +        rc = SQLITE_ERROR;
          150  +        break;
          151  +        
          152  +      case SQLITE_TEXT:
          153  +      case SQLITE_BLOB:
          154  +        nKey = sqlite3_value_bytes(argv[2]);
          155  +        zKey = (char *)sqlite3_value_blob(argv[2]);
          156  +        sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
          157  +        break;
          158  +
          159  +      case SQLITE_NULL:
          160  +        /* No key specified.  Use the key from the main database */
          161  +        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
          162  +        sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
          163  +        break;
   134    164       }
   135    165     }
   136    166   #endif
   137         -  db->flags &= ~SQLITE_Initialized;
   138         -  if( pParse->nErr==0 && rc==SQLITE_OK ){
   139         -    rc = sqlite3ReadSchema(pParse);
          167  +
          168  +  /* If the file was opened successfully, read the schema for the new database.
          169  +  ** If this fails, or if opening the file failed, then close the file and 
          170  +  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
          171  +  ** we found it.
          172  +  */
          173  +  if( rc==SQLITE_OK ){
          174  +    db->flags &= ~SQLITE_Initialized;
          175  +    sqlite3SafetyOn(db);
          176  +    rc = sqlite3Init(db, &zErrDyn);
          177  +    sqlite3SafetyOff(db);
   140    178     }
   141    179     if( rc ){
   142    180       int i = db->nDb - 1;
   143    181       assert( i>=2 );
   144    182       if( db->aDb[i].pBt ){
   145    183         sqlite3BtreeClose(db->aDb[i].pBt);
   146    184         db->aDb[i].pBt = 0;
          185  +      db->aDb[i].pSchema = 0;
   147    186       }
   148    187       sqlite3ResetInternalSchema(db, 0);
   149         -    assert( pParse->nErr>0 );  /* Always set by sqlite3ReadSchema() */
   150         -    if( pParse->rc==SQLITE_OK ){
   151         -      pParse->rc = SQLITE_ERROR;
   152         -    }
          188  +    db->nDb = i;
          189  +    sqlite3_snprintf(127, zErr, "unable to open database: %s", zFile);
          190  +    goto attach_error;
   153    191     }
          192  +  
          193  +  return;
   154    194   
   155         -attach_end:
   156         -  sqliteFree(zFile);
   157         -  sqliteFree(zName);
          195  +attach_error:
          196  +  /* Return an error if we get here */
          197  +  if( zErrDyn ){
          198  +    sqlite3_result_error(context, zErrDyn, -1);
          199  +    sqliteFree(zErrDyn);
          200  +  }else{
          201  +    zErr[sizeof(zErr)-1] = 0;
          202  +    sqlite3_result_error(context, zErr, -1);
          203  +  }
   158    204   }
   159    205   
   160    206   /*
   161         -** This routine is called by the parser to process a DETACH statement:
          207  +** An SQL user-function registered to do the work of an DETACH statement. The
          208  +** three arguments to the function come directly from a detach statement:
   162    209   **
   163         -**    DETACH DATABASE dbname
          210  +**     DETACH DATABASE x
   164    211   **
   165         -** The pDbname argument is the name of the database in the DETACH statement.
          212  +**     SELECT sqlite_detach(x)
   166    213   */
   167         -void sqlite3Detach(Parse *pParse, Token *pDbname){
          214  +static void detachFunc(
          215  +  sqlite3_context *context,
          216  +  int argc,
          217  +  sqlite3_value **argv
          218  +){
          219  +  const char *zName = (const char *)sqlite3_value_text(argv[0]);
          220  +  sqlite3 *db = sqlite3_user_data(context);
   168    221     int i;
   169         -  sqlite3 *db;
   170         -  Vdbe *v;
   171    222     Db *pDb = 0;
   172         -  char *zName;
          223  +  char zErr[128];
   173    224   
   174         -  v = sqlite3GetVdbe(pParse);
   175         -  if( !v ) return;
   176         -  sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
   177         -  sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
   178         -  if( pParse->explain ) return;
   179         -  db = pParse->db;
   180         -  zName = sqlite3NameFromToken(pDbname);
   181         -  if( zName==0 ) return;
          225  +  assert(zName);
   182    226     for(i=0; i<db->nDb; i++){
   183    227       pDb = &db->aDb[i];
   184    228       if( pDb->pBt==0 ) continue;
   185    229       if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
   186    230     }
          231  +
   187    232     if( i>=db->nDb ){
   188         -    sqlite3ErrorMsg(pParse, "no such database: %z", zName);
   189         -    return;
          233  +    sqlite3_snprintf(sizeof(zErr), zErr, "no such database: %s", zName);
          234  +    goto detach_error;
   190    235     }
   191    236     if( i<2 ){
   192         -    sqlite3ErrorMsg(pParse, "cannot detach database %z", zName);
   193         -    return;
          237  +    sqlite3_snprintf(sizeof(zErr), zErr, "cannot detach database %s", zName);
          238  +    goto detach_error;
   194    239     }
   195         -  sqliteFree(zName);
   196    240     if( !db->autoCommit ){
   197         -    sqlite3ErrorMsg(pParse, "cannot DETACH database within transaction");
   198         -    pParse->rc = SQLITE_ERROR;
   199         -    return;
          241  +    strcpy(zErr, "cannot DETACH database within transaction");
          242  +    goto detach_error;
   200    243     }
   201         -#ifndef SQLITE_OMIT_AUTHORIZATION
   202         -  if( sqlite3AuthCheck(pParse,SQLITE_DETACH,db->aDb[i].zName,0,0)!=SQLITE_OK ){
   203         -    return;
   204         -  }
   205         -#endif /* SQLITE_OMIT_AUTHORIZATION */
          244  +
   206    245     sqlite3BtreeClose(pDb->pBt);
   207    246     pDb->pBt = 0;
          247  +  pDb->pSchema = 0;
   208    248     sqlite3ResetInternalSchema(db, 0);
          249  +  return;
          250  +
          251  +detach_error:
          252  +  sqlite3_result_error(context, zErr, -1);
          253  +}
          254  +
          255  +/*
          256  +** This procedure generates VDBE code for a single invocation of either the
          257  +** sqlite_detach() or sqlite_attach() SQL user functions.
          258  +*/
          259  +static void codeAttach(
          260  +  Parse *pParse,       /* The parser context */
          261  +  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
          262  +  const char *zFunc,   /* Either "sqlite_attach" or "sqlite_detach */
          263  +  int nFunc,           /* Number of args to pass to zFunc */
          264  +  Expr *pAuthArg,      /* Expression to pass to authorization callback */
          265  +  Expr *pFilename,     /* Name of database file */
          266  +  Expr *pDbname,       /* Name of the database to use internally */
          267  +  Expr *pKey           /* Database key for encryption extension */
          268  +){
          269  +  int rc;
          270  +  NameContext sName;
          271  +  Vdbe *v;
          272  +  FuncDef *pFunc;
          273  +  sqlite3* db = pParse->db;
          274  +
          275  +#ifndef SQLITE_OMIT_AUTHORIZATION
          276  +  assert( sqlite3ThreadData()->mallocFailed || pAuthArg );
          277  +  if( pAuthArg ){
          278  +    char *zAuthArg = sqlite3NameFromToken(&pAuthArg->span);
          279  +    if( !zAuthArg ){
          280  +      goto attach_end;
          281  +    }
          282  +    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
          283  +    sqliteFree(zAuthArg);
          284  +    if(rc!=SQLITE_OK ){
          285  +      goto attach_end;
          286  +    }
          287  +  }
          288  +#endif /* SQLITE_OMIT_AUTHORIZATION */
          289  +
          290  +  memset(&sName, 0, sizeof(NameContext));
          291  +  sName.pParse = pParse;
          292  +
          293  +  if( 
          294  +      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
          295  +      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
          296  +      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
          297  +  ){
          298  +    pParse->nErr++;
          299  +    goto attach_end;
          300  +  }
          301  +
          302  +  v = sqlite3GetVdbe(pParse);
          303  +  sqlite3ExprCode(pParse, pFilename);
          304  +  sqlite3ExprCode(pParse, pDbname);
          305  +  sqlite3ExprCode(pParse, pKey);
          306  +
          307  +  assert(v || sqlite3ThreadData()->mallocFailed);
          308  +  if( v ){
          309  +    sqlite3VdbeAddOp(v, OP_Function, 0, nFunc);
          310  +    pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
          311  +    sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF);
          312  +
          313  +    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
          314  +    ** statement only). For DETACH, set it to false (expire all existing
          315  +    ** statements).
          316  +    */
          317  +    sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0);
          318  +  }
          319  +  
          320  +attach_end:
          321  +  sqlite3ExprDelete(pFilename);
          322  +  sqlite3ExprDelete(pDbname);
          323  +  sqlite3ExprDelete(pKey);
          324  +}
          325  +
          326  +/*
          327  +** Called by the parser to compile a DETACH statement.
          328  +**
          329  +**     DETACH pDbname
          330  +*/
          331  +void sqlite3Detach(Parse *pParse, Expr *pDbname){
          332  +  codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
          333  +}
          334  +
          335  +/*
          336  +** Called by the parser to compile an ATTACH statement.
          337  +**
          338  +**     ATTACH p AS pDbname KEY pKey
          339  +*/
          340  +void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
          341  +  codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
          342  +}
          343  +
          344  +/*
          345  +** Register the functions sqlite_attach and sqlite_detach.
          346  +*/
          347  +void sqlite3AttachFunctions(sqlite3 *db){
          348  +  static const int enc = SQLITE_UTF8;
          349  +  sqlite3_create_function(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
          350  +  sqlite3_create_function(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
   209    351   }
   210    352   
   211    353   /*
   212    354   ** Initialize a DbFixer structure.  This routine must be called prior
   213    355   ** to passing the structure to one of the sqliteFixAAAA() routines below.
   214    356   **
   215    357   ** The return value indicates whether or not fixation is required.  TRUE

Changes to SQLite.Interop/src/auth.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains code used to implement the sqlite3_set_authorizer()
    13     13   ** API.  This facility is an optional feature of the library.  Embedded
    14     14   ** systems that do not need this facility may omit it by recompiling
    15     15   ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
    16     16   **
    17         -** $Id: auth.c,v 1.10 2005/12/19 17:57:46 rmsimpson Exp $
           17  +** $Id: auth.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   
    21     21   /*
    22     22   ** All of the code in this file may be omitted by defining a single
    23     23   ** macro.
    24     24   */
................................................................................
   108    108     sqlite3 *db = pParse->db;
   109    109     int rc;
   110    110     Table *pTab;          /* The table being read */
   111    111     const char *zCol;     /* Name of the column of the table */
   112    112     int iSrc;             /* Index in pTabList->a[] of table being read */
   113    113     const char *zDBase;   /* Name of database being accessed */
   114    114     TriggerStack *pStack; /* The stack of current triggers */
          115  +  int iDb;              /* The index of the database the expression refers to */
   115    116   
   116    117     if( db->xAuth==0 ) return;
   117    118     if( pExpr->op==TK_AS ) return;
   118    119     assert( pExpr->op==TK_COLUMN );
          120  +  iDb = sqlite3SchemaToIndex(pParse->db, pExpr->pSchema);
   119    121     for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
   120    122       if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
   121    123     }
   122    124     if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
   123    125       pTab = pTabList->a[iSrc].pTab;
   124    126     }else if( (pStack = pParse->trigStack)!=0 ){
   125    127       /* This must be an attempt to read the NEW or OLD pseudo-tables
................................................................................
   136    138       zCol = pTab->aCol[pExpr->iColumn].zName;
   137    139     }else if( pTab->iPKey>=0 ){
   138    140       assert( pTab->iPKey<pTab->nCol );
   139    141       zCol = pTab->aCol[pTab->iPKey].zName;
   140    142     }else{
   141    143       zCol = "ROWID";
   142    144     }
   143         -  assert( pExpr->iDb<db->nDb );
   144         -  zDBase = db->aDb[pExpr->iDb].zName;
          145  +  assert( iDb<db->nDb );
          146  +  zDBase = db->aDb[iDb].zName;
   145    147     rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, 
   146    148                    pParse->zAuthContext);
   147    149     if( rc==SQLITE_IGNORE ){
   148    150       pExpr->op = TK_NULL;
   149    151     }else if( rc==SQLITE_DENY ){
   150         -    if( db->nDb>2 || pExpr->iDb!=0 ){
          152  +    if( db->nDb>2 || iDb!=0 ){
   151    153         sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", 
   152    154            zDBase, pTab->zName, zCol);
   153    155       }else{
   154    156         sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
   155    157       }
   156    158       pParse->rc = SQLITE_AUTH;
   157    159     }else if( rc!=SQLITE_OK ){

Changes to SQLite.Interop/src/btree.c.

     5      5   ** a legal notice, here is a blessing:
     6      6   **
     7      7   **    May you do good and not evil.
     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12         -** $Id: btree.c,v 1.12 2005/12/19 17:57:46 rmsimpson Exp $
           12  +** $Id: btree.c,v 1.13 2006/01/10 18:40:37 rmsimpson Exp $
    13     13   **
    14     14   ** This file implements a external (disk-based) database using BTrees.
    15     15   ** For a detailed discussion of BTrees, refer to
    16     16   **
    17     17   **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
    18     18   **     "Sorting And Searching", pages 473-480. Addison-Wesley
    19     19   **     Publishing Company, Reading, Massachusetts.
................................................................................
   226    226   ** assumes a minimum cell size of 3 bytes.  Such small cells will be
   227    227   ** exceedingly rare, but they are possible.
   228    228   */
   229    229   #define MX_CELL(pBt) ((pBt->pageSize-8)/3)
   230    230   
   231    231   /* Forward declarations */
   232    232   typedef struct MemPage MemPage;
          233  +typedef struct BtLock BtLock;
   233    234   
   234    235   /*
   235    236   ** This is a magic string that appears at the beginning of every
   236    237   ** SQLite database in order to identify the file as a real database.
   237    238   **
   238    239   ** You can change this value at compile-time by specifying a
   239    240   ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
................................................................................
   281    282     u16 maxLocal;        /* Copy of Btree.maxLocal or Btree.maxLeaf */
   282    283     u16 minLocal;        /* Copy of Btree.minLocal or Btree.minLeaf */
   283    284     u16 cellOffset;      /* Index in aData of first cell pointer */
   284    285     u16 idxParent;       /* Index in parent of this node */
   285    286     u16 nFree;           /* Number of free bytes on the page */
   286    287     u16 nCell;           /* Number of cells on this page, local and ovfl */
   287    288     struct _OvflCell {   /* Cells that will not fit on aData[] */
   288         -    u8 *pCell;           /* Pointers to the body of the overflow cell */
   289         -    u16 idx;             /* Insert this cell before idx-th non-overflow cell */
          289  +    u8 *pCell;          /* Pointers to the body of the overflow cell */
          290  +    u16 idx;            /* Insert this cell before idx-th non-overflow cell */
   290    291     } aOvfl[5];
   291         -  struct Btree *pBt;   /* Pointer back to BTree structure */
          292  +  BtShared *pBt;       /* Pointer back to BTree structure */
   292    293     u8 *aData;           /* Pointer back to the start of the page */
   293    294     Pgno pgno;           /* Page number for this page */
   294    295     MemPage *pParent;    /* The parent of this page.  NULL for root */
   295    296   };
   296    297   
   297    298   /*
   298    299   ** The in-memory image of a disk page has the auxiliary information appended
   299    300   ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
   300    301   ** that extra information.
   301    302   */
   302    303   #define EXTRA_SIZE sizeof(MemPage)
   303    304   
          305  +/* Btree handle */
          306  +struct Btree {
          307  +  sqlite3 *pSqlite;
          308  +  BtShared *pBt;
          309  +  u8 inTrans;            /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
          310  +};
          311  +
          312  +/*
          313  +** Btree.inTrans may take one of the following values.
          314  +**
          315  +** If the shared-data extension is enabled, there may be multiple users
          316  +** of the Btree structure. At most one of these may open a write transaction,
          317  +** but any number may have active read transactions. Variable Btree.pDb 
          318  +** points to the handle that owns any current write-transaction.
          319  +*/
          320  +#define TRANS_NONE  0
          321  +#define TRANS_READ  1
          322  +#define TRANS_WRITE 2
          323  +
   304    324   /*
   305    325   ** Everything we need to know about an open database
   306    326   */
   307         -struct Btree {
          327  +struct BtShared {
   308    328     Pager *pPager;        /* The page cache */
   309    329     BtCursor *pCursor;    /* A list of all open cursors */
   310    330     MemPage *pPage1;      /* First page of the database */
   311         -  u8 inTrans;           /* True if a transaction is in progress */
   312    331     u8 inStmt;            /* True if we are in a statement subtransaction */
   313    332     u8 readOnly;          /* True if the underlying file is readonly */
   314    333     u8 maxEmbedFrac;      /* Maximum payload as % of total page size */
   315    334     u8 minEmbedFrac;      /* Minimum payload as % of total page size */
   316    335     u8 minLeafFrac;       /* Minimum leaf payload as % of total page size */
   317    336     u8 pageSizeFixed;     /* True if the page size can no longer be changed */
   318    337   #ifndef SQLITE_OMIT_AUTOVACUUM
................................................................................
   321    340     u16 pageSize;         /* Total number of bytes on a page */
   322    341     u16 usableSize;       /* Number of usable bytes on each page */
   323    342     int maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
   324    343     int minLocal;         /* Minimum local payload in non-LEAFDATA tables */
   325    344     int maxLeaf;          /* Maximum local payload in a LEAFDATA table */
   326    345     int minLeaf;          /* Minimum local payload in a LEAFDATA table */
   327    346     BusyHandler *pBusyHandler;   /* Callback for when there is lock contention */
          347  +  u8 inTransaction;     /* Transaction state */
          348  +  int nRef;             /* Number of references to this structure */
          349  +  int nTransaction;     /* Number of open transactions (read + write) */
          350  +  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
          351  +  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
          352  +#ifndef SQLITE_OMIT_SHARED_CACHE
          353  +  BtLock *pLock;        /* List of locks held on this shared-btree struct */
          354  +  BtShared *pNext;      /* Next in ThreadData.pBtree linked list */
          355  +#endif
   328    356   };
   329         -typedef Btree Bt;
   330         -
   331         -/*
   332         -** Btree.inTrans may take one of the following values.
   333         -*/
   334         -#define TRANS_NONE  0
   335         -#define TRANS_READ  1
   336         -#define TRANS_WRITE 2
   337    357   
   338    358   /*
   339    359   ** An instance of the following structure is used to hold information
   340    360   ** about a cell.  The parseCellPtr() function fills in this structure
   341    361   ** based on information extract from the raw disk page.
   342    362   */
   343    363   typedef struct CellInfo CellInfo;
................................................................................
   353    373   
   354    374   /*
   355    375   ** A cursor is a pointer to a particular entry in the BTree.
   356    376   ** The entry is identified by its MemPage and the index in
   357    377   ** MemPage.aCell[] of the entry.
   358    378   */
   359    379   struct BtCursor {
   360         -  Btree *pBt;               /* The Btree to which this cursor belongs */
          380  +  Btree *pBtree;            /* The Btree to which this cursor belongs */
   361    381     BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
   362    382     int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
   363    383     void *pArg;               /* First arg to xCompare() */
   364    384     Pgno pgnoRoot;            /* The root page of this tree */
   365    385     MemPage *pPage;           /* Page that contains the entry */
   366    386     int idx;                  /* Index of the entry in pPage->aCell[] */
   367    387     CellInfo info;            /* A parse of the cell we are pointing at */
   368    388     u8 wrFlag;                /* True if writable */
   369         -  u8 isValid;               /* TRUE if points to a valid entry */
          389  +  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
          390  +#ifndef SQLITE_OMIT_SHARED_CACHE
          391  +  void *pKey;
          392  +  i64 nKey;
          393  +  int skip;        /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
          394  +#endif
   370    395   };
   371    396   
          397  +/*
          398  +** Potential values for BtCursor.eState. The first two values (VALID and 
          399  +** INVALID) may occur in any build. The third (REQUIRESEEK) may only occur 
          400  +** if sqlite was compiled without the OMIT_SHARED_CACHE symbol defined.
          401  +**
          402  +** CURSOR_VALID:
          403  +**   Cursor points to a valid entry. getPayload() etc. may be called.
          404  +**
          405  +** CURSOR_INVALID:
          406  +**   Cursor does not point to a valid entry. This can happen (for example) 
          407  +**   because the table is empty or because BtreeCursorFirst() has not been
          408  +**   called.
          409  +**
          410  +** CURSOR_REQUIRESEEK:
          411  +**   The table that this cursor was opened on still exists, but has been 
          412  +**   modified since the cursor was last used. The cursor position is saved
          413  +**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
          414  +**   this state, restoreCursorPosition() can be called to attempt to seek 
          415  +**   the cursor to the saved position.
          416  +*/
          417  +#define CURSOR_INVALID           0
          418  +#define CURSOR_VALID             1
          419  +#define CURSOR_REQUIRESEEK       2
          420  +
   372    421   /*
   373    422   ** The TRACE macro will print high-level status information about the
   374    423   ** btree operation when the global variable sqlite3_btree_trace is
   375    424   ** enabled.
   376    425   */
   377    426   #if SQLITE_TEST
   378    427   # define TRACE(X)   if( sqlite3_btree_trace )\
................................................................................
   381    430   # define TRACE(X)
   382    431   #endif
   383    432   int sqlite3_btree_trace=0;  /* True to enable tracing */
   384    433   
   385    434   /*
   386    435   ** Forward declaration
   387    436   */
   388         -static int checkReadLocks(Btree*,Pgno,BtCursor*);
          437  +static int checkReadLocks(BtShared*,Pgno,BtCursor*);
   389    438   
   390    439   /*
   391    440   ** Read or write a two- and four-byte big-endian integer values.
   392    441   */
   393    442   static u32 get2byte(unsigned char *p){
   394    443     return (p[0]<<8) | p[1];
   395    444   }
................................................................................
   418    467   
   419    468   /* The database page the PENDING_BYTE occupies. This page is never used.
   420    469   ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
   421    470   ** should possibly be consolidated (presumably in pager.h).
   422    471   */
   423    472   #define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
   424    473   
          474  +/*
          475  +** A linked list of the following structures is stored at BtShared.pLock.
          476  +** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
          477  +** is opened on the table with root page BtShared.iTable. Locks are removed
          478  +** from this list when a transaction is committed or rolled back, or when
          479  +** a btree handle is closed.
          480  +*/
          481  +struct BtLock {
          482  +  Btree *pBtree;        /* Btree handle holding this lock */
          483  +  Pgno iTable;          /* Root page of table */
          484  +  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
          485  +  BtLock *pNext;        /* Next in BtShared.pLock list */
          486  +};
          487  +
          488  +/* Candidate values for BtLock.eLock */
          489  +#define READ_LOCK     1
          490  +#define WRITE_LOCK    2
          491  +
          492  +#ifdef SQLITE_OMIT_SHARED_CACHE
          493  +  /*
          494  +  ** The functions queryTableLock(), lockTable() and unlockAllTables()
          495  +  ** manipulate entries in the BtShared.pLock linked list used to store
          496  +  ** shared-cache table level locks. If the library is compiled with the
          497  +  ** shared-cache feature disabled, then there is only ever one user
          498  +  ** of each BtShared structure and so this locking is not necessary. 
          499  +  ** So define the lock related functions as no-ops.
          500  +  */
          501  +  #define queryTableLock(a,b,c) SQLITE_OK
          502  +  #define lockTable(a,b,c) SQLITE_OK
          503  +  #define unlockAllTables(a)
          504  +  #define restoreCursorPosition(a,b) SQLITE_OK
          505  +  #define saveAllCursors(a,b,c) SQLITE_OK
          506  +
          507  +#else
          508  +
          509  +/*
          510  +** Save the current cursor position in the variables BtCursor.nKey 
          511  +** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
          512  +*/
          513  +static int saveCursorPosition(BtCursor *pCur){
          514  +  int rc = SQLITE_OK;
          515  +
          516  +  assert( CURSOR_VALID==pCur->eState|| CURSOR_INVALID==pCur->eState );
          517  +  assert( 0==pCur->pKey );
          518  +
          519  +  if( pCur->eState==CURSOR_VALID ){
          520  +    rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
          521  +
          522  +    /* If this is an intKey table, then the above call to BtreeKeySize()
          523  +    ** stores the integer key in pCur->nKey. In this case this value is
          524  +    ** all that is required. Otherwise, if pCur is not open on an intKey
          525  +    ** table, then malloc space for and store the pCur->nKey bytes of key 
          526  +    ** data.
          527  +    */
          528  +    if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
          529  +      void *pKey = sqliteMalloc(pCur->nKey);
          530  +      if( pKey ){
          531  +        rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
          532  +        if( rc==SQLITE_OK ){
          533  +          pCur->pKey = pKey;
          534  +        }else{
          535  +          sqliteFree(pKey);
          536  +        }
          537  +      }else{
          538  +        rc = SQLITE_NOMEM;
          539  +      }
          540  +    }
          541  +    assert( !pCur->pPage->intKey || !pCur->pKey );
          542  +
          543  +    /* Todo: Should we drop the reference to pCur->pPage here? */
          544  +
          545  +    if( rc==SQLITE_OK ){
          546  +      pCur->eState = CURSOR_REQUIRESEEK;
          547  +    }
          548  +  }
          549  +
          550  +  return rc;
          551  +}
          552  +
          553  +/*
          554  +** Save the positions of all cursors except pExcept open on the table 
          555  +** with root-page iRoot. Usually, this is called just before cursor
          556  +** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
          557  +*/
          558  +static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
          559  +  BtCursor *p;
          560  +  if( sqlite3ThreadData()->useSharedData ){
          561  +    for(p=pBt->pCursor; p; p=p->pNext){
          562  +      if( p!=pExcept && p->pgnoRoot==iRoot && p->eState==CURSOR_VALID ){
          563  +        int rc = saveCursorPosition(p);
          564  +        if( SQLITE_OK!=rc ){
          565  +          return rc;
          566  +        }
          567  +      }
          568  +    }
          569  +  }
          570  +  return SQLITE_OK;
          571  +}
          572  +
          573  +/*
          574  +** Restore the cursor to the position it was in (or as close to as possible)
          575  +** when saveCursorPosition() was called. Note that this call deletes the 
          576  +** saved position info stored by saveCursorPosition(), so there can be
          577  +** at most one effective restoreCursorPosition() call after each 
          578  +** saveCursorPosition().
          579  +**
          580  +** If the second argument argument - doSeek - is false, then instead of 
          581  +** returning the cursor to it's saved position, any saved position is deleted
          582  +** and the cursor state set to CURSOR_INVALID.
          583  +*/
          584  +static int restoreCursorPosition(BtCursor *pCur, int doSeek){
          585  +  int rc = SQLITE_OK;
          586  +  if( pCur->eState==CURSOR_REQUIRESEEK ){
          587  +    assert( sqlite3ThreadData()->useSharedData );
          588  +    if( doSeek ){
          589  +      rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, &pCur->skip);
          590  +    }else{
          591  +      pCur->eState = CURSOR_INVALID;
          592  +    }
          593  +    if( rc==SQLITE_OK ){
          594  +      sqliteFree(pCur->pKey);
          595  +      pCur->pKey = 0;
          596  +      assert( CURSOR_VALID==pCur->eState || CURSOR_INVALID==pCur->eState );
          597  +    }
          598  +  }
          599  +  return rc;
          600  +}
          601  +
          602  +/*
          603  +** Query to see if btree handle p may obtain a lock of type eLock 
          604  +** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
          605  +** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
          606  +** SQLITE_LOCKED if not.
          607  +*/
          608  +static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
          609  +  BtShared *pBt = p->pBt;
          610  +  BtLock *pIter;
          611  +
          612  +  /* This is a no-op if the shared-cache is not enabled */
          613  +  if( 0==sqlite3ThreadData()->useSharedData ){
          614  +    return SQLITE_OK;
          615  +  }
          616  +
          617  +  /* This (along with lockTable()) is where the ReadUncommitted flag is
          618  +  ** dealt with. If the caller is querying for a read-lock and the flag is
          619  +  ** set, it is unconditionally granted - even if there are write-locks
          620  +  ** on the table. If a write-lock is requested, the ReadUncommitted flag
          621  +  ** is not considered.
          622  +  **
          623  +  ** In function lockTable(), if a read-lock is demanded and the 
          624  +  ** ReadUncommitted flag is set, no entry is added to the locks list 
          625  +  ** (BtShared.pLock).
          626  +  **
          627  +  ** To summarize: If the ReadUncommitted flag is set, then read cursors do
          628  +  ** not create or respect table locks. The locking procedure for a 
          629  +  ** write-cursor does not change.
          630  +  */
          631  +  if( 
          632  +    !p->pSqlite || 
          633  +    0==(p->pSqlite->flags&SQLITE_ReadUncommitted) || 
          634  +    eLock==WRITE_LOCK ||
          635  +    iTab==MASTER_ROOT
          636  +  ){
          637  +    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
          638  +      if( pIter->pBtree!=p && pIter->iTable==iTab && 
          639  +          (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
          640  +        return SQLITE_LOCKED;
          641  +      }
          642  +    }
          643  +  }
          644  +  return SQLITE_OK;
          645  +}
          646  +
          647  +/*
          648  +** Add a lock on the table with root-page iTable to the shared-btree used
          649  +** by Btree handle p. Parameter eLock must be either READ_LOCK or 
          650  +** WRITE_LOCK.
          651  +**
          652  +** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
          653  +** SQLITE_NOMEM may also be returned.
          654  +*/
          655  +static int lockTable(Btree *p, Pgno iTable, u8 eLock){
          656  +  BtShared *pBt = p->pBt;
          657  +  BtLock *pLock = 0;
          658  +  BtLock *pIter;
          659  +
          660  +  /* This is a no-op if the shared-cache is not enabled */
          661  +  if( 0==sqlite3ThreadData()->useSharedData ){
          662  +    return SQLITE_OK;
          663  +  }
          664  +
          665  +  assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
          666  +
          667  +  /* If the read-uncommitted flag is set and a read-lock is requested,
          668  +  ** return early without adding an entry to the BtShared.pLock list. See
          669  +  ** comment in function queryTableLock() for more info on handling 
          670  +  ** the ReadUncommitted flag.
          671  +  */
          672  +  if( 
          673  +    (p->pSqlite) && 
          674  +    (p->pSqlite->flags&SQLITE_ReadUncommitted) && 
          675  +    (eLock==READ_LOCK) &&
          676  +    iTable!=MASTER_ROOT
          677  +  ){
          678  +    return SQLITE_OK;
          679  +  }
          680  +
          681  +  /* First search the list for an existing lock on this table. */
          682  +  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
          683  +    if( pIter->iTable==iTable && pIter->pBtree==p ){
          684  +      pLock = pIter;
          685  +      break;
          686  +    }
          687  +  }
          688  +
          689  +  /* If the above search did not find a BtLock struct associating Btree p
          690  +  ** with table iTable, allocate one and link it into the list.
          691  +  */
          692  +  if( !pLock ){
          693  +    pLock = (BtLock *)sqliteMalloc(sizeof(BtLock));
          694  +    if( !pLock ){
          695  +      return SQLITE_NOMEM;
          696  +    }
          697  +    pLock->iTable = iTable;
          698  +    pLock->pBtree = p;
          699  +    pLock->pNext = pBt->pLock;
          700  +    pBt->pLock = pLock;
          701  +  }
          702  +
          703  +  /* Set the BtLock.eLock variable to the maximum of the current lock
          704  +  ** and the requested lock. This means if a write-lock was already held
          705  +  ** and a read-lock requested, we don't incorrectly downgrade the lock.
          706  +  */
          707  +  assert( WRITE_LOCK>READ_LOCK );
          708  +  if( eLock>pLock->eLock ){
          709  +    pLock->eLock = eLock;
          710  +  }
          711  +
          712  +  return SQLITE_OK;
          713  +}
          714  +
          715  +/*
          716  +** Release all the table locks (locks obtained via calls to the lockTable()
          717  +** procedure) held by Btree handle p.
          718  +*/
          719  +static void unlockAllTables(Btree *p){
          720  +  BtLock **ppIter = &p->pBt->pLock;
          721  +
          722  +  /* If the shared-cache extension is not enabled, there should be no
          723  +  ** locks in the BtShared.pLock list, making this procedure a no-op. Assert
          724  +  ** that this is the case.
          725  +  */
          726  +  assert( sqlite3ThreadData()->useSharedData || 0==*ppIter );
          727  +
          728  +  while( *ppIter ){
          729  +    BtLock *pLock = *ppIter;
          730  +    if( pLock->pBtree==p ){
          731  +      *ppIter = pLock->pNext;
          732  +      sqliteFree(pLock);
          733  +    }else{
          734  +      ppIter = &pLock->pNext;
          735  +    }
          736  +  }
          737  +}
          738  +#endif /* SQLITE_OMIT_SHARED_CACHE */
          739  +
   425    740   #ifndef SQLITE_OMIT_AUTOVACUUM
   426    741   /*
   427    742   ** These macros define the location of the pointer-map entry for a 
   428    743   ** database page. The first argument to each is the number of usable
   429    744   ** bytes on each page of the database (often 1024). The second is the
   430    745   ** page number to look up in the pointer map.
   431    746   **
................................................................................
   482    797   /*
   483    798   ** Write an entry into the pointer map.
   484    799   **
   485    800   ** This routine updates the pointer map entry for page number 'key'
   486    801   ** so that it maps to type 'eType' and parent page number 'pgno'.
   487    802   ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
   488    803   */
   489         -static int ptrmapPut(Btree *pBt, Pgno key, u8 eType, Pgno parent){
          804  +static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
   490    805     u8 *pPtrmap;    /* The pointer map page */
   491    806     Pgno iPtrmap;   /* The pointer map page number */
   492    807     int offset;     /* Offset in pointer map page */
   493    808     int rc;
   494    809   
   495    810     assert( pBt->autoVacuum );
   496    811     if( key==0 ){
................................................................................
   519    834   /*
   520    835   ** Read an entry from the pointer map.
   521    836   **
   522    837   ** This routine retrieves the pointer map entry for page 'key', writing
   523    838   ** the type and parent page number to *pEType and *pPgno respectively.
   524    839   ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
   525    840   */
   526         -static int ptrmapGet(Btree *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
          841  +static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
   527    842     int iPtrmap;       /* Pointer map page index */
   528    843     u8 *pPtrmap;       /* Pointer map page data */
   529    844     int offset;        /* Offset of entry in pointer map */
   530    845     int rc;
   531    846   
   532    847     iPtrmap = PTRMAP_PAGENO(pBt->usableSize, key);
   533    848     rc = sqlite3pager_get(pBt->pPager, iPtrmap, (void **)&pPtrmap);
................................................................................
   786   1101     sqliteFree(used);
   787   1102   }
   788   1103   #define pageIntegrity(X) _pageIntegrity(X)
   789   1104   #else
   790   1105   # define pageIntegrity(X)
   791   1106   #endif
   792   1107   
         1108  +/* A bunch of assert() statements to check the transaction state variables
         1109  +** of handle p (type Btree*) are internally consistent.
         1110  +*/
         1111  +#define btreeIntegrity(p) \
         1112  +  assert( p->inTrans!=TRANS_NONE || p->pBt->nTransaction<p->pBt->nRef ); \
         1113  +  assert( p->pBt->nTransaction<=p->pBt->nRef ); \
         1114  +  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
         1115  +  assert( p->pBt->inTransaction>=p->inTrans ); 
         1116  +
   793   1117   /*
   794   1118   ** Defragment the page given.  All Cells are moved to the
   795         -** beginning of the page and all free space is collected 
   796         -** into one big FreeBlk at the end of the page.
         1119  +** end of the page and all free space is collected into one
         1120  +** big FreeBlk that occurs in between the header and cell
         1121  +** pointer array and the cell content area.
   797   1122   */
   798   1123   static int defragmentPage(MemPage *pPage){
   799   1124     int i;                     /* Loop counter */
   800   1125     int pc;                    /* Address of a i-th cell */
   801   1126     int addr;                  /* Offset of first byte after cell pointer array */
   802   1127     int hdr;                   /* Offset to the page header */
   803   1128     int size;                  /* Size of a cell */
................................................................................
   973   1298   }
   974   1299   
   975   1300   /*
   976   1301   ** Decode the flags byte (the first byte of the header) for a page
   977   1302   ** and initialize fields of the MemPage structure accordingly.
   978   1303   */
   979   1304   static void decodeFlags(MemPage *pPage, int flagByte){
   980         -  Btree *pBt;     /* A copy of pPage->pBt */
         1305  +  BtShared *pBt;     /* A copy of pPage->pBt */
   981   1306   
   982   1307     assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
   983   1308     pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
   984   1309     pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
   985   1310     pPage->leaf = (flagByte & PTF_LEAF)!=0;
   986   1311     pPage->childPtrSize = 4*(pPage->leaf==0);
   987   1312     pBt = pPage->pBt;
................................................................................
  1013   1338   static int initPage(
  1014   1339     MemPage *pPage,        /* The page to be initialized */
  1015   1340     MemPage *pParent       /* The parent.  Might be NULL */
  1016   1341   ){
  1017   1342     int pc;            /* Address of a freeblock within pPage->aData[] */
  1018   1343     int hdr;           /* Offset to beginning of page header */
  1019   1344     u8 *data;          /* Equal to pPage->aData */
  1020         -  Btree *pBt;        /* The main btree structure */
         1345  +  BtShared *pBt;        /* The main btree structure */
  1021   1346     int usableSize;    /* Amount of usable space on each page */
  1022   1347     int cellOffset;    /* Offset from start of page to first cell pointer */
  1023   1348     int nFree;         /* Number of unused bytes on the page */
  1024   1349     int top;           /* First byte of the cell content area */
  1025   1350   
  1026   1351     pBt = pPage->pBt;
  1027   1352     assert( pBt!=0 );
................................................................................
  1086   1411   
  1087   1412   /*
  1088   1413   ** Set up a raw page so that it looks like a database page holding
  1089   1414   ** no entries.
  1090   1415   */
  1091   1416   static void zeroPage(MemPage *pPage, int flags){
  1092   1417     unsigned char *data = pPage->aData;
  1093         -  Btree *pBt = pPage->pBt;
         1418  +  BtShared *pBt = pPage->pBt;
  1094   1419     int hdr = pPage->hdrOffset;
  1095   1420     int first;
  1096   1421   
  1097   1422     assert( sqlite3pager_pagenumber(data)==pPage->pgno );
  1098   1423     assert( &data[pBt->pageSize] == (unsigned char*)pPage );
  1099   1424     assert( sqlite3pager_iswriteable(data) );
  1100   1425     memset(&data[hdr], 0, pBt->usableSize - hdr);
................................................................................
  1114   1439     pageIntegrity(pPage);
  1115   1440   }
  1116   1441   
  1117   1442   /*
  1118   1443   ** Get a page from the pager.  Initialize the MemPage.pBt and
  1119   1444   ** MemPage.aData elements if needed.
  1120   1445   */
  1121         -static int getPage(Btree *pBt, Pgno pgno, MemPage **ppPage){
         1446  +static int getPage(BtShared *pBt, Pgno pgno, MemPage **ppPage){
  1122   1447     int rc;
  1123   1448     unsigned char *aData;
  1124   1449     MemPage *pPage;
  1125   1450     rc = sqlite3pager_get(pBt->pPager, pgno, (void**)&aData);
  1126   1451     if( rc ) return rc;
  1127   1452     pPage = (MemPage*)&aData[pBt->pageSize];
  1128   1453     pPage->aData = aData;
................................................................................
  1135   1460   
  1136   1461   /*
  1137   1462   ** Get a page from the pager and initialize it.  This routine
  1138   1463   ** is just a convenience wrapper around separate calls to
  1139   1464   ** getPage() and initPage().
  1140   1465   */
  1141   1466   static int getAndInitPage(
  1142         -  Btree *pBt,          /* The database file */
         1467  +  BtShared *pBt,          /* The database file */
  1143   1468     Pgno pgno,           /* Number of the page to get */
  1144   1469     MemPage **ppPage,    /* Write the page pointer here */
  1145   1470     MemPage *pParent     /* Parent of the page */
  1146   1471   ){
  1147   1472     int rc;
  1148   1473     if( pgno==0 ){
  1149   1474       return SQLITE_CORRUPT_BKPT; 
................................................................................
  1208   1533   ** 
  1209   1534   ** zFilename is the name of the database file.  If zFilename is NULL
  1210   1535   ** a new database with a random name is created.  This randomly named
  1211   1536   ** database file will be deleted when sqlite3BtreeClose() is called.
  1212   1537   */
  1213   1538   int sqlite3BtreeOpen(
  1214   1539     const char *zFilename,  /* Name of the file containing the BTree database */
         1540  +  sqlite3 *pSqlite,       /* Associated database handle */
  1215   1541     Btree **ppBtree,        /* Pointer to new Btree object written here */
  1216   1542     int flags               /* Options */
  1217   1543   ){
  1218         -  Btree *pBt;
         1544  +  BtShared *pBt;          /* Shared part of btree structure */
         1545  +  Btree *p;               /* Handle to return */
  1219   1546     int rc;
  1220   1547     int nReserve;
  1221   1548     unsigned char zDbHeader[100];
         1549  +#ifndef SQLITE_OMIT_SHARED_CACHE
         1550  +  ThreadData *pTsd = sqlite3ThreadData();
         1551  +#endif
         1552  +
         1553  +  /* Set the variable isMemdb to true for an in-memory database, or 
         1554  +  ** false for a file-based database. This symbol is only required if
         1555  +  ** either of the shared-data or autovacuum features are compiled 
         1556  +  ** into the library.
         1557  +  */
         1558  +#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
         1559  +  #ifdef SQLITE_OMIT_MEMORYDB
         1560  +  const int isMemdb = !zFilename;
         1561  +  #else
         1562  +  const int isMemdb = !zFilename || (strcmp(zFilename, ":memory:")?0:1);
         1563  +  #endif
         1564  +#endif
         1565  +
         1566  +  p = sqliteMalloc(sizeof(Btree));
         1567  +  if( !p ){
         1568  +    return SQLITE_NOMEM;
         1569  +  }
         1570  +  p->inTrans = TRANS_NONE;
         1571  +  p->pSqlite = pSqlite;
         1572  +
         1573  +  /* Try to find an existing Btree structure opened on zFilename. */
         1574  +#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
         1575  +  if( pTsd->useSharedData && zFilename && !isMemdb ){
         1576  +    char *zFullPathname = sqlite3OsFullPathname(zFilename);
         1577  +    if( !zFullPathname ){
         1578  +      sqliteFree(p);
         1579  +      return SQLITE_NOMEM;
         1580  +    }
         1581  +    for(pBt=pTsd->pBtree; pBt; pBt=pBt->pNext){
         1582  +      if( 0==strcmp(zFullPathname, sqlite3pager_filename(pBt->pPager)) ){
         1583  +        p->pBt = pBt;
         1584  +        *ppBtree = p;
         1585  +        pBt->nRef++;
         1586  +        sqliteFree(zFullPathname);
         1587  +        return SQLITE_OK;
         1588  +      }
         1589  +    }
         1590  +    sqliteFree(zFullPathname);
         1591  +  }
         1592  +#endif
  1222   1593   
  1223   1594     /*
  1224   1595     ** The following asserts make sure that structures used by the btree are
  1225   1596     ** the right size.  This is to guard against size changes that result
  1226   1597     ** when compiling on a different architecture.
  1227   1598     */
  1228   1599     assert( sizeof(i64)==8 );
................................................................................
  1230   1601     assert( sizeof(u32)==4 );
  1231   1602     assert( sizeof(u16)==2 );
  1232   1603     assert( sizeof(Pgno)==4 );
  1233   1604   
  1234   1605     pBt = sqliteMalloc( sizeof(*pBt) );
  1235   1606     if( pBt==0 ){
  1236   1607       *ppBtree = 0;
         1608  +    sqliteFree(p);
  1237   1609       return SQLITE_NOMEM;
  1238   1610     }
  1239   1611     rc = sqlite3pager_open(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
  1240   1612     if( rc!=SQLITE_OK ){
  1241   1613       if( pBt->pPager ) sqlite3pager_close(pBt->pPager);
  1242   1614       sqliteFree(pBt);
         1615  +    sqliteFree(p);
  1243   1616       *ppBtree = 0;
  1244   1617       return rc;
  1245   1618     }
         1619  +  p->pBt = pBt;
         1620  +
  1246   1621     sqlite3pager_set_destructor(pBt->pPager, pageDestructor);
  1247   1622     sqlite3pager_set_reiniter(pBt->pPager, pageReinit);
  1248   1623     pBt->pCursor = 0;
  1249   1624     pBt->pPage1 = 0;
  1250   1625     pBt->readOnly = sqlite3pager_isreadonly(pBt->pPager);
  1251   1626     sqlite3pager_read_fileheader(pBt->pPager, sizeof(zDbHeader), zDbHeader);
  1252   1627     pBt->pageSize = get2byte(&zDbHeader[16]);
................................................................................
  1259   1634   #ifndef SQLITE_OMIT_AUTOVACUUM
  1260   1635       /* If the magic name ":memory:" will create an in-memory database, then
  1261   1636       ** do not set the auto-vacuum flag, even if SQLITE_DEFAULT_AUTOVACUUM
  1262   1637       ** is true. On the other hand, if SQLITE_OMIT_MEMORYDB has been defined,
  1263   1638       ** then ":memory:" is just a regular file-name. Respect the auto-vacuum
  1264   1639       ** default in this case.
  1265   1640       */
  1266         -#ifndef SQLITE_OMIT_MEMORYDB
  1267         -    if( zFilename && strcmp(zFilename,":memory:") ){
  1268         -#else
  1269         -    if( zFilename ){
  1270         -#endif
         1641  +    if( zFilename && !isMemdb ){
  1271   1642         pBt->autoVacuum = SQLITE_DEFAULT_AUTOVACUUM;
  1272   1643       }
  1273   1644   #endif
  1274   1645       nReserve = 0;
  1275   1646     }else{
  1276   1647       nReserve = zDbHeader[20];
  1277   1648       pBt->maxEmbedFrac = zDbHeader[21];
................................................................................
  1281   1652   #ifndef SQLITE_OMIT_AUTOVACUUM
  1282   1653       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  1283   1654   #endif
  1284   1655     }
  1285   1656     pBt->usableSize = pBt->pageSize - nReserve;
  1286   1657     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
  1287   1658     sqlite3pager_set_pagesize(pBt->pPager, pBt->pageSize);
  1288         -  *ppBtree = pBt;
         1659  +
         1660  +#ifndef SQLITE_OMIT_SHARED_CACHE
         1661  +  /* Add the new btree to the linked list starting at ThreadData.pBtree */
         1662  +  if( pTsd->useSharedData && zFilename && !isMemdb ){
         1663  +    pBt->pNext = pTsd->pBtree;
         1664  +    pTsd->pBtree = pBt;
         1665  +  }
         1666  +#endif
         1667  +  pBt->nRef = 1;
         1668  +  *ppBtree = p;
  1289   1669     return SQLITE_OK;
  1290   1670   }
  1291   1671   
  1292   1672   /*
  1293   1673   ** Close an open database and invalidate all cursors.
  1294   1674   */
  1295         -int sqlite3BtreeClose(Btree *pBt){
  1296         -  while( pBt->pCursor ){
  1297         -    sqlite3BtreeCloseCursor(pBt->pCursor);
         1675  +int sqlite3BtreeClose(Btree *p){
         1676  +  BtShared *pBt = p->pBt;
         1677  +  BtCursor *pCur;
         1678  +
         1679  +#ifndef SQLITE_OMIT_SHARED_CACHE
         1680  +  ThreadData *pTsd = sqlite3ThreadData();
         1681  +#endif
         1682  +
         1683  +  /* Drop any table-locks */
         1684  +  unlockAllTables(p);
         1685  +
         1686  +  /* Close all cursors opened via this handle.  */
         1687  +  pCur = pBt->pCursor;
         1688  +  while( pCur ){
         1689  +    BtCursor *pTmp = pCur;
         1690  +    pCur = pCur->pNext;
         1691  +    if( pTmp->pBtree==p ){
         1692  +      sqlite3BtreeCloseCursor(pTmp);
         1693  +    }
  1298   1694     }
         1695  +
         1696  +  sqliteFree(p);
         1697  +
         1698  +#ifndef SQLITE_OMIT_SHARED_CACHE
         1699  +  /* If there are still other outstanding references to the shared-btree
         1700  +  ** structure, return now. The remainder of this procedure cleans 
         1701  +  ** up the shared-btree.
         1702  +  */
         1703  +  assert( pBt->nRef>0 );
         1704  +  pBt->nRef--;
         1705  +  if( pBt->nRef ){
         1706  +    return SQLITE_OK;
         1707  +  }
         1708  +
         1709  +  /* Remove the shared-btree from the thread wide list */
         1710  +  if( pTsd->pBtree==pBt ){
         1711  +    pTsd->pBtree = pBt->pNext;
         1712  +  }else{
         1713  +    BtShared *pPrev;
         1714  +    for(pPrev=pTsd->pBtree; pPrev && pPrev->pNext!=pBt; pPrev=pPrev->pNext);
         1715  +    if( pPrev ){
         1716  +      pPrev->pNext = pBt->pNext;
         1717  +    }
         1718  +  }
         1719  +#endif
         1720  +
         1721  +  /* Close the pager and free the shared-btree structure */
         1722  +  assert( !pBt->pCursor );
  1299   1723     sqlite3pager_close(pBt->pPager);
         1724  +  if( pBt->xFreeSchema && pBt->pSchema ){
         1725  +    pBt->xFreeSchema(pBt->pSchema);
         1726  +  }
         1727  +  sqliteFree(pBt->pSchema);
  1300   1728     sqliteFree(pBt);
  1301   1729     return SQLITE_OK;
  1302   1730   }
  1303   1731   
  1304   1732   /*
  1305   1733   ** Change the busy handler callback function.
  1306   1734   */
  1307         -int sqlite3BtreeSetBusyHandler(Btree *pBt, BusyHandler *pHandler){
         1735  +int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
         1736  +  BtShared *pBt = p->pBt;
  1308   1737     pBt->pBusyHandler = pHandler;
  1309   1738     sqlite3pager_set_busyhandler(pBt->pPager, pHandler);
  1310   1739     return SQLITE_OK;
  1311   1740   }
  1312   1741   
  1313   1742   /*
  1314   1743   ** Change the limit on the number of pages allowed in the cache.
................................................................................
  1321   1750   ** and the database cannot be corrupted if this program
  1322   1751   ** crashes.  But if the operating system crashes or there is
  1323   1752   ** an abrupt power failure when synchronous is off, the database
  1324   1753   ** could be left in an inconsistent and unrecoverable state.
  1325   1754   ** Synchronous is on by default so database corruption is not
  1326   1755   ** normally a worry.
  1327   1756   */
  1328         -int sqlite3BtreeSetCacheSize(Btree *pBt, int mxPage){
         1757  +int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
         1758  +  BtShared *pBt = p->pBt;
  1329   1759     sqlite3pager_set_cachesize(pBt->pPager, mxPage);
  1330   1760     return SQLITE_OK;
  1331   1761   }
  1332   1762   
  1333   1763   /*
  1334   1764   ** Change the way data is synced to disk in order to increase or decrease
  1335   1765   ** how well the database resists damage due to OS crashes and power
  1336   1766   ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
  1337   1767   ** there is a high probability of damage)  Level 2 is the default.  There
  1338   1768   ** is a very low but non-zero probability of damage.  Level 3 reduces the
  1339   1769   ** probability of damage to near zero but with a write performance reduction.
  1340   1770   */
  1341   1771   #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  1342         -int sqlite3BtreeSetSafetyLevel(Btree *pBt, int level){
         1772  +int sqlite3BtreeSetSafetyLevel(Btree *p, int level){
         1773  +  BtShared *pBt = p->pBt;
  1343   1774     sqlite3pager_set_safety_level(pBt->pPager, level);
  1344   1775     return SQLITE_OK;
  1345   1776   }
  1346   1777   #endif
  1347   1778   
  1348   1779   /*
  1349   1780   ** Return TRUE if the given btree is set to safety level 1.  In other
  1350   1781   ** words, return TRUE if no sync() occurs on the disk files.
  1351   1782   */
  1352         -int sqlite3BtreeSyncDisabled(Btree *pBt){
         1783  +int sqlite3BtreeSyncDisabled(Btree *p){
         1784  +  BtShared *pBt = p->pBt;
  1353   1785     assert( pBt && pBt->pPager );
  1354   1786     return sqlite3pager_nosync(pBt->pPager);
  1355   1787   }
  1356   1788   
  1357   1789   #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  1358   1790   /*
  1359   1791   ** Change the default pages size and the number of reserved bytes per page.
................................................................................
  1366   1798   ** of the database file used for locking (beginning at PENDING_BYTE,
  1367   1799   ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  1368   1800   ** at the beginning of a page.
  1369   1801   **
  1370   1802   ** If parameter nReserve is less than zero, then the number of reserved
  1371   1803   ** bytes per page is left unchanged.
  1372   1804   */
  1373         -int sqlite3BtreeSetPageSize(Btree *pBt, int pageSize, int nReserve){
         1805  +int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
         1806  +  BtShared *pBt = p->pBt;
  1374   1807     if( pBt->pageSizeFixed ){
  1375   1808       return SQLITE_READONLY;
  1376   1809     }
  1377   1810     if( nReserve<0 ){
  1378   1811       nReserve = pBt->pageSize - pBt->usableSize;
  1379   1812     }
  1380   1813     if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  1381   1814           ((pageSize-1)&pageSize)==0 ){
  1382   1815       assert( (pageSize & 7)==0 );
         1816  +    assert( !pBt->pPage1 && !pBt->pCursor );
  1383   1817       pBt->pageSize = sqlite3pager_set_pagesize(pBt->pPager, pageSize);
  1384   1818     }
  1385   1819     pBt->usableSize = pBt->pageSize - nReserve;
  1386   1820     return SQLITE_OK;
  1387   1821   }
  1388   1822   
  1389   1823   /*
  1390   1824   ** Return the currently defined page size
  1391   1825   */
  1392         -int sqlite3BtreeGetPageSize(Btree *pBt){
  1393         -  return pBt->pageSize;
         1826  +int sqlite3BtreeGetPageSize(Btree *p){
         1827  +  return p->pBt->pageSize;
  1394   1828   }
  1395         -int sqlite3BtreeGetReserve(Btree *pBt){
  1396         -  return pBt->pageSize - pBt->usableSize;
         1829  +int sqlite3BtreeGetReserve(Btree *p){
         1830  +  return p->pBt->pageSize - p->pBt->usableSize;
  1397   1831   }
  1398   1832   #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  1399   1833   
  1400   1834   /*
  1401   1835   ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  1402   1836   ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  1403   1837   ** is disabled. The default value for the auto-vacuum property is 
  1404   1838   ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  1405   1839   */
  1406         -int sqlite3BtreeSetAutoVacuum(Btree *pBt, int autoVacuum){
         1840  +int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
         1841  +  BtShared *pBt = p->pBt;;
  1407   1842   #ifdef SQLITE_OMIT_AUTOVACUUM
  1408   1843     return SQLITE_READONLY;
  1409   1844   #else
  1410   1845     if( pBt->pageSizeFixed ){
  1411   1846       return SQLITE_READONLY;
  1412   1847     }
  1413   1848     pBt->autoVacuum = (autoVacuum?1:0);
................................................................................
  1415   1850   #endif
  1416   1851   }
  1417   1852   
  1418   1853   /*
  1419   1854   ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
  1420   1855   ** enabled 1 is returned. Otherwise 0.
  1421   1856   */
  1422         -int sqlite3BtreeGetAutoVacuum(Btree *pBt){
         1857  +int sqlite3BtreeGetAutoVacuum(Btree *p){
  1423   1858   #ifdef SQLITE_OMIT_AUTOVACUUM
  1424   1859     return 0;
  1425   1860   #else
  1426         -  return pBt->autoVacuum;
         1861  +  return p->pBt->autoVacuum;
  1427   1862   #endif
  1428   1863   }
  1429   1864   
  1430   1865   
  1431   1866   /*
  1432   1867   ** Get a reference to pPage1 of the database file.  This will
  1433   1868   ** also acquire a readlock on that file.
................................................................................
  1434   1869   **
  1435   1870   ** SQLITE_OK is returned on success.  If the file is not a
  1436   1871   ** well-formed database file, then SQLITE_CORRUPT is returned.
  1437   1872   ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
  1438   1873   ** is returned if we run out of memory.  SQLITE_PROTOCOL is returned
  1439   1874   ** if there is a locking protocol violation.
  1440   1875   */
  1441         -static int lockBtree(Btree *pBt){
         1876  +static int lockBtree(BtShared *pBt){
  1442   1877     int rc, pageSize;
  1443   1878     MemPage *pPage1;
  1444   1879     if( pBt->pPage1 ) return SQLITE_OK;
  1445   1880     rc = getPage(pBt, 1, &pPage1);
  1446   1881     if( rc!=SQLITE_OK ) return rc;
  1447   1882     
  1448   1883   
................................................................................
  1506   1941     return rc;
  1507   1942   }
  1508   1943   
  1509   1944   /*
  1510   1945   ** This routine works like lockBtree() except that it also invokes the
  1511   1946   ** busy callback if there is lock contention.
  1512   1947   */
  1513         -static int lockBtreeWithRetry(Btree *pBt){
         1948  +static int lockBtreeWithRetry(Btree *pRef){
  1514   1949     int rc = SQLITE_OK;
  1515         -  if( pBt->inTrans==TRANS_NONE ){
  1516         -    rc = sqlite3BtreeBeginTrans(pBt, 0);
  1517         -    pBt->inTrans = TRANS_NONE;
         1950  +  if( pRef->inTrans==TRANS_NONE ){
         1951  +    u8 inTransaction = pRef->pBt->inTransaction;
         1952  +    btreeIntegrity(pRef);
         1953  +    rc = sqlite3BtreeBeginTrans(pRef, 0);
         1954  +    pRef->pBt->inTransaction = inTransaction;
         1955  +    pRef->inTrans = TRANS_NONE;
         1956  +    if( rc==SQLITE_OK ){
         1957  +      pRef->pBt->nTransaction--;
         1958  +    }
         1959  +    btreeIntegrity(pRef);
  1518   1960     }
  1519   1961     return rc;
  1520   1962   }
  1521   1963          
  1522   1964   
  1523   1965   /*
  1524   1966   ** If there are no outstanding cursors and we are not in the middle
................................................................................
  1526   1968   ** this routine unrefs the first page of the database file which 
  1527   1969   ** has the effect of releasing the read lock.
  1528   1970   **
  1529   1971   ** If there are any outstanding cursors, this routine is a no-op.
  1530   1972   **
  1531   1973   ** If there is a transaction in progress, this routine is a no-op.
  1532   1974   */
  1533         -static void unlockBtreeIfUnused(Btree *pBt){
  1534         -  if( pBt->inTrans==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
         1975  +static void unlockBtreeIfUnused(BtShared *pBt){
         1976  +  if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
  1535   1977       if( pBt->pPage1->aData==0 ){
  1536   1978         MemPage *pPage = pBt->pPage1;
  1537         -      pPage->aData = &((char*)pPage)[-pBt->pageSize];
         1979  +      pPage->aData = &((u8*)pPage)[-pBt->pageSize];
  1538   1980         pPage->pBt = pBt;
  1539   1981         pPage->pgno = 1;
  1540   1982       }
  1541   1983       releasePage(pBt->pPage1);
  1542   1984       pBt->pPage1 = 0;
  1543   1985       pBt->inStmt = 0;
  1544   1986     }
  1545   1987   }
  1546   1988   
  1547   1989   /*
  1548   1990   ** Create a new database by initializing the first page of the
  1549   1991   ** file.
  1550   1992   */
  1551         -static int newDatabase(Btree *pBt){
         1993  +static int newDatabase(BtShared *pBt){
  1552   1994     MemPage *pP1;
  1553   1995     unsigned char *data;
  1554   1996     int rc;
  1555   1997     if( sqlite3pager_pagecount(pBt->pPager)>0 ) return SQLITE_OK;
  1556   1998     pP1 = pBt->pPage1;
  1557   1999     assert( pP1!=0 );
  1558   2000     data = pP1->aData;
................................................................................
  1609   2051   ** a reserved lock.  B tries to promote to exclusive but is blocked because
  1610   2052   ** of A's read lock.  A tries to promote to reserved but is blocked by B.
  1611   2053   ** One or the other of the two processes must give way or there can be
  1612   2054   ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
  1613   2055   ** when A already has a read lock, we encourage A to give up and let B
  1614   2056   ** proceed.
  1615   2057   */
  1616         -int sqlite3BtreeBeginTrans(Btree *pBt, int wrflag){
         2058  +int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
         2059  +  BtShared *pBt = p->pBt;
  1617   2060     int rc = SQLITE_OK;
         2061  +
         2062  +  btreeIntegrity(p);
  1618   2063   
  1619   2064     /* If the btree is already in a write-transaction, or it
  1620   2065     ** is already in a read-transaction and a read-transaction
  1621   2066     ** is requested, this is a no-op.
  1622   2067     */
  1623         -  if( pBt->inTrans==TRANS_WRITE || (pBt->inTrans==TRANS_READ && !wrflag) ){
         2068  +  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  1624   2069       return SQLITE_OK;
  1625   2070     }
  1626   2071   
  1627   2072     /* Write transactions are not possible on a read-only database */
  1628   2073     if( pBt->readOnly && wrflag ){
  1629   2074       return SQLITE_READONLY;
  1630   2075     }
         2076  +
         2077  +  /* If another database handle has already opened a write transaction 
         2078  +  ** on this shared-btree structure and a second write transaction is
         2079  +  ** requested, return SQLITE_BUSY.
         2080  +  */
         2081  +  if( pBt->inTransaction==TRANS_WRITE && wrflag ){
         2082  +    return SQLITE_BUSY;
         2083  +  }
  1631   2084   
  1632   2085     do {
  1633   2086       if( pBt->pPage1==0 ){
  1634   2087         rc = lockBtree(pBt);
  1635   2088       }
  1636   2089     
  1637   2090       if( rc==SQLITE_OK && wrflag ){
................................................................................
  1638   2091         rc = sqlite3pager_begin(pBt->pPage1->aData, wrflag>1);
  1639   2092         if( rc==SQLITE_OK ){
  1640   2093           rc = newDatabase(pBt);
  1641   2094         }
  1642   2095       }
  1643   2096     
  1644   2097       if( rc==SQLITE_OK ){
  1645         -      pBt->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  1646   2098         if( wrflag ) pBt->inStmt = 0;
  1647   2099       }else{
  1648   2100         unlockBtreeIfUnused(pBt);
  1649   2101       }
  1650         -  }while( rc==SQLITE_BUSY && pBt->inTrans==TRANS_NONE &&
         2102  +  }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  1651   2103             sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
         2104  +
         2105  +  if( rc==SQLITE_OK ){
         2106  +    if( p->inTrans==TRANS_NONE ){
         2107  +      pBt->nTransaction++;
         2108  +    }
         2109  +    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
         2110  +    if( p->inTrans>pBt->inTransaction ){
         2111  +      pBt->inTransaction = p->inTrans;
         2112  +    }
         2113  +  }
         2114  +
         2115  +  btreeIntegrity(p);
  1652   2116     return rc;
  1653   2117   }
  1654   2118   
  1655   2119   #ifndef SQLITE_OMIT_AUTOVACUUM
  1656   2120   
  1657   2121   /*
  1658   2122   ** Set the pointer-map entries for all children of page pPage. Also, if
................................................................................
  1659   2123   ** pPage contains cells that point to overflow pages, set the pointer
  1660   2124   ** map entries for the overflow pages as well.
  1661   2125   */
  1662   2126   static int setChildPtrmaps(MemPage *pPage){
  1663   2127     int i;                             /* Counter variable */
  1664   2128     int nCell;                         /* Number of cells in page pPage */
  1665   2129     int rc = SQLITE_OK;                /* Return code */
  1666         -  Btree *pBt = pPage->pBt;
         2130  +  BtShared *pBt = pPage->pBt;
  1667   2131     int isInitOrig = pPage->isInit;
  1668   2132     Pgno pgno = pPage->pgno;
  1669   2133   
  1670   2134     initPage(pPage, 0);
  1671   2135     nCell = pPage->nCell;
  1672   2136   
  1673   2137     for(i=0; i<nCell; i++){
................................................................................
  1759   2223   
  1760   2224   
  1761   2225   /*
  1762   2226   ** Move the open database page pDbPage to location iFreePage in the 
  1763   2227   ** database. The pDbPage reference remains valid.
  1764   2228   */
  1765   2229   static int relocatePage(
  1766         -  Btree *pBt,              /* Btree */
         2230  +  BtShared *pBt,           /* Btree */
  1767   2231     MemPage *pDbPage,        /* Open page to move */
  1768   2232     u8 eType,                /* Pointer map 'type' entry for pDbPage */
  1769   2233     Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
  1770   2234     Pgno iFreePage           /* The location to move pDbPage to */
  1771   2235   ){
  1772   2236     MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
  1773   2237     Pgno iDbPage = pDbPage->pgno;
................................................................................
  1829   2293         rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
  1830   2294       }
  1831   2295     }
  1832   2296     return rc;
  1833   2297   }
  1834   2298   
  1835   2299   /* Forward declaration required by autoVacuumCommit(). */
  1836         -static int allocatePage(Btree *, MemPage **, Pgno *, Pgno, u8);
         2300  +static int allocatePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  1837   2301   
  1838   2302   /*
  1839   2303   ** This routine is called prior to sqlite3pager_commit when a transaction
  1840   2304   ** is commited for an auto-vacuum database.
  1841   2305   */
  1842         -static int autoVacuumCommit(Btree *pBt, Pgno *nTrunc){
         2306  +static int autoVacuumCommit(BtShared *pBt, Pgno *nTrunc){
  1843   2307     Pager *pPager = pBt->pPager;
  1844         -  Pgno nFreeList;   /* Number of pages remaining on the free-list. */
  1845         -  int nPtrMap;      /* Number of pointer-map pages deallocated */
  1846         -  Pgno origSize;  /* Pages in the database file */
  1847         -  Pgno finSize;   /* Pages in the database file after truncation */
  1848         -  int rc;           /* Return code */
         2308  +  Pgno nFreeList;            /* Number of pages remaining on the free-list. */
         2309  +  int nPtrMap;               /* Number of pointer-map pages deallocated */
         2310  +  Pgno origSize;             /* Pages in the database file */
         2311  +  Pgno finSize;              /* Pages in the database file after truncation */
         2312  +  int rc;                    /* Return code */
  1849   2313     u8 eType;
  1850   2314     int pgsz = pBt->pageSize;  /* Page size for this database */
  1851   2315     Pgno iDbPage;              /* The database page to move */
  1852   2316     MemPage *pDbMemPage = 0;   /* "" */
  1853   2317     Pgno iPtrPage;             /* The page that contains a pointer to iDbPage */
  1854   2318     Pgno iFreePage;            /* The free-list page to move iDbPage to */
  1855   2319     MemPage *pFreeMemPage = 0; /* "" */
................................................................................
  1924   2388           goto autovacuum_out;
  1925   2389         }
  1926   2390         assert( iFreePage<=origSize );
  1927   2391       }while( iFreePage>finSize );
  1928   2392       releasePage(pFreeMemPage);
  1929   2393       pFreeMemPage = 0;
  1930   2394   
         2395  +    /* Relocate the page into the body of the file. Note that although the 
         2396  +    ** page has moved within the database file, the pDbMemPage pointer 
         2397  +    ** remains valid. This means that this function can run without
         2398  +    ** invalidating cursors open on the btree. This is important in 
         2399  +    ** shared-cache mode.
         2400  +    */
  1931   2401       rc = relocatePage(pBt, pDbMemPage, eType, iPtrPage, iFreePage);
  1932   2402       releasePage(pDbMemPage);
  1933   2403       if( rc!=SQLITE_OK ) goto autovacuum_out;
  1934   2404     }
  1935   2405   
  1936   2406     /* The entire free-list has been swapped to the end of the file. So
  1937   2407     ** truncate the database file to finSize pages and consider the
................................................................................
  1955   2425   
  1956   2426   /*
  1957   2427   ** Commit the transaction currently in progress.
  1958   2428   **
  1959   2429   ** This will release the write lock on the database file.  If there
  1960   2430   ** are no active cursors, it also releases the read lock.
  1961   2431   */
  1962         -int sqlite3BtreeCommit(Btree *pBt){
         2432  +int sqlite3BtreeCommit(Btree *p){
  1963   2433     int rc = SQLITE_OK;
  1964         -  if( pBt->inTrans==TRANS_WRITE ){
         2434  +  BtShared *pBt = p->pBt;
         2435  +
         2436  +  btreeIntegrity(p);
         2437  +  unlockAllTables(p);
         2438  +
         2439  +  /* If the handle has a write-transaction open, commit the shared-btrees 
         2440  +  ** transaction and set the shared state to TRANS_READ.
         2441  +  */
         2442  +  if( p->inTrans==TRANS_WRITE ){
         2443  +    assert( pBt->inTransaction==TRANS_WRITE );
         2444  +    assert( pBt->nTransaction>0 );
  1965   2445       rc = sqlite3pager_commit(pBt->pPager);
         2446  +    pBt->inTransaction = TRANS_READ;
         2447  +    pBt->inStmt = 0;
  1966   2448     }
  1967         -  pBt->inTrans = TRANS_NONE;
  1968         -  pBt->inStmt = 0;
         2449  +
         2450  +  /* If the handle has any kind of transaction open, decrement the transaction
         2451  +  ** count of the shared btree. If the transaction count reaches 0, set
         2452  +  ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
         2453  +  ** will unlock the pager.
         2454  +  */
         2455  +  if( p->inTrans!=TRANS_NONE ){
         2456  +    pBt->nTransaction--;
         2457  +    if( 0==pBt->nTransaction ){
         2458  +      pBt->inTransaction = TRANS_NONE;
         2459  +    }
         2460  +  }
         2461  +
         2462  +  /* Set the handles current transaction state to TRANS_NONE and unlock
         2463  +  ** the pager if this call closed the only read or write transaction.
         2464  +  */
         2465  +  p->inTrans = TRANS_NONE;
  1969   2466     unlockBtreeIfUnused(pBt);
         2467  +
         2468  +  btreeIntegrity(p);
  1970   2469     return rc;
  1971   2470   }
  1972   2471   
  1973   2472   #ifndef NDEBUG
  1974   2473   /*
  1975   2474   ** Return the number of write-cursors open on this handle. This is for use
  1976   2475   ** in assert() expressions, so it is only compiled if NDEBUG is not
  1977   2476   ** defined.
  1978   2477   */
  1979         -static int countWriteCursors(Btree *pBt){
         2478  +static int countWriteCursors(BtShared *pBt){
  1980   2479     BtCursor *pCur;
  1981   2480     int r = 0;
  1982   2481     for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  1983         -    if( pCur->wrFlag ) r++;
         2482  +    if( pCur->wrFlag ) r++; 
  1984   2483     }
  1985   2484     return r;
  1986   2485   }
  1987   2486   #endif
  1988   2487   
  1989   2488   #ifdef SQLITE_TEST
  1990   2489   /*
  1991   2490   ** Print debugging information about all cursors to standard output.
  1992   2491   */
  1993         -void sqlite3BtreeCursorList(Btree *pBt){
         2492  +void sqlite3BtreeCursorList(Btree *p){
  1994   2493     BtCursor *pCur;
         2494  +  BtShared *pBt = p->pBt;
  1995   2495     for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  1996   2496       MemPage *pPage = pCur->pPage;
  1997   2497       char *zMode = pCur->wrFlag ? "rw" : "ro";
  1998   2498       sqlite3DebugPrintf("CURSOR %p rooted at %4d(%s) currently at %d.%d%s\n",
  1999   2499          pCur, pCur->pgnoRoot, zMode,
  2000   2500          pPage ? pPage->pgno : 0, pCur->idx,
  2001         -       pCur->isValid ? "" : " eof"
         2501  +       (pCur->eState==CURSOR_VALID) ? "" : " eof"
  2002   2502       );
  2003   2503     }
  2004   2504   }
  2005   2505   #endif
  2006   2506   
  2007   2507   /*
  2008   2508   ** Rollback the transaction in progress.  All cursors will be
................................................................................
  2009   2509   ** invalided by this operation.  Any attempt to use a cursor
  2010   2510   ** that was open at the beginning of this operation will result
  2011   2511   ** in an error.
  2012   2512   **
  2013   2513   ** This will release the write lock on the database file.  If there
  2014   2514   ** are no active cursors, it also releases the read lock.
  2015   2515   */
  2016         -int sqlite3BtreeRollback(Btree *pBt){
         2516  +int sqlite3BtreeRollback(Btree *p){
  2017   2517     int rc = SQLITE_OK;
         2518  +  BtShared *pBt = p->pBt;
  2018   2519     MemPage *pPage1;
  2019         -  if( pBt->inTrans==TRANS_WRITE ){
         2520  +
         2521  +  btreeIntegrity(p);
         2522  +  unlockAllTables(p);
         2523  +
         2524  +  if( p->inTrans==TRANS_WRITE ){
         2525  +    assert( TRANS_WRITE==pBt->inTransaction );
         2526  +
  2020   2527       rc = sqlite3pager_rollback(pBt->pPager);
  2021   2528       /* The rollback may have destroyed the pPage1->aData value.  So
  2022   2529       ** call getPage() on page 1 again to make sure pPage1->aData is
  2023   2530       ** set correctly. */
  2024   2531       if( getPage(pBt, 1, &pPage1)==SQLITE_OK ){
  2025   2532         releasePage(pPage1);
  2026   2533       }
  2027   2534       assert( countWriteCursors(pBt)==0 );
         2535  +    pBt->inTransaction = TRANS_READ;
  2028   2536     }
  2029         -  pBt->inTrans = TRANS_NONE;
         2537  +
         2538  +  if( p->inTrans!=TRANS_NONE ){
         2539  +    assert( pBt->nTransaction>0 );
         2540  +    pBt->nTransaction--;
         2541  +    if( 0==pBt->nTransaction ){
         2542  +      pBt->inTransaction = TRANS_NONE;
         2543  +    }
         2544  +  }
         2545  +
         2546  +  p->inTrans = TRANS_NONE;
  2030   2547     pBt->inStmt = 0;
  2031   2548     unlockBtreeIfUnused(pBt);
         2549  +
         2550  +  btreeIntegrity(p);
  2032   2551     return rc;
  2033   2552   }
  2034   2553   
  2035   2554   /*
  2036   2555   ** Start a statement subtransaction.  The subtransaction can
  2037   2556   ** can be rolled back independently of the main transaction.
  2038   2557   ** You must start a transaction before starting a subtransaction.
................................................................................
  2043   2562   ** to start a new subtransaction if another subtransaction is already active.
  2044   2563   **
  2045   2564   ** Statement subtransactions are used around individual SQL statements
  2046   2565   ** that are contained within a BEGIN...COMMIT block.  If a constraint
  2047   2566   ** error occurs within the statement, the effect of that one statement
  2048   2567   ** can be rolled back without having to rollback the entire transaction.
  2049   2568   */
  2050         -int sqlite3BtreeBeginStmt(Btree *pBt){
         2569  +int sqlite3BtreeBeginStmt(Btree *p){
  2051   2570     int rc;
  2052         -  if( (pBt->inTrans!=TRANS_WRITE) || pBt->inStmt ){
         2571  +  BtShared *pBt = p->pBt;
         2572  +  if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
  2053   2573       return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  2054   2574     }
         2575  +  assert( pBt->inTransaction==TRANS_WRITE );
  2055   2576     rc = pBt->readOnly ? SQLITE_OK : sqlite3pager_stmt_begin(pBt->pPager);
  2056   2577     pBt->inStmt = 1;
  2057   2578     return rc;
  2058   2579   }
  2059   2580   
  2060   2581   
  2061   2582   /*
  2062   2583   ** Commit the statment subtransaction currently in progress.  If no
  2063   2584   ** subtransaction is active, this is a no-op.
  2064   2585   */
  2065         -int sqlite3BtreeCommitStmt(Btree *pBt){
         2586  +int sqlite3BtreeCommitStmt(Btree *p){
  2066   2587     int rc;
         2588  +  BtShared *pBt = p->pBt;
  2067   2589     if( pBt->inStmt && !pBt->readOnly ){
  2068   2590       rc = sqlite3pager_stmt_commit(pBt->pPager);
  2069   2591     }else{
  2070   2592       rc = SQLITE_OK;
  2071   2593     }
  2072   2594     pBt->inStmt = 0;
  2073   2595     return rc;
................................................................................
  2077   2599   ** Rollback the active statement subtransaction.  If no subtransaction
  2078   2600   ** is active this routine is a no-op.
  2079   2601   **
  2080   2602   ** All cursors will be invalidated by this operation.  Any attempt
  2081   2603   ** to use a cursor that was open at the beginning of this operation
  2082   2604   ** will result in an error.
  2083   2605   */
  2084         -int sqlite3BtreeRollbackStmt(Btree *pBt){
         2606  +int sqlite3BtreeRollbackStmt(Btree *p){
  2085   2607     int rc;
         2608  +  BtShared *pBt = p->pBt;
  2086   2609     if( pBt->inStmt==0 || pBt->readOnly ) return SQLITE_OK;
  2087   2610     rc = sqlite3pager_stmt_rollback(pBt->pPager);
  2088   2611     assert( countWriteCursors(pBt)==0 );
  2089   2612     pBt->inStmt = 0;
  2090   2613     return rc;
  2091   2614   }
  2092   2615   
................................................................................
  2146   2669   ** The comparison function must be logically the same for every cursor
  2147   2670   ** on a particular table.  Changing the comparison function will result
  2148   2671   ** in incorrect operations.  If the comparison function is NULL, a
  2149   2672   ** default comparison function is used.  The comparison function is
  2150   2673   ** always ignored for INTKEY tables.
  2151   2674   */
  2152   2675   int sqlite3BtreeCursor(
  2153         -  Btree *pBt,                                 /* The btree */
         2676  +  Btree *p,                                   /* The btree */
  2154   2677     int iTable,                                 /* Root page of table to open */
  2155   2678     int wrFlag,                                 /* 1 to write. 0 read-only */
  2156   2679     int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
  2157   2680     void *pArg,                                 /* First arg to xCompare() */
  2158   2681     BtCursor **ppCur                            /* Write new cursor here */
  2159   2682   ){
  2160   2683     int rc;
  2161   2684     BtCursor *pCur;
         2685  +  BtShared *pBt = p->pBt;
  2162   2686   
  2163   2687     *ppCur = 0;
  2164   2688     if( wrFlag ){
  2165   2689       if( pBt->readOnly ){
  2166   2690         return SQLITE_READONLY;
  2167   2691       }
  2168   2692       if( checkReadLocks(pBt, iTable, 0) ){
  2169   2693         return SQLITE_LOCKED;
  2170   2694       }
  2171   2695     }
         2696  +
  2172   2697     if( pBt->pPage1==0 ){
  2173         -    rc = lockBtreeWithRetry(pBt);
         2698  +    rc = lockBtreeWithRetry(p);
  2174   2699       if( rc!=SQLITE_OK ){
  2175   2700         return rc;
  2176   2701       }
  2177   2702     }
  2178         -  pCur = sqliteMallocRaw( sizeof(*pCur) );
         2703  +  pCur = sqliteMalloc( sizeof(*pCur) );
  2179   2704     if( pCur==0 ){
  2180   2705       rc = SQLITE_NOMEM;
  2181   2706       goto create_cursor_exception;
  2182   2707     }
  2183   2708     pCur->pgnoRoot = (Pgno)iTable;
  2184   2709     pCur->pPage = 0;  /* For exit-handler, in case getAndInitPage() fails. */
  2185   2710     if( iTable==1 && sqlite3pager_pagecount(pBt->pPager)==0 ){
................................................................................
  2186   2711       rc = SQLITE_EMPTY;
  2187   2712       goto create_cursor_exception;
  2188   2713     }
  2189   2714     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
  2190   2715     if( rc!=SQLITE_OK ){
  2191   2716       goto create_cursor_exception;
  2192   2717     }
         2718  +
         2719  +  /* Now that no other errors can occur, finish filling in the BtCursor
         2720  +  ** variables, link the cursor into the BtShared list and set *ppCur (the
         2721  +  ** output argument to this function).
         2722  +  */
  2193   2723     pCur->xCompare = xCmp ? xCmp : dfltCompare;
  2194   2724     pCur->pArg = pArg;
  2195         -  pCur->pBt = pBt;
         2725  +  pCur->pBtree = p;
  2196   2726     pCur->wrFlag = wrFlag;
  2197   2727     pCur->idx = 0;
  2198   2728     memset(&pCur->info, 0, sizeof(pCur->info));
  2199   2729     pCur->pNext = pBt->pCursor;
  2200   2730     if( pCur->pNext ){
  2201   2731       pCur->pNext->pPrev = pCur;
  2202   2732     }
  2203   2733     pCur->pPrev = 0;
  2204   2734     pBt->pCursor = pCur;
  2205         -  pCur->isValid = 0;
         2735  +  pCur->eState = CURSOR_INVALID;
  2206   2736     *ppCur = pCur;
         2737  +
  2207   2738     return SQLITE_OK;
  2208         -
  2209   2739   create_cursor_exception:
  2210   2740     if( pCur ){
  2211   2741       releasePage(pCur->pPage);
  2212   2742       sqliteFree(pCur);
  2213   2743     }
  2214   2744     unlockBtreeIfUnused(pBt);
  2215   2745     return rc;
................................................................................
  2230   2760   #endif
  2231   2761   
  2232   2762   /*
  2233   2763   ** Close a cursor.  The read lock on the database file is released
  2234   2764   ** when the last cursor is closed.
  2235   2765   */
  2236   2766   int sqlite3BtreeCloseCursor(BtCursor *pCur){
  2237         -  Btree *pBt = pCur->pBt;
         2767  +  BtShared *pBt = pCur->pBtree->pBt;
         2768  +  restoreCursorPosition(pCur, 0);
  2238   2769     if( pCur->pPrev ){
  2239   2770       pCur->pPrev->pNext = pCur->pNext;
  2240   2771     }else{
  2241   2772       pBt->pCursor = pCur->pNext;
  2242   2773     }
  2243   2774     if( pCur->pNext ){
  2244   2775       pCur->pNext->pPrev = pCur->pPrev;
................................................................................
  2297   2828   ** the key for the current entry.  If the cursor is not pointing
  2298   2829   ** to a valid entry, *pSize is set to 0. 
  2299   2830   **
  2300   2831   ** For a table with the INTKEY flag set, this routine returns the key
  2301   2832   ** itself, not the number of bytes in the key.
  2302   2833   */
  2303   2834   int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  2304         -  if( !pCur->isValid ){
  2305         -    *pSize = 0;
  2306         -  }else{
  2307         -    getCellInfo(pCur);
  2308         -    *pSize = pCur->info.nKey;
         2835  +  int rc = restoreCursorPosition(pCur, 1);
         2836  +  if( rc==SQLITE_OK ){
         2837  +    assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
         2838  +    if( pCur->eState==CURSOR_INVALID ){
         2839  +      *pSize = 0;
         2840  +    }else{
         2841  +      getCellInfo(pCur);
         2842  +      *pSize = pCur->info.nKey;
         2843  +    }
  2309   2844     }
  2310         -  return SQLITE_OK;
         2845  +  return rc;
  2311   2846   }
  2312   2847   
  2313   2848   /*
  2314   2849   ** Set *pSize to the number of bytes of data in the entry the
  2315   2850   ** cursor currently points to.  Always return SQLITE_OK.
  2316   2851   ** Failure is not possible.  If the cursor is not currently
  2317   2852   ** pointing to an entry (which can happen, for example, if
  2318   2853   ** the database is empty) then *pSize is set to 0.
  2319   2854   */
  2320   2855   int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  2321         -  if( !pCur->isValid ){
  2322         -    /* Not pointing at a valid entry - set *pSize to 0. */
  2323         -    *pSize = 0;
  2324         -  }else{
  2325         -    getCellInfo(pCur);
  2326         -    *pSize = pCur->info.nData;
         2856  +  int rc = restoreCursorPosition(pCur, 1);
         2857  +  if( rc==SQLITE_OK ){
         2858  +    assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
         2859  +    if( pCur->eState==CURSOR_INVALID ){
         2860  +      /* Not pointing at a valid entry - set *pSize to 0. */
         2861  +      *pSize = 0;
         2862  +    }else{
         2863  +      getCellInfo(pCur);
         2864  +      *pSize = pCur->info.nData;
         2865  +    }
  2327   2866     }
  2328         -  return SQLITE_OK;
         2867  +  return rc;
  2329   2868   }
  2330   2869   
  2331   2870   /*
  2332   2871   ** Read payload information from the entry that the pCur cursor is
  2333   2872   ** pointing to.  Begin reading the payload at "offset" and read
  2334   2873   ** a total of "amt" bytes.  Put the result in zBuf.
  2335   2874   **
................................................................................
  2344   2883     unsigned char *pBuf, /* Write the bytes into this buffer */ 
  2345   2884     int skipKey          /* offset begins at data if this is true */
  2346   2885   ){
  2347   2886     unsigned char *aPayload;
  2348   2887     Pgno nextPage;
  2349   2888     int rc;
  2350   2889     MemPage *pPage;
  2351         -  Btree *pBt;
         2890  +  BtShared *pBt;
  2352   2891     int ovflSize;
  2353   2892     u32 nKey;
  2354   2893   
  2355   2894     assert( pCur!=0 && pCur->pPage!=0 );
  2356         -  assert( pCur->isValid );
  2357         -  pBt = pCur->pBt;
         2895  +  assert( pCur->eState==CURSOR_VALID );
         2896  +  pBt = pCur->pBtree->pBt;
  2358   2897     pPage = pCur->pPage;
  2359   2898     pageIntegrity(pPage);
  2360   2899     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
  2361   2900     getCellInfo(pCur);
  2362   2901     aPayload = pCur->info.pCell;
  2363   2902     aPayload += pCur->info.nHeader;
  2364   2903     if( pPage->intKey ){
................................................................................
  2425   2964   ** begins at "offset".
  2426   2965   **
  2427   2966   ** Return SQLITE_OK on success or an error code if anything goes
  2428   2967   ** wrong.  An error is returned if "offset+amt" is larger than
  2429   2968   ** the available payload.
  2430   2969   */
  2431   2970   int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  2432         -  assert( pCur->isValid );
  2433         -  assert( pCur->pPage!=0 );
  2434         -  if( pCur->pPage->intKey ){
  2435         -    return SQLITE_CORRUPT_BKPT;
         2971  +  int rc = restoreCursorPosition(pCur, 1);
         2972  +  if( rc==SQLITE_OK ){
         2973  +    assert( pCur->eState==CURSOR_VALID );
         2974  +    assert( pCur->pPage!=0 );
         2975  +    if( pCur->pPage->intKey ){
         2976  +      return SQLITE_CORRUPT_BKPT;
         2977  +    }
         2978  +    assert( pCur->pPage->intKey==0 );
         2979  +    assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
         2980  +    rc = getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  2436   2981     }
  2437         -  assert( pCur->pPage->intKey==0 );
  2438         -  assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
  2439         -  return getPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
         2982  +  return rc;
  2440   2983   }
  2441   2984   
  2442   2985   /*
  2443   2986   ** Read part of the data associated with cursor pCur.  Exactly
  2444   2987   ** "amt" bytes will be transfered into pBuf[].  The transfer
  2445   2988   ** begins at "offset".
  2446   2989   **
  2447   2990   ** Return SQLITE_OK on success or an error code if anything goes
  2448   2991   ** wrong.  An error is returned if "offset+amt" is larger than
  2449   2992   ** the available payload.
  2450   2993   */
  2451   2994   int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  2452         -  assert( pCur->isValid );
  2453         -  assert( pCur->pPage!=0 );
  2454         -  assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
  2455         -  return getPayload(pCur, offset, amt, pBuf, 1);
         2995  +  int rc = restoreCursorPosition(pCur, 1);
         2996  +  if( rc==SQLITE_OK ){
         2997  +    assert( pCur->eState==CURSOR_VALID );
         2998  +    assert( pCur->pPage!=0 );
         2999  +    assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
         3000  +    rc = getPayload(pCur, offset, amt, pBuf, 1);
         3001  +  }
         3002  +  return rc;
  2456   3003   }
  2457   3004   
  2458   3005   /*
  2459   3006   ** Return a pointer to payload information from the entry that the 
  2460   3007   ** pCur cursor is pointing to.  The pointer is to the beginning of
  2461   3008   ** the key if skipKey==0 and it points to the beginning of data if
  2462   3009   ** skipKey==1.  The number of bytes of available key/data is written
................................................................................
  2481   3028   ){
  2482   3029     unsigned char *aPayload;
  2483   3030     MemPage *pPage;
  2484   3031     u32 nKey;
  2485   3032     int nLocal;
  2486   3033   
  2487   3034     assert( pCur!=0 && pCur->pPage!=0 );
  2488         -  assert( pCur->isValid );
         3035  +  assert( pCur->eState==CURSOR_VALID );
  2489   3036     pPage = pCur->pPage;
  2490   3037     pageIntegrity(pPage);
  2491   3038     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
  2492   3039     getCellInfo(pCur);
  2493   3040     aPayload = pCur->info.pCell;
  2494   3041     aPayload += pCur->info.nHeader;
  2495   3042     if( pPage->intKey ){
................................................................................
  2519   3066   ** The pointer returned is ephemeral.  The key/data may move
  2520   3067   ** or be destroyed on the next call to any Btree routine.
  2521   3068   **
  2522   3069   ** These routines is used to get quick access to key and data
  2523   3070   ** in the common case where no overflow pages are used.
  2524   3071   */
  2525   3072   const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  2526         -  return (const void*)fetchPayload(pCur, pAmt, 0);
         3073  +  if( pCur->eState==CURSOR_VALID ){
         3074  +    return (const void*)fetchPayload(pCur, pAmt, 0);
         3075  +  }
         3076  +  return 0;
  2527   3077   }
  2528   3078   const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  2529         -  return (const void*)fetchPayload(pCur, pAmt, 1);
         3079  +  if( pCur->eState==CURSOR_VALID ){
         3080  +    return (const void*)fetchPayload(pCur, pAmt, 1);
         3081  +  }
         3082  +  return 0;
  2530   3083   }
  2531   3084   
  2532   3085   
  2533   3086   /*
  2534   3087   ** Move the cursor down to a new child page.  The newPgno argument is the
  2535   3088   ** page number of the child page to move to.
  2536   3089   */
  2537   3090   static int moveToChild(BtCursor *pCur, u32 newPgno){
  2538   3091     int rc;
  2539   3092     MemPage *pNewPage;
  2540   3093     MemPage *pOldPage;
  2541         -  Btree *pBt = pCur->pBt;
         3094  +  BtShared *pBt = pCur->pBtree->pBt;
  2542   3095   
  2543         -  assert( pCur->isValid );
         3096  +  assert( pCur->eState==CURSOR_VALID );
  2544   3097     rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
  2545   3098     if( rc ) return rc;
  2546   3099     pageIntegrity(pNewPage);
  2547   3100     pNewPage->idxParent = pCur->idx;
  2548   3101     pOldPage = pCur->pPage;
  2549   3102     pOldPage->idxShift = 0;
  2550   3103     releasePage(pOldPage);
................................................................................
  2583   3136   ** the largest cell index.
  2584   3137   */
  2585   3138   static void moveToParent(BtCursor *pCur){
  2586   3139     MemPage *pParent;
  2587   3140     MemPage *pPage;
  2588   3141     int idxParent;
  2589   3142   
  2590         -  assert( pCur->isValid );
         3143  +  assert( pCur->eState==CURSOR_VALID );
  2591   3144     pPage = pCur->pPage;
  2592   3145     assert( pPage!=0 );
  2593   3146     assert( !isRootPage(pPage) );
  2594   3147     pageIntegrity(pPage);
  2595   3148     pParent = pPage->pParent;
  2596   3149     assert( pParent!=0 );
  2597   3150     pageIntegrity(pParent);
................................................................................
  2606   3159   
  2607   3160   /*
  2608   3161   ** Move the cursor to the root page
  2609   3162   */
  2610   3163   static int moveToRoot(BtCursor *pCur){
  2611   3164     MemPage *pRoot;
  2612   3165     int rc;
  2613         -  Btree *pBt = pCur->pBt;
         3166  +  BtShared *pBt = pCur->pBtree->pBt;
  2614   3167   
  2615         -  rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0);
  2616         -  if( rc ){
  2617         -    pCur->isValid = 0;
         3168  +  if( 
         3169  +    SQLITE_OK!=(rc = restoreCursorPosition(pCur, 0)) ||
         3170  +    SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
         3171  +  ){
         3172  +    pCur->eState = CURSOR_INVALID;
  2618   3173       return rc;
  2619   3174     }
  2620   3175     releasePage(pCur->pPage);
  2621   3176     pageIntegrity(pRoot);
  2622   3177     pCur->pPage = pRoot;
  2623   3178     pCur->idx = 0;
  2624   3179     pCur->info.nSize = 0;
  2625   3180     if( pRoot->nCell==0 && !pRoot->leaf ){
  2626   3181       Pgno subpage;
  2627   3182       assert( pRoot->pgno==1 );
  2628   3183       subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  2629   3184       assert( subpage>0 );
  2630         -    pCur->isValid = 1;
         3185  +    pCur->eState = CURSOR_VALID;
  2631   3186       rc = moveToChild(pCur, subpage);
  2632   3187     }
  2633         -  pCur->isValid = pCur->pPage->nCell>0;
         3188  +  pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  2634   3189     return rc;
  2635   3190   }
  2636   3191   
  2637   3192   /*
  2638   3193   ** Move the cursor down to the left-most leaf entry beneath the
  2639   3194   ** entry to which it is currently pointing.
  2640   3195   */
  2641   3196   static int moveToLeftmost(BtCursor *pCur){
  2642   3197     Pgno pgno;
  2643   3198     int rc;
  2644   3199     MemPage *pPage;
  2645   3200   
  2646         -  assert( pCur->isValid );
         3201  +  assert( pCur->eState==CURSOR_VALID );
  2647   3202     while( !(pPage = pCur->pPage)->leaf ){
  2648   3203       assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
  2649   3204       pgno = get4byte(findCell(pPage, pCur->idx));
  2650   3205       rc = moveToChild(pCur, pgno);
  2651   3206       if( rc ) return rc;
  2652   3207     }
  2653   3208     return SQLITE_OK;
................................................................................
  2661   3216   ** finds the right-most entry beneath the *page*.
  2662   3217   */
  2663   3218   static int moveToRightmost(BtCursor *pCur){
  2664   3219     Pgno pgno;
  2665   3220     int rc;
  2666   3221     MemPage *pPage;
  2667   3222   
  2668         -  assert( pCur->isValid );
         3223  +  assert( pCur->eState==CURSOR_VALID );
  2669   3224     while( !(pPage = pCur->pPage)->leaf ){
  2670   3225       pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  2671   3226       pCur->idx = pPage->nCell;
  2672   3227       rc = moveToChild(pCur, pgno);
  2673   3228       if( rc ) return rc;
  2674   3229     }
  2675   3230     pCur->idx = pPage->nCell - 1;
................................................................................
  2681   3236   ** on success.  Set *pRes to 0 if the cursor actually points to something
  2682   3237   ** or set *pRes to 1 if the table is empty.
  2683   3238   */
  2684   3239   int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  2685   3240     int rc;
  2686   3241     rc = moveToRoot(pCur);
  2687   3242     if( rc ) return rc;
  2688         -  if( pCur->isValid==0 ){
         3243  +  if( pCur->eState==CURSOR_INVALID ){
  2689   3244       assert( pCur->pPage->nCell==0 );
  2690   3245       *pRes = 1;
  2691   3246       return SQLITE_OK;
  2692   3247     }
  2693   3248     assert( pCur->pPage->nCell>0 );
  2694   3249     *pRes = 0;
  2695   3250     rc = moveToLeftmost(pCur);
................................................................................
  2700   3255   ** on success.  Set *pRes to 0 if the cursor actually points to something
  2701   3256   ** or set *pRes to 1 if the table is empty.
  2702   3257   */
  2703   3258   int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  2704   3259     int rc;
  2705   3260     rc = moveToRoot(pCur);
  2706   3261     if( rc ) return rc;
  2707         -  if( pCur->isValid==0 ){
         3262  +  if( CURSOR_INVALID==pCur->eState ){
  2708   3263       assert( pCur->pPage->nCell==0 );
  2709   3264       *pRes = 1;
  2710   3265       return SQLITE_OK;
  2711   3266     }
  2712         -  assert( pCur->isValid );
         3267  +  assert( pCur->eState==CURSOR_VALID );
  2713   3268     *pRes = 0;
  2714   3269     rc = moveToRightmost(pCur);
  2715   3270     return rc;
  2716   3271   }
  2717   3272   
  2718   3273   /* Move the cursor so that it points to an entry near pKey/nKey.
  2719   3274   ** Return a success code.
  2720   3275   **
  2721   3276   ** For INTKEY tables, only the nKey parameter is used.  pKey is
  2722   3277   ** ignored.  For other tables, nKey is the number of bytes of data
  2723         -** in nKey.  The comparison function specified when the cursor was
         3278  +** in pKey.  The comparison function specified when the cursor was
  2724   3279   ** created is used to compare keys.
  2725   3280   **
  2726   3281   ** If an exact match is not found, then the cursor is always
  2727   3282   ** left pointing at a leaf page which would hold the entry if it
  2728   3283   ** were present.  The cursor might point to an entry that comes
  2729   3284   ** before or after the key.
  2730   3285   **
................................................................................
  2744   3299   */
  2745   3300   int sqlite3BtreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int *pRes){
  2746   3301     int rc;
  2747   3302     rc = moveToRoot(pCur);
  2748   3303     if( rc ) return rc;
  2749   3304     assert( pCur->pPage );
  2750   3305     assert( pCur->pPage->isInit );
  2751         -  if( pCur->isValid==0 ){
         3306  +  if( pCur->eState==CURSOR_INVALID ){
  2752   3307       *pRes = -1;
  2753   3308       assert( pCur->pPage->nCell==0 );
  2754   3309       return SQLITE_OK;
  2755   3310     }
  2756   3311      for(;;){
  2757   3312       int lwr, upr;
  2758   3313       Pgno chldPg;
................................................................................
  2836   3391   ** Return TRUE if the cursor is not pointing at an entry of the table.
  2837   3392   **
  2838   3393   ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  2839   3394   ** past the last entry in the table or sqlite3BtreePrev() moves past
  2840   3395   ** the first entry.  TRUE is also returned if the table is empty.
  2841   3396   */
  2842   3397   int sqlite3BtreeEof(BtCursor *pCur){
  2843         -  return pCur->isValid==0;
         3398  +  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
         3399  +  ** have been deleted? This API will need to change to return an error code
         3400  +  ** as well as the boolean result value.
         3401  +  */
         3402  +  return (CURSOR_VALID!=pCur->eState);
  2844   3403   }
  2845   3404   
  2846   3405   /*
  2847   3406   ** Advance the cursor to the next entry in the database.  If
  2848   3407   ** successful then set *pRes=0.  If the cursor
  2849   3408   ** was already pointing to the last entry in the database before
  2850   3409   ** this routine was called, then set *pRes=1.
  2851   3410   */
  2852   3411   int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  2853   3412     int rc;
  2854   3413     MemPage *pPage = pCur->pPage;
         3414  +
         3415  +#ifndef SQLITE_OMIT_SHARED_CACHE
         3416  +  rc = restoreCursorPosition(pCur, 1);
         3417  +  if( rc!=SQLITE_OK ){
         3418  +    return rc;
         3419  +  }
         3420  +  if( pCur->skip>0 ){
         3421  +    pCur->skip = 0;
         3422  +    *pRes = 0;
         3423  +    return SQLITE_OK;
         3424  +  }
         3425  +  pCur->skip = 0;
         3426  +#endif
  2855   3427   
  2856   3428     assert( pRes!=0 );
  2857         -  if( pCur->isValid==0 ){
         3429  +  if( CURSOR_INVALID==pCur->eState ){
  2858   3430       *pRes = 1;
  2859   3431       return SQLITE_OK;
  2860   3432     }
  2861   3433     assert( pPage->isInit );
  2862   3434     assert( pCur->idx<pPage->nCell );
  2863   3435   
  2864   3436     pCur->idx++;
................................................................................
  2870   3442         rc = moveToLeftmost(pCur);
  2871   3443         *pRes = 0;
  2872   3444         return rc;
  2873   3445       }
  2874   3446       do{
  2875   3447         if( isRootPage(pPage) ){
  2876   3448           *pRes = 1;
  2877         -        pCur->isValid = 0;
         3449  +        pCur->eState = CURSOR_INVALID;
  2878   3450           return SQLITE_OK;
  2879   3451         }
  2880   3452         moveToParent(pCur);
  2881   3453         pPage = pCur->pPage;
  2882   3454       }while( pCur->idx>=pPage->nCell );
  2883   3455       *pRes = 0;
  2884   3456       if( pPage->leafData ){
................................................................................
  2902   3474   ** was already pointing to the first entry in the database before
  2903   3475   ** this routine was called, then set *pRes=1.
  2904   3476   */
  2905   3477   int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  2906   3478     int rc;
  2907   3479     Pgno pgno;
  2908   3480     MemPage *pPage;
  2909         -  if( pCur->isValid==0 ){
         3481  +
         3482  +#ifndef SQLITE_OMIT_SHARED_CACHE
         3483  +  rc = restoreCursorPosition(pCur, 1);
         3484  +  if( rc!=SQLITE_OK ){
         3485  +    return rc;
         3486  +  }
         3487  +  if( pCur->skip<0 ){
         3488  +    pCur->skip = 0;
         3489  +    *pRes = 0;
         3490  +    return SQLITE_OK;
         3491  +  }
         3492  +  pCur->skip = 0;
         3493  +#endif
         3494  +
         3495  +  if( CURSOR_INVALID==pCur->eState ){
  2910   3496       *pRes = 1;
  2911   3497       return SQLITE_OK;
  2912   3498     }
  2913   3499   
  2914   3500     pPage = pCur->pPage;
  2915   3501     assert( pPage->isInit );
  2916   3502     assert( pCur->idx>=0 );
................................................................................
  2918   3504       pgno = get4byte( findCell(pPage, pCur->idx) );
  2919   3505       rc = moveToChild(pCur, pgno);
  2920   3506       if( rc ) return rc;
  2921   3507       rc = moveToRightmost(pCur);
  2922   3508     }else{
  2923   3509       while( pCur->idx==0 ){
  2924   3510         if( isRootPage(pPage) ){
  2925         -        pCur->isValid = 0;
         3511  +        pCur->eState = CURSOR_INVALID;
  2926   3512           *pRes = 1;
  2927   3513           return SQLITE_OK;
  2928   3514         }
  2929   3515         moveToParent(pCur);
  2930   3516         pPage = pCur->pPage;
  2931   3517       }
  2932   3518       pCur->idx--;
................................................................................
  2959   3545   ** which in turn can make database access faster.
  2960   3546   **
  2961   3547   ** If the "exact" parameter is not 0, and the page-number nearby exists 
  2962   3548   ** anywhere on the free-list, then it is guarenteed to be returned. This
  2963   3549   ** is only used by auto-vacuum databases when allocating a new table.
  2964   3550   */
  2965   3551   static int allocatePage(
  2966         -  Btree *pBt, 
         3552  +  BtShared *pBt, 
  2967   3553     MemPage **ppPage, 
  2968   3554     Pgno *pPgno, 
  2969   3555     Pgno nearby,
  2970   3556     u8 exact
  2971   3557   ){
  2972   3558     MemPage *pPage1;
  2973   3559     int rc;
................................................................................
  3177   3763   
  3178   3764   /*
  3179   3765   ** Add a page of the database file to the freelist.
  3180   3766   **
  3181   3767   ** sqlite3pager_unref() is NOT called for pPage.
  3182   3768   */
  3183   3769   static int freePage(MemPage *pPage){
  3184         -  Btree *pBt = pPage->pBt;
         3770  +  BtShared *pBt = pPage->pBt;
  3185   3771     MemPage *pPage1 = pBt->pPage1;
  3186   3772     int rc, n, k;
  3187   3773   
  3188   3774     /* Prepare the page for freeing */
  3189   3775     assert( pPage->pgno>1 );
  3190   3776     pPage->isInit = 0;
  3191   3777     releasePage(pPage->pParent);
................................................................................
  3245   3831     return rc;
  3246   3832   }
  3247   3833   
  3248   3834   /*
  3249   3835   ** Free any overflow pages associated with the given Cell.
  3250   3836   */
  3251   3837   static int clearCell(MemPage *pPage, unsigned char *pCell){
  3252         -  Btree *pBt = pPage->pBt;
         3838  +  BtShared *pBt = pPage->pBt;
  3253   3839     CellInfo info;
  3254   3840     Pgno ovflPgno;
  3255   3841     int rc;
  3256   3842   
  3257   3843     parseCellPtr(pPage, pCell, &info);
  3258   3844     if( info.iOverflow==0 ){
  3259   3845       return SQLITE_OK;  /* No overflow pages. Return without doing anything */
................................................................................
  3297   3883     const u8 *pSrc;
  3298   3884     int nSrc, n, rc;
  3299   3885     int spaceLeft;
  3300   3886     MemPage *pOvfl = 0;
  3301   3887     MemPage *pToRelease = 0;
  3302   3888     unsigned char *pPrior;
  3303   3889     unsigned char *pPayload;
  3304         -  Btree *pBt = pPage->pBt;
         3890  +  BtShared *pBt = pPage->pBt;
  3305   3891     Pgno pgnoOvfl = 0;
  3306   3892     int nHeader;
  3307   3893     CellInfo info;
  3308   3894   
  3309   3895     /* Fill in the header. */
  3310   3896     nHeader = 0;
  3311   3897     if( !pPage->leaf ){
................................................................................
  3386   3972   }
  3387   3973   
  3388   3974   /*
  3389   3975   ** Change the MemPage.pParent pointer on the page whose number is
  3390   3976   ** given in the second argument so that MemPage.pParent holds the
  3391   3977   ** pointer in the third argument.
  3392   3978   */
  3393         -static int reparentPage(Btree *pBt, Pgno pgno, MemPage *pNewParent, int idx){
         3979  +static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
  3394   3980     MemPage *pThis;
  3395   3981     unsigned char *aData;
  3396   3982   
  3397   3983     if( pgno==0 ) return SQLITE_OK;
  3398   3984     assert( pBt->pPager!=0 );
  3399   3985     aData = sqlite3pager_lookup(pBt->pPager, pgno);
  3400   3986     if( aData ){
................................................................................
  3429   4015   ** to make sure that each child knows that pPage is its parent.
  3430   4016   **
  3431   4017   ** This routine gets called after you memcpy() one page into
  3432   4018   ** another.
  3433   4019   */
  3434   4020   static int reparentChildPages(MemPage *pPage){
  3435   4021     int i;
  3436         -  Btree *pBt = pPage->pBt;
         4022  +  BtShared *pBt = pPage->pBt;
  3437   4023     int rc = SQLITE_OK;
  3438   4024   
  3439   4025     if( pPage->leaf ) return SQLITE_OK;
  3440   4026   
  3441   4027     for(i=0; i<pPage->nCell; i++){
  3442   4028       u8 *pCell = findCell(pPage, i);
  3443   4029       if( !pPage->leaf ){
................................................................................
  3662   4248   static int balance_quick(MemPage *pPage, MemPage *pParent){
  3663   4249     int rc;
  3664   4250     MemPage *pNew;
  3665   4251     Pgno pgnoNew;
  3666   4252     u8 *pCell;
  3667   4253     int szCell;
  3668   4254     CellInfo info;
  3669         -  Btree *pBt = pPage->pBt;
         4255  +  BtShared *pBt = pPage->pBt;
  3670   4256     int parentIdx = pParent->nCell;   /* pParent new divider cell index */
  3671   4257     int parentSize;                   /* Size of new divider cell */
  3672   4258     u8 parentCell[64];                /* Space for the new divider cell */
  3673   4259   
  3674   4260     /* Allocate a new page. Insert the overflow cell from pPage
  3675   4261     ** into it. Then remove the overflow cell from pPage.
  3676   4262     */
................................................................................
  3771   4357   **
  3772   4358   ** If this routine fails for any reason, it might leave the database
  3773   4359   ** in a corrupted state.  So if this routine fails, the database should
  3774   4360   ** be rolled back.
  3775   4361   */
  3776   4362   static int balance_nonroot(MemPage *pPage){
  3777   4363     MemPage *pParent;            /* The parent of pPage */
  3778         -  Btree *pBt;                  /* The whole database */
         4364  +  BtShared *pBt;                  /* The whole database */
  3779   4365     int nCell = 0;               /* Number of cells in apCell[] */
  3780   4366     int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
  3781   4367     int nOld;                    /* Number of pages in apOld[] */
  3782   4368     int nNew;                    /* Number of pages in apNew[] */
  3783   4369     int nDiv;                    /* Number of cells in apDiv[] */
  3784   4370     int i, j, k;                 /* Loop counters */
  3785   4371     int idx;                     /* Index of pPage in pParent->aCell[] */
................................................................................
  3792   4378     int subtotal;                /* Subtotal of bytes in cells on one page */
  3793   4379     int iSpace = 0;              /* First unused byte of aSpace[] */
  3794   4380     MemPage *apOld[NB];          /* pPage and up to two siblings */
  3795   4381     Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
  3796   4382     MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
  3797   4383     MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
  3798   4384     Pgno pgnoNew[NB+2];          /* Page numbers for each page in apNew[] */
  3799         -  int idxDiv[NB];              /* Indices of divider cells in pParent */
  3800   4385     u8 *apDiv[NB];               /* Divider cells in pParent */
  3801   4386     int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
  3802   4387     int szNew[NB+2];             /* Combined size of cells place on i-th page */
  3803   4388     u8 **apCell = 0;             /* All cells begin balanced */
  3804   4389     int *szCell;                 /* Local size of all cells in apCell[] */
  3805   4390     u8 *aCopy[NB];               /* Space for holding data of apCopy[] */
  3806   4391     u8 *aSpace;                  /* Space to hold copies of dividers cells */
................................................................................
  3884   4469     }
  3885   4470     if( nxDiv<0 ){
  3886   4471       nxDiv = 0;
  3887   4472     }
  3888   4473     nDiv = 0;
  3889   4474     for(i=0, k=nxDiv; i<NB; i++, k++){
  3890   4475       if( k<pParent->nCell ){
  3891         -      idxDiv[i] = k;
  3892   4476         apDiv[i] = findCell(pParent, k);
  3893   4477         nDiv++;
  3894   4478         assert( !pParent->leaf );
  3895   4479         pgnoOld[i] = get4byte(apDiv[i]);
  3896   4480       }else if( k==pParent->nCell ){
  3897   4481         pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
  3898   4482       }else{
................................................................................
  4322   4906   ** page contains no cells.  This is an opportunity to make the tree
  4323   4907   ** shallower by one level.
  4324   4908   */
  4325   4909   static int balance_shallower(MemPage *pPage){
  4326   4910     MemPage *pChild;             /* The only child page of pPage */
  4327   4911     Pgno pgnoChild;              /* Page number for pChild */
  4328   4912     int rc = SQLITE_OK;          /* Return code from subprocedures */
  4329         -  Btree *pBt;                  /* The main BTree structure */
         4913  +  BtShared *pBt;                  /* The main BTree structure */
  4330   4914     int mxCellPerPage;           /* Maximum number of cells per page */
  4331   4915     u8 **apCell;                 /* All cells from pages being balanced */
  4332   4916     int *szCell;                 /* Local size of all cells */
  4333   4917   
  4334   4918     assert( pPage->pParent==0 );
  4335   4919     assert( pPage->nCell==0 );
  4336   4920     pBt = pPage->pBt;
................................................................................
  4424   5008   ** child.   Finally, call balance_internal() on the new child
  4425   5009   ** to cause it to split.
  4426   5010   */
  4427   5011   static int balance_deeper(MemPage *pPage){
  4428   5012     int rc;             /* Return value from subprocedures */
  4429   5013     MemPage *pChild;    /* Pointer to a new child page */
  4430   5014     Pgno pgnoChild;     /* Page number of the new child page */
  4431         -  Btree *pBt;         /* The BTree */
         5015  +  BtShared *pBt;         /* The BTree */
  4432   5016     int usableSize;     /* Total usable size of a page */
  4433   5017     u8 *data;           /* Content of the parent page */
  4434   5018     u8 *cdata;          /* Content of the child page */
  4435   5019     int hdr;            /* Offset to page header in parent */
  4436   5020     int brk;            /* Offset to content of first cell in parent */
  4437   5021   
  4438   5022     assert( pPage->pParent==0 );
................................................................................
  4513   5097   ** means a cursor opened with wrFlag==0) this routine also moves
  4514   5098   ** all cursors other than pExclude so that they are pointing to the 
  4515   5099   ** first Cell on root page.  This is necessary because an insert 
  4516   5100   ** or delete might change the number of cells on a page or delete
  4517   5101   ** a page entirely and we do not want to leave any cursors 
  4518   5102   ** pointing to non-existant pages or cells.
  4519   5103   */
  4520         -static int checkReadLocks(Btree *pBt, Pgno pgnoRoot, BtCursor *pExclude){
         5104  +static int checkReadLocks(BtShared *pBt, Pgno pgnoRoot, BtCursor *pExclude){
  4521   5105     BtCursor *p;
  4522   5106     for(p=pBt->pCursor; p; p=p->pNext){
         5107  +    u32 flags = (p->pBtree->pSqlite ? p->pBtree->pSqlite->flags : 0);
  4523   5108       if( p->pgnoRoot!=pgnoRoot || p==pExclude ) continue;
         5109  +    if( p->wrFlag==0 && flags&SQLITE_ReadUncommitted ) continue;
  4524   5110       if( p->wrFlag==0 ) return SQLITE_LOCKED;
  4525   5111       if( p->pPage->pgno!=p->pgnoRoot ){
  4526   5112         moveToRoot(p);
  4527   5113       }
  4528   5114     }
  4529   5115     return SQLITE_OK;
  4530   5116   }
................................................................................
  4543   5129     const void *pKey, i64 nKey,    /* The key of the new record */
  4544   5130     const void *pData, int nData   /* The data of the new record */
  4545   5131   ){
  4546   5132     int rc;
  4547   5133     int loc;
  4548   5134     int szNew;
  4549   5135     MemPage *pPage;
  4550         -  Btree *pBt = pCur->pBt;
         5136  +  BtShared *pBt = pCur->pBtree->pBt;
  4551   5137     unsigned char *oldCell;
  4552   5138     unsigned char *newCell = 0;
  4553   5139   
  4554         -  if( pBt->inTrans!=TRANS_WRITE ){
         5140  +  if( pBt->inTransaction!=TRANS_WRITE ){
  4555   5141       /* Must start a transaction before doing an insert */
  4556   5142       return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  4557   5143     }
  4558   5144     assert( !pBt->readOnly );
  4559   5145     if( !pCur->wrFlag ){
  4560   5146       return SQLITE_PERM;   /* Cursor not open for writing */
  4561   5147     }
  4562   5148     if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
  4563   5149       return SQLITE_LOCKED; /* The table pCur points to has a read lock */
  4564   5150     }
  4565         -  rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc);
  4566         -  if( rc ) return rc;
         5151  +
         5152  +  /* Save the positions of any other cursors open on this table */
         5153  +  if( 
         5154  +    SQLITE_OK!=(rc = restoreCursorPosition(pCur, 0)) ||
         5155  +    SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
         5156  +    SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, &loc))
         5157  +  ){
         5158  +    return rc;
         5159  +  }
         5160  +
  4567   5161     pPage = pCur->pPage;
  4568   5162     assert( pPage->intKey || nKey>=0 );
  4569   5163     assert( pPage->leaf || !pPage->leafData );
  4570   5164     TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  4571   5165             pCur->pgnoRoot, nKey, nData, pPage->pgno,
  4572   5166             loc==0 ? "overwrite" : "new entry"));
  4573   5167     assert( pPage->isInit );
................................................................................
  4575   5169     if( rc ) return rc;
  4576   5170     newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
  4577   5171     if( newCell==0 ) return SQLITE_NOMEM;
  4578   5172     rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, &szNew);
  4579   5173     if( rc ) goto end_insert;
  4580   5174     assert( szNew==cellSizePtr(pPage, newCell) );
  4581   5175     assert( szNew<=MX_CELL_SIZE(pBt) );
  4582         -  if( loc==0 && pCur->isValid ){
         5176  +  if( loc==0 && CURSOR_VALID==pCur->eState ){
  4583   5177       int szOld;
  4584   5178       assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
  4585   5179       oldCell = findCell(pPage, pCur->idx);
  4586   5180       if( !pPage->leaf ){
  4587   5181         memcpy(newCell, oldCell, 4);
  4588   5182       }
  4589   5183       szOld = cellSizePtr(pPage, oldCell);
................................................................................
  4615   5209   ** is left pointing at a random location.
  4616   5210   */
  4617   5211   int sqlite3BtreeDelete(BtCursor *pCur){
  4618   5212     MemPage *pPage = pCur->pPage;
  4619   5213     unsigned char *pCell;
  4620   5214     int rc;
  4621   5215     Pgno pgnoChild = 0;
  4622         -  Btree *pBt = pCur->pBt;
         5216  +  BtShared *pBt = pCur->pBtree->pBt;
  4623   5217   
  4624   5218     assert( pPage->isInit );
  4625         -  if( pBt->inTrans!=TRANS_WRITE ){
         5219  +  if( pBt->inTransaction!=TRANS_WRITE ){
  4626   5220       /* Must start a transaction before doing a delete */
  4627   5221       return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  4628   5222     }
  4629   5223     assert( !pBt->readOnly );
  4630   5224     if( pCur->idx >= pPage->nCell ){
  4631   5225       return SQLITE_ERROR;  /* The cursor is not pointing to anything */
  4632   5226     }
  4633   5227     if( !pCur->wrFlag ){
  4634   5228       return SQLITE_PERM;   /* Did not open this cursor for writing */
  4635   5229     }
  4636   5230     if( checkReadLocks(pBt, pCur->pgnoRoot, pCur) ){
  4637   5231       return SQLITE_LOCKED; /* The table pCur points to has a read lock */
  4638   5232     }
  4639         -  rc = sqlite3pager_write(pPage->aData);
  4640         -  if( rc ) return rc;
         5233  +
         5234  +  /* Restore the current cursor position (a no-op if the cursor is not in 
         5235  +  ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors 
         5236  +  ** open on the same table. Then call sqlite3pager_write() on the page
         5237  +  ** that the entry will be deleted from.
         5238  +  */
         5239  +  if( 
         5240  +    (rc = restoreCursorPosition(pCur, 1)) ||
         5241  +    (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
         5242  +    (rc = sqlite3pager_write(pPage->aData))
         5243  +  ){
         5244  +    return rc;
         5245  +  }
  4641   5246   
  4642   5247     /* Locate the cell within it's page and leave pCell pointing to the
  4643   5248     ** data. The clearCell() call frees any overflow pages associated with the
  4644   5249     ** cell. The cell itself is still intact.
  4645   5250     */
  4646   5251     pCell = findCell(pPage, pCur->idx);
  4647   5252     if( !pPage->leaf ){
................................................................................
  4718   5323   ** The type of type is determined by the flags parameter.  Only the
  4719   5324   ** following values of flags are currently in use.  Other values for
  4720   5325   ** flags might not work:
  4721   5326   **
  4722   5327   **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
  4723   5328   **     BTREE_ZERODATA                  Used for SQL indices
  4724   5329   */
  4725         -int sqlite3BtreeCreateTable(Btree *pBt, int *piTable, int flags){
         5330  +int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
         5331  +  BtShared *pBt = p->pBt;
  4726   5332     MemPage *pRoot;
  4727   5333     Pgno pgnoRoot;
  4728   5334     int rc;
  4729         -  if( pBt->inTrans!=TRANS_WRITE ){
         5335  +  if( pBt->inTransaction!=TRANS_WRITE ){
  4730   5336       /* Must start a transaction first */
  4731   5337       return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  4732   5338     }
  4733   5339     assert( !pBt->readOnly );
  4734   5340   
  4735   5341     /* It is illegal to create a table if any cursors are open on the
  4736   5342     ** database. This is because in auto-vacuum mode the backend may
................................................................................
  4749   5355       Pgno pgnoMove;      /* Move a page here to make room for the root-page */
  4750   5356       MemPage *pPageMove; /* The page to move to. */
  4751   5357   
  4752   5358       /* Read the value of meta[3] from the database to determine where the
  4753   5359       ** root page of the new table should go. meta[3] is the largest root-page
  4754   5360       ** created so far, so the new root-page is (meta[3]+1).
  4755   5361       */
  4756         -    rc = sqlite3BtreeGetMeta(pBt, 4, &pgnoRoot);
         5362  +    rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
  4757   5363       if( rc!=SQLITE_OK ) return rc;
  4758   5364       pgnoRoot++;
  4759   5365   
  4760   5366       /* The new root-page may not be allocated on a pointer-map page, or the
  4761   5367       ** PENDING_BYTE page.
  4762   5368       */
  4763   5369       if( pgnoRoot==PTRMAP_PAGENO(pBt->usableSize, pgnoRoot) ||
................................................................................
  4816   5422   
  4817   5423       /* Update the pointer-map and meta-data with the new root-page number. */
  4818   5424       rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
  4819   5425       if( rc ){
  4820   5426         releasePage(pRoot);
  4821   5427         return rc;
  4822   5428       }
  4823         -    rc = sqlite3BtreeUpdateMeta(pBt, 4, pgnoRoot);
         5429  +    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  4824   5430       if( rc ){
  4825   5431         releasePage(pRoot);
  4826   5432         return rc;
  4827   5433       }
  4828   5434   
  4829   5435     }else{
  4830   5436       rc = allocatePage(pBt, &pRoot, &pgnoRoot, 1, 0);
................................................................................
  4839   5445   }
  4840   5446   
  4841   5447   /*
  4842   5448   ** Erase the given database page and all its children.  Return
  4843   5449   ** the page to the freelist.
  4844   5450   */
  4845   5451   static int clearDatabasePage(
  4846         -  Btree *pBt,           /* The BTree that contains the table */
         5452  +  BtShared *pBt,           /* The BTree that contains the table */
  4847   5453     Pgno pgno,            /* Page number to clear */
  4848   5454     MemPage *pParent,     /* Parent page.  NULL for the root */
  4849   5455     int freePageFlag      /* Deallocate page if true */
  4850   5456   ){
  4851   5457     MemPage *pPage = 0;
  4852   5458     int rc;
  4853   5459     unsigned char *pCell;
................................................................................
  4890   5496   ** the page number of the root of the table.  After this routine returns,
  4891   5497   ** the root page is empty, but still exists.
  4892   5498   **
  4893   5499   ** This routine will fail with SQLITE_LOCKED if there are any open
  4894   5500   ** read cursors on the table.  Open write cursors are moved to the
  4895   5501   ** root of the table.
  4896   5502   */
  4897         -int sqlite3BtreeClearTable(Btree *pBt, int iTable){
         5503  +int sqlite3BtreeClearTable(Btree *p, int iTable){
  4898   5504     int rc;
  4899   5505     BtCursor *pCur;
  4900         -  if( pBt->inTrans!=TRANS_WRITE ){
         5506  +  BtShared *pBt = p->pBt;
         5507  +  if( p->inTrans!=TRANS_WRITE ){
  4901   5508       return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  4902   5509     }
  4903   5510     for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  4904   5511       if( pCur->pgnoRoot==(Pgno)iTable ){
  4905   5512         if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
  4906   5513         moveToRoot(pCur);
  4907   5514       }
  4908   5515     }
  4909   5516     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
         5517  +#if 0
  4910   5518     if( rc ){
  4911   5519       sqlite3BtreeRollback(pBt);
  4912   5520     }
         5521  +#endif
  4913   5522     return rc;
  4914   5523   }
  4915   5524   
  4916   5525   /*
  4917   5526   ** Erase all information in a table and add the root of the table to
  4918   5527   ** the freelist.  Except, the root of the principle table (the one on
  4919   5528   ** page 1) is never added to the freelist.
................................................................................
  4929   5538   ** root pages are kept at the beginning of the database file, which
  4930   5539   ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
  4931   5540   ** page number that used to be the last root page in the file before
  4932   5541   ** the move.  If no page gets moved, *piMoved is set to 0.
  4933   5542   ** The last root page is recorded in meta[3] and the value of
  4934   5543   ** meta[3] is updated by this procedure.
  4935   5544   */
  4936         -int sqlite3BtreeDropTable(Btree *pBt, int iTable, int *piMoved){
         5545  +int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  4937   5546     int rc;
  4938   5547     MemPage *pPage = 0;
         5548  +  BtShared *pBt = p->pBt;
  4939   5549   
  4940         -  if( pBt->inTrans!=TRANS_WRITE ){
         5550  +  if( p->inTrans!=TRANS_WRITE ){
  4941   5551       return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  4942   5552     }
  4943   5553   
  4944   5554     /* It is illegal to drop a table if any cursors are open on the
  4945   5555     ** database. This is because in auto-vacuum mode the backend may
  4946   5556     ** need to move another root-page to fill a gap left by the deleted
  4947   5557     ** root page. If an open cursor was using this page a problem would 
................................................................................
  4949   5559     */
  4950   5560     if( pBt->pCursor ){
  4951   5561       return SQLITE_LOCKED;
  4952   5562     }
  4953   5563   
  4954   5564     rc = getPage(pBt, (Pgno)iTable, &pPage);
  4955   5565     if( rc ) return rc;
  4956         -  rc = sqlite3BtreeClearTable(pBt, iTable);
         5566  +  rc = sqlite3BtreeClearTable(p, iTable);
  4957   5567     if( rc ){
  4958   5568       releasePage(pPage);
  4959   5569       return rc;
  4960   5570     }
  4961   5571   
  4962   5572     *piMoved = 0;
  4963   5573   
................................................................................
  4964   5574     if( iTable>1 ){
  4965   5575   #ifdef SQLITE_OMIT_AUTOVACUUM
  4966   5576       rc = freePage(pPage);
  4967   5577       releasePage(pPage);
  4968   5578   #else
  4969   5579       if( pBt->autoVacuum ){
  4970   5580         Pgno maxRootPgno;
  4971         -      rc = sqlite3BtreeGetMeta(pBt, 4, &maxRootPgno);
         5581  +      rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
  4972   5582         if( rc!=SQLITE_OK ){
  4973   5583           releasePage(pPage);
  4974   5584           return rc;
  4975   5585         }
  4976   5586   
  4977   5587         if( iTable==maxRootPgno ){
  4978   5588           /* If the table being dropped is the table with the largest root-page
................................................................................
  5021   5631           maxRootPgno--;
  5022   5632         }
  5023   5633         if( maxRootPgno==PTRMAP_PAGENO(pBt->usableSize, maxRootPgno) ){
  5024   5634           maxRootPgno--;
  5025   5635         }
  5026   5636         assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  5027   5637   
  5028         -      rc = sqlite3BtreeUpdateMeta(pBt, 4, maxRootPgno);
         5638  +      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  5029   5639       }else{
  5030   5640         rc = freePage(pPage);
  5031   5641         releasePage(pPage);
  5032   5642       }
  5033   5643   #endif
  5034   5644     }else{
  5035   5645       /* If sqlite3BtreeDropTable was called on page 1. */
................................................................................
  5046   5656   ** through meta[15] are available for use by higher layers.  Meta[0]
  5047   5657   ** is read-only, the others are read/write.
  5048   5658   ** 
  5049   5659   ** The schema layer numbers meta values differently.  At the schema
  5050   5660   ** layer (and the SetCookie and ReadCookie opcodes) the number of
  5051   5661   ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
  5052   5662   */
  5053         -int sqlite3BtreeGetMeta(Btree *pBt, int idx, u32 *pMeta){
         5663  +int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  5054   5664     int rc;
  5055   5665     unsigned char *pP1;
         5666  +  BtShared *pBt = p->pBt;
         5667  +
         5668  +  /* Reading a meta-data value requires a read-lock on page 1 (and hence
         5669  +  ** the sqlite_master table. We grab this lock regardless of whether or
         5670  +  ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
         5671  +  ** 1 is treated as a special case by queryTableLock() and lockTable()).
         5672  +  */
         5673  +  rc = queryTableLock(p, 1, READ_LOCK);
         5674  +  if( rc!=SQLITE_OK ){
         5675  +    return rc;
         5676  +  }
  5056   5677   
  5057   5678     assert( idx>=0 && idx<=15 );
  5058   5679     rc = sqlite3pager_get(pBt->pPager, 1, (void**)&pP1);
  5059   5680     if( rc ) return rc;
  5060   5681     *pMeta = get4byte(&pP1[36 + idx*4]);
  5061   5682     sqlite3pager_unref(pP1);
  5062   5683   
................................................................................
  5063   5684     /* If autovacuumed is disabled in this build but we are trying to 
  5064   5685     ** access an autovacuumed database, then make the database readonly. 
  5065   5686     */
  5066   5687   #ifdef SQLITE_OMIT_AUTOVACUUM
  5067   5688     if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
  5068   5689   #endif
  5069   5690   
  5070         -  return SQLITE_OK;
         5691  +  /* Grab the read-lock on page 1. */
         5692  +  rc = lockTable(p, 1, READ_LOCK);
         5693  +  return rc;
  5071   5694   }
  5072   5695   
  5073   5696   /*
  5074   5697   ** Write meta-information back into the database.  Meta[0] is
  5075   5698   ** read-only and may not be written.
  5076   5699   */
  5077         -int sqlite3BtreeUpdateMeta(Btree *pBt, int idx, u32 iMeta){
         5700  +int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
         5701  +  BtShared *pBt = p->pBt;
  5078   5702     unsigned char *pP1;
  5079   5703     int rc;
  5080   5704     assert( idx>=1 && idx<=15 );
  5081         -  if( pBt->inTrans!=TRANS_WRITE ){
         5705  +  if( p->inTrans!=TRANS_WRITE ){
  5082   5706       return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  5083   5707     }
  5084   5708     assert( pBt->pPage1!=0 );
  5085   5709     pP1 = pBt->pPage1->aData;
  5086   5710     rc = sqlite3pager_write(pP1);
  5087   5711     if( rc ) return rc;
  5088   5712     put4byte(&pP1[36 + idx*4], iMeta);
................................................................................
  5090   5714   }
  5091   5715   
  5092   5716   /*
  5093   5717   ** Return the flag byte at the beginning of the page that the cursor
  5094   5718   ** is currently pointing to.
  5095   5719   */
  5096   5720   int sqlite3BtreeFlags(BtCursor *pCur){
         5721  +  /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
         5722  +  ** restoreCursorPosition() here.
         5723  +  */
  5097   5724     MemPage *pPage = pCur->pPage;
  5098   5725     return pPage ? pPage->aData[pPage->hdrOffset] : 0;
  5099   5726   }
  5100   5727   
  5101   5728   #ifdef SQLITE_DEBUG
  5102   5729   /*
  5103   5730   ** Print a disassembly of the given page on standard output.  This routine
  5104   5731   ** is used for debugging and testing only.
  5105   5732   */
  5106         -static int btreePageDump(Btree *pBt, int pgno, int recursive, MemPage *pParent){
         5733  +static int btreePageDump(BtShared *pBt, int pgno, int recursive, MemPage *pParent){
  5107   5734     int rc;
  5108   5735     MemPage *pPage;
  5109   5736     int i, j, c;
  5110   5737     int nFree;
  5111   5738     u16 idx;
  5112   5739     int hdr;
  5113   5740     int nCell;
................................................................................
  5195   5822       btreePageDump(pBt, get4byte(&data[hdr+8]), 1, pPage);
  5196   5823     }
  5197   5824     pPage->isInit = isInit;
  5198   5825     sqlite3pager_unref(data);
  5199   5826     fflush(stdout);
  5200   5827     return SQLITE_OK;
  5201   5828   }
  5202         -int sqlite3BtreePageDump(Btree *pBt, int pgno, int recursive){
  5203         -  return btreePageDump(pBt, pgno, recursive, 0);
         5829  +int sqlite3BtreePageDump(Btree *p, int pgno, int recursive){
         5830  +  return btreePageDump(p->pBt, pgno, recursive, 0);
  5204   5831   }
  5205   5832   #endif
  5206   5833   
  5207   5834   #ifdef SQLITE_TEST
  5208   5835   /*
  5209   5836   ** Fill aResult[] with information about the entry and page that the
  5210   5837   ** cursor is pointing to.
................................................................................
  5222   5849   **
  5223   5850   ** This routine is used for testing and debugging only.
  5224   5851   */
  5225   5852   int sqlite3BtreeCursorInfo(BtCursor *pCur, int *aResult, int upCnt){
  5226   5853     int cnt, idx;
  5227   5854     MemPage *pPage = pCur->pPage;
  5228   5855     BtCursor tmpCur;
         5856  +
         5857  +  int rc = restoreCursorPosition(pCur, 1);
         5858  +  if( rc!=SQLITE_OK ){
         5859  +    return rc;
         5860  +  }
  5229   5861   
  5230   5862     pageIntegrity(pPage);
  5231   5863     assert( pPage->isInit );
  5232   5864     getTempCursor(pCur, &tmpCur);
  5233   5865     while( upCnt-- ){
  5234   5866       moveToParent(&tmpCur);
  5235   5867     }
................................................................................
  5269   5901   }
  5270   5902   #endif
  5271   5903   
  5272   5904   /*
  5273   5905   ** Return the pager associated with a BTree.  This routine is used for
  5274   5906   ** testing and debugging only.
  5275   5907   */
  5276         -Pager *sqlite3BtreePager(Btree *pBt){
  5277         -  return pBt->pPager;
         5908  +Pager *sqlite3BtreePager(Btree *p){
         5909  +  return p->pBt->pPager;
  5278   5910   }
  5279   5911   
  5280   5912   /*
  5281   5913   ** This structure is passed around through all the sanity checking routines
  5282   5914   ** in order to keep track of some global state information.
  5283   5915   */
  5284   5916   typedef struct IntegrityCk IntegrityCk;
  5285   5917   struct IntegrityCk {
  5286         -  Btree *pBt;    /* The tree being checked out */
         5918  +  BtShared *pBt;    /* The tree being checked out */
  5287   5919     Pager *pPager; /* The associated pager.  Also accessible by pBt->pPager */
  5288   5920     int nPage;     /* Number of pages in the database */
  5289   5921     int *anRef;    /* Number of times each page is referenced */
  5290   5922     char *zErrMsg; /* An error message.  NULL of no errors seen. */
  5291   5923   };
  5292   5924   
  5293   5925   #ifndef SQLITE_OMIT_INTEGRITY_CHECK
................................................................................
  5470   6102     int nUpper            /* Number of characters in zUpperBound */
  5471   6103   ){
  5472   6104     MemPage *pPage;
  5473   6105     int i, rc, depth, d2, pgno, cnt;
  5474   6106     int hdr, cellStart;
  5475   6107     int nCell;
  5476   6108     u8 *data;
  5477         -  BtCursor cur;
  5478         -  Btree *pBt;
         6109  +  BtShared *pBt;
  5479   6110     int usableSize;
  5480   6111     char zContext[100];
  5481   6112     char *hit;
  5482   6113   
  5483   6114     sprintf(zContext, "Page %d: ", iPage);
  5484   6115   
  5485   6116     /* Check that the page exists
  5486   6117     */
  5487         -  cur.pBt = pBt = pCheck->pBt;
         6118  +  pBt = pCheck->pBt;
  5488   6119     usableSize = pBt->usableSize;
  5489   6120     if( iPage==0 ) return 0;
  5490   6121     if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  5491   6122     if( (rc = getPage(pBt, (Pgno)iPage, &pPage))!=0 ){
  5492   6123       checkAppendMsg(pCheck, zContext,
  5493   6124          "unable to get the page. error code=%d", rc);
  5494   6125       return 0;
................................................................................
  5498   6129       releasePage(pPage);
  5499   6130       return 0;
  5500   6131     }
  5501   6132   
  5502   6133     /* Check out all the cells.
  5503   6134     */
  5504   6135     depth = 0;
  5505         -  cur.pPage = pPage;
  5506   6136     for(i=0; i<pPage->nCell; i++){
  5507   6137       u8 *pCell;
  5508   6138       int sz;
  5509   6139       CellInfo info;
  5510   6140   
  5511   6141       /* Check payload overflow pages
  5512   6142       */
................................................................................
  5614   6244   ** a table.  nRoot is the number of entries in aRoot.
  5615   6245   **
  5616   6246   ** If everything checks out, this routine returns NULL.  If something is
  5617   6247   ** amiss, an error message is written into memory obtained from malloc()
  5618   6248   ** and a pointer to that error message is returned.  The calling function
  5619   6249   ** is responsible for freeing the error message when it is done.
  5620   6250   */
  5621         -char *sqlite3BtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
         6251  +char *sqlite3BtreeIntegrityCheck(Btree *p, int *aRoot, int nRoot){
  5622   6252     int i;
  5623   6253     int nRef;
  5624   6254     IntegrityCk sCheck;
         6255  +  BtShared *pBt = p->pBt;
  5625   6256   
  5626   6257     nRef = *sqlite3pager_stats(pBt->pPager);
  5627         -  if( lockBtreeWithRetry(pBt)!=SQLITE_OK ){
         6258  +  if( lockBtreeWithRetry(p)!=SQLITE_OK ){
  5628   6259       return sqliteStrDup("Unable to acquire a read lock on the database");
  5629   6260     }
  5630   6261     sCheck.pBt = pBt;
  5631   6262     sCheck.pPager = pBt->pPager;
  5632   6263     sCheck.nPage = sqlite3pager_pagecount(sCheck.pPager);
  5633   6264     if( sCheck.nPage==0 ){
  5634   6265       unlockBtreeIfUnused(pBt);
................................................................................
  5702   6333     return sCheck.zErrMsg;
  5703   6334   }
  5704   6335   #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  5705   6336   
  5706   6337   /*
  5707   6338   ** Return the full pathname of the underlying database file.
  5708   6339   */
  5709         -const char *sqlite3BtreeGetFilename(Btree *pBt){
  5710         -  assert( pBt->pPager!=0 );
  5711         -  return sqlite3pager_filename(pBt->pPager);
         6340  +const char *sqlite3BtreeGetFilename(Btree *p){
         6341  +  assert( p->pBt->pPager!=0 );
         6342  +  return sqlite3pager_filename(p->pBt->pPager);
  5712   6343   }
  5713   6344   
  5714   6345   /*
  5715   6346   ** Return the pathname of the directory that contains the database file.
  5716   6347   */
  5717         -const char *sqlite3BtreeGetDirname(Btree *pBt){
  5718         -  assert( pBt->pPager!=0 );
  5719         -  return sqlite3pager_dirname(pBt->pPager);
         6348  +const char *sqlite3BtreeGetDirname(Btree *p){
         6349  +  assert( p->pBt->pPager!=0 );
         6350  +  return sqlite3pager_dirname(p->pBt->pPager);
  5720   6351   }
  5721   6352   
  5722   6353   /*
  5723   6354   ** Return the pathname of the journal file for this database. The return
  5724   6355   ** value of this routine is the same regardless of whether the journal file
  5725   6356   ** has been created or not.
  5726   6357   */
  5727         -const char *sqlite3BtreeGetJournalname(Btree *pBt){
  5728         -  assert( pBt->pPager!=0 );
  5729         -  return sqlite3pager_journalname(pBt->pPager);
         6358  +const char *sqlite3BtreeGetJournalname(Btree *p){
         6359  +  assert( p->pBt->pPager!=0 );
         6360  +  return sqlite3pager_journalname(p->pBt->pPager);
  5730   6361   }
  5731   6362   
  5732   6363   #ifndef SQLITE_OMIT_VACUUM
  5733   6364   /*
  5734   6365   ** Copy the complete content of pBtFrom into pBtTo.  A transaction
  5735   6366   ** must be active for both files.
  5736   6367   **
  5737   6368   ** The size of file pBtFrom may be reduced by this operation.
  5738   6369   ** If anything goes wrong, the transaction on pBtFrom is rolled back.
  5739   6370   */
  5740         -int sqlite3BtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
         6371  +int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  5741   6372     int rc = SQLITE_OK;
  5742   6373     Pgno i, nPage, nToPage, iSkip;
  5743   6374   
  5744         -  if( pBtTo->inTrans!=TRANS_WRITE || pBtFrom->inTrans!=TRANS_WRITE ){
         6375  +  BtShared *pBtTo = pTo->pBt;
         6376  +  BtShared *pBtFrom = pFrom->pBt;
         6377  +
         6378  +  if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
  5745   6379       return SQLITE_ERROR;
  5746   6380     }
  5747   6381     if( pBtTo->pCursor ) return SQLITE_BUSY;
  5748   6382     nToPage = sqlite3pager_pagecount(pBtTo->pPager);
  5749   6383     nPage = sqlite3pager_pagecount(pBtFrom->pPager);
  5750   6384     iSkip = PENDING_BYTE_PAGE(pBtTo);
  5751   6385     for(i=1; rc==SQLITE_OK && i<=nPage; i++){
................................................................................
  5766   6400       sqlite3pager_unref(pPage);
  5767   6401       sqlite3pager_dont_write(pBtTo->pPager, i);
  5768   6402     }
  5769   6403     if( !rc && nPage<nToPage ){
  5770   6404       rc = sqlite3pager_truncate(pBtTo->pPager, nPage);
  5771   6405     }
  5772   6406     if( rc ){
  5773         -    sqlite3BtreeRollback(pBtTo);
         6407  +    sqlite3BtreeRollback(pTo);
  5774   6408     }
  5775   6409     return rc;  
  5776   6410   }
  5777   6411   #endif /* SQLITE_OMIT_VACUUM */
  5778   6412   
  5779   6413   /*
  5780   6414   ** Return non-zero if a transaction is active.
  5781   6415   */
  5782         -int sqlite3BtreeIsInTrans(Btree *pBt){
  5783         -  return (pBt && (pBt->inTrans==TRANS_WRITE));
         6416  +int sqlite3BtreeIsInTrans(Btree *p){
         6417  +  return (p && (p->inTrans==TRANS_WRITE));
  5784   6418   }
  5785   6419   
  5786   6420   /*
  5787   6421   ** Return non-zero if a statement transaction is active.
  5788   6422   */
  5789         -int sqlite3BtreeIsInStmt(Btree *pBt){
  5790         -  return (pBt && pBt->inStmt);
         6423  +int sqlite3BtreeIsInStmt(Btree *p){
         6424  +  return (p->pBt && p->pBt->inStmt);
  5791   6425   }
  5792   6426   
  5793   6427   /*
  5794   6428   ** This call is a no-op if no write-transaction is currently active on pBt.
  5795   6429   **
  5796   6430   ** Otherwise, sync the database file for the btree pBt. zMaster points to
  5797   6431   ** the name of a master journal file that should be written into the
................................................................................
  5800   6434   **
  5801   6435   ** When this is called, the master journal should already have been
  5802   6436   ** created, populated with this journal pointer and synced to disk.
  5803   6437   **
  5804   6438   ** Once this is routine has returned, the only thing required to commit
  5805   6439   ** the write-transaction for this database file is to delete the journal.
  5806   6440   */
  5807         -int sqlite3BtreeSync(Btree *pBt, const char *zMaster){
  5808         -  if( pBt->inTrans==TRANS_WRITE ){
         6441  +int sqlite3BtreeSync(Btree *p, const char *zMaster){
         6442  +  if( p->inTrans==TRANS_WRITE ){
         6443  +    BtShared *pBt = p->pBt;
  5809   6444   #ifndef SQLITE_OMIT_AUTOVACUUM
  5810   6445       Pgno nTrunc = 0;
  5811   6446       if( pBt->autoVacuum ){
  5812   6447         int rc = autoVacuumCommit(pBt, &nTrunc); 
  5813   6448         if( rc!=SQLITE_OK ) return rc;
  5814   6449       }
  5815   6450       return sqlite3pager_sync(pBt->pPager, zMaster, nTrunc);
  5816   6451   #endif
  5817   6452       return sqlite3pager_sync(pBt->pPager, zMaster, 0);
  5818   6453     }
  5819   6454     return SQLITE_OK;
  5820   6455   }
  5821   6456   
  5822         -#ifndef SQLITE_OMIT_GLOBALRECOVER
         6457  +/*
         6458  +** This function returns a pointer to a blob of memory associated with
         6459  +** a single shared-btree. The memory is used by client code for it's own
         6460  +** purposes (for example, to store a high-level schema associated with 
         6461  +** the shared-btree). The btree layer manages reference counting issues.
         6462  +**
         6463  +** The first time this is called on a shared-btree, nBytes bytes of memory
         6464  +** are allocated, zeroed, and returned to the caller. For each subsequent 
         6465  +** call the nBytes parameter is ignored and a pointer to the same blob
         6466  +** of memory returned. 
         6467  +**
         6468  +** Just before the shared-btree is closed, the function passed as the 
         6469  +** xFree argument when the memory allocation was made is invoked on the 
         6470  +** blob of allocated memory. This function should not call sqliteFree()
         6471  +** on the memory, the btree layer does that.
         6472  +*/
         6473  +void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
         6474  +  BtShared *pBt = p->pBt;
         6475  +  if( !pBt->pSchema ){
         6476  +    pBt->pSchema = sqliteMalloc(nBytes);
         6477  +    pBt->xFreeSchema = xFree;
         6478  +  }
         6479  +  return pBt->pSchema;
         6480  +}
         6481  +
  5823   6482   /*
  5824         -** Reset the btree and underlying pager after a malloc() failure. Any
  5825         -** transaction that was active when malloc() failed is rolled back.
         6483  +** Return true if another user of the same shared btree as the argument
         6484  +** handle holds an exclusive lock on the sqlite_master table.
  5826   6485   */
  5827         -int sqlite3BtreeReset(Btree *pBt){
  5828         -  if( pBt->pCursor ) return SQLITE_BUSY;
  5829         -  pBt->inTrans = TRANS_NONE;
  5830         -  unlockBtreeIfUnused(pBt);
  5831         -  return sqlite3pager_reset(pBt->pPager);
         6486  +int sqlite3BtreeSchemaLocked(Btree *p){
         6487  +  return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
  5832   6488   }
         6489  +
         6490  +int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
         6491  +  int rc = SQLITE_OK;
         6492  +#ifndef SQLITE_OMIT_SHARED_CACHE
         6493  +  u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
         6494  +  rc = queryTableLock(p, iTab, lockType);
         6495  +  if( rc==SQLITE_OK ){
         6496  +    rc = lockTable(p, iTab, lockType);
         6497  +  }
  5833   6498   #endif
         6499  +  return rc;
         6500  +}

Changes to SQLite.Interop/src/btree.h.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This header file defines the interface that the sqlite B-Tree file
    13     13   ** subsystem.  See comments in the source code for a detailed description
    14     14   ** of what each interface routine does.
    15     15   **
    16         -** @(#) $Id: btree.h,v 1.11 2005/12/19 17:57:46 rmsimpson Exp $
           16  +** @(#) $Id: btree.h,v 1.12 2006/01/10 18:40:37 rmsimpson Exp $
    17     17   */
    18     18   #ifndef _BTREE_H_
    19     19   #define _BTREE_H_
    20     20   
    21     21   /* TODO: This definition is just included so other modules compile. It
    22     22   ** needs to be revisited.
    23     23   */
................................................................................
    32     32   #endif
    33     33   
    34     34   /*
    35     35   ** Forward declarations of structure
    36     36   */
    37     37   typedef struct Btree Btree;
    38     38   typedef struct BtCursor BtCursor;
           39  +typedef struct BtShared BtShared;
    39     40   
    40     41   
    41     42   int sqlite3BtreeOpen(
    42     43     const char *zFilename,   /* Name of database file to open */
           44  +  sqlite3 *db,             /* Associated database connection */
    43     45     Btree **,                /* Return open Btree* here */
    44     46     int flags                /* Flags */
    45     47   );
    46     48   
    47     49   /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
    48     50   ** following values.
    49     51   **
................................................................................
    70     72   int sqlite3BtreeBeginStmt(Btree*);
    71     73   int sqlite3BtreeCommitStmt(Btree*);
    72     74   int sqlite3BtreeRollbackStmt(Btree*);
    73     75   int sqlite3BtreeCreateTable(Btree*, int*, int flags);
    74     76   int sqlite3BtreeIsInTrans(Btree*);
    75     77   int sqlite3BtreeIsInStmt(Btree*);
    76     78   int sqlite3BtreeSync(Btree*, const char *zMaster);
    77         -int sqlite3BtreeReset(Btree *);
           79  +void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
           80  +int sqlite3BtreeSchemaLocked(Btree *);
           81  +int sqlite3BtreeLockTable(Btree *, int, u8);
    78     82   
    79     83   const char *sqlite3BtreeGetFilename(Btree *);
    80     84   const char *sqlite3BtreeGetDirname(Btree *);
    81     85   const char *sqlite3BtreeGetJournalname(Btree *);
    82     86   int sqlite3BtreeCopyFile(Btree *, Btree *);
    83     87   
    84     88   /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR

Changes to SQLite.Interop/src/build.c.

    18     18   **     CREATE INDEX
    19     19   **     DROP INDEX
    20     20   **     creating ID lists
    21     21   **     BEGIN TRANSACTION
    22     22   **     COMMIT
    23     23   **     ROLLBACK
    24     24   **
    25         -** $Id: build.c,v 1.10 2005/12/19 17:57:46 rmsimpson Exp $
           25  +** $Id: build.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    26     26   */
    27     27   #include "sqliteInt.h"
    28     28   #include <ctype.h>
    29     29   
    30     30   /*
    31     31   ** This routine is called when a new SQL statement is beginning to
    32     32   ** be parsed.  Initialize the pParse structure as needed.
    33     33   */
    34     34   void sqlite3BeginParse(Parse *pParse, int explainFlag){
    35     35     pParse->explain = explainFlag;
    36     36     pParse->nVar = 0;
    37     37   }
           38  +
           39  +#ifndef SQLITE_OMIT_SHARED_CACHE
           40  +/*
           41  +** The TableLock structure is only used by the sqlite3TableLock() and
           42  +** codeTableLocks() functions.
           43  +*/
           44  +struct TableLock {
           45  +  int iDb;
           46  +  int iTab;
           47  +  u8 isWriteLock;
           48  +  const char *zName;
           49  +};
           50  +
           51  +/*
           52  +** Have the compiled statement lock the table with rootpage iTab in database
           53  +** iDb at the shared-cache level when executed. The isWriteLock argument 
           54  +** is zero for a read-lock, or non-zero for a write-lock.
           55  +**
           56  +** The zName parameter should point to the unqualified table name. This is
           57  +** used to provide a more informative error message should the lock fail.
           58  +*/
           59  +void sqlite3TableLock(
           60  +  Parse *pParse, 
           61  +  int iDb, 
           62  +  int iTab, 
           63  +  u8 isWriteLock,  
           64  +  const char *zName
           65  +){
           66  +  int i;
           67  +  int nBytes;
           68  +  TableLock *p;
           69  +  ThreadData *pTsd = sqlite3ThreadData();
           70  +
           71  +  if( 0==pTsd->useSharedData || iDb<0 ){
           72  +    return;
           73  +  }
           74  +
           75  +  for(i=0; i<pParse->nTableLock; i++){
           76  +    p = &pParse->aTableLock[i];
           77  +    if( p->iDb==iDb && p->iTab==iTab ){
           78  +      p->isWriteLock = (p->isWriteLock || isWriteLock);
           79  +      return;
           80  +    }
           81  +  }
           82  +
           83  +  nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
           84  +  sqliteReallocOrFree((void **)&pParse->aTableLock, nBytes);
           85  +  if( pParse->aTableLock ){
           86  +    p = &pParse->aTableLock[pParse->nTableLock++];
           87  +    p->iDb = iDb;
           88  +    p->iTab = iTab;
           89  +    p->isWriteLock = isWriteLock;
           90  +    p->zName = zName;
           91  +  }
           92  +}
           93  +
           94  +/*
           95  +** Code an OP_TableLock instruction for each table locked by the
           96  +** statement (configured by calls to sqlite3TableLock()).
           97  +*/
           98  +static void codeTableLocks(Parse *pParse){
           99  +  int i;
          100  +  Vdbe *pVdbe; 
          101  +  assert( sqlite3ThreadData()->useSharedData || pParse->nTableLock==0 );
          102  +
          103  +  if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
          104  +    return;
          105  +  }
          106  +
          107  +  for(i=0; i<pParse->nTableLock; i++){
          108  +    TableLock *p = &pParse->aTableLock[i];
          109  +    int p1 = p->iDb;
          110  +    if( p->isWriteLock ){
          111  +      p1 = -1*(p1+1);
          112  +    }
          113  +    sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
          114  +  }
          115  +}
          116  +#else
          117  +  #define codeTableLocks(x)
          118  +#endif
    38    119   
    39    120   /*
    40    121   ** This routine is called after a single SQL statement has been
    41    122   ** parsed and a VDBE program to execute that statement has been
    42    123   ** prepared.  This routine puts the finishing touches on the
    43    124   ** VDBE program and resets the pParse structure for the next
    44    125   ** parse.
................................................................................
    46    127   ** Note that if an error occurred, it might be the case that
    47    128   ** no VDBE code was generated.
    48    129   */
    49    130   void sqlite3FinishCoding(Parse *pParse){
    50    131     sqlite3 *db;
    51    132     Vdbe *v;
    52    133   
    53         -  if( sqlite3_malloc_failed ) return;
          134  +  if( sqlite3ThreadData()->mallocFailed ) return;
    54    135     if( pParse->nested ) return;
    55    136     if( !pParse->pVdbe ){
    56    137       if( pParse->rc==SQLITE_OK && pParse->nErr ){
    57    138         pParse->rc = SQLITE_ERROR;
    58    139       }
    59    140       return;
    60    141     }
................................................................................
    78    159         int iDb;
    79    160         sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
    80    161         for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
    81    162           if( (mask & pParse->cookieMask)==0 ) continue;
    82    163           sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
    83    164           sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
    84    165         }
          166  +
          167  +      /* Once all the cookies have been verified and transactions opened, 
          168  +      ** obtain the required table-locks. This is a no-op unless the 
          169  +      ** shared-cache feature is enabled.
          170  +      */
          171  +      codeTableLocks(pParse);
    85    172         sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
    86    173       }
    87    174   
    88    175   #ifndef SQLITE_OMIT_TRACE
    89    176       /* Add a No-op that contains the complete text of the compiled SQL
    90    177       ** statement as its P3 argument.  This does not change the functionality
    91    178       ** of the program. 
................................................................................
   168    255     Table *p = 0;
   169    256     int i;
   170    257     assert( zName!=0 );
   171    258     assert( (db->flags & SQLITE_Initialized) || db->init.busy );
   172    259     for(i=OMIT_TEMPDB; i<db->nDb; i++){
   173    260       int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   174    261       if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
   175         -    p = sqlite3HashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
          262  +    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
   176    263       if( p ) break;
   177    264     }
   178    265     return p;
   179    266   }
   180    267   
   181    268   /*
   182    269   ** Locate the in-memory structure that describes a particular database
................................................................................
   223    310   */
   224    311   Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   225    312     Index *p = 0;
   226    313     int i;
   227    314     assert( (db->flags & SQLITE_Initialized) || db->init.busy );
   228    315     for(i=OMIT_TEMPDB; i<db->nDb; i++){
   229    316       int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
          317  +    Schema *pSchema = db->aDb[j].pSchema;
   230    318       if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
   231         -    p = sqlite3HashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
          319  +    assert( pSchema || (j==1 && !db->aDb[1].pBt) );
          320  +    if( pSchema ){
          321  +      p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
          322  +    }
   232    323       if( p ) break;
   233    324     }
   234    325     return p;
   235    326   }
   236    327   
   237    328   /*
   238    329   ** Reclaim the memory used by an index
................................................................................
   248    339   **
   249    340   ** The index is removed from the database hash tables but
   250    341   ** it is not unlinked from the Table that it indexes.
   251    342   ** Unlinking from the Table must be done by the calling function.
   252    343   */
   253    344   static void sqliteDeleteIndex(sqlite3 *db, Index *p){
   254    345     Index *pOld;
          346  +  const char *zName = p->zName;
   255    347   
   256         -  assert( db!=0 && p->zName!=0 );
   257         -  pOld = sqlite3HashInsert(&db->aDb[p->iDb].idxHash, p->zName,
   258         -                          strlen(p->zName)+1, 0);
          348  +  pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
   259    349     assert( pOld==0 || pOld==p );
   260    350     freeIndex(p);
   261    351   }
   262    352   
   263    353   /*
   264    354   ** For the index called zIdxName which is found in the database iDb,
   265    355   ** unlike that index from its Table then remove the index from
   266    356   ** the index hash table and free all memory structures associated
   267    357   ** with the index.
   268    358   */
   269    359   void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   270    360     Index *pIndex;
   271    361     int len;
          362  +  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
   272    363   
   273    364     len = strlen(zIdxName);
   274         -  pIndex = sqlite3HashInsert(&db->aDb[iDb].idxHash, zIdxName, len+1, 0);
          365  +  pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
   275    366     if( pIndex ){
   276    367       if( pIndex->pTable->pIndex==pIndex ){
   277    368         pIndex->pTable->pIndex = pIndex->pNext;
   278    369       }else{
   279    370         Index *p;
   280    371         for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
   281    372         if( p && p->pNext==pIndex ){
................................................................................
   295    386   ** schema-cookie mismatch occurs.
   296    387   **
   297    388   ** If iDb<=0 then reset the internal schema tables for all database
   298    389   ** files.  If iDb>=2 then reset the internal schema for only the
   299    390   ** single file indicated.
   300    391   */
   301    392   void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
   302         -  HashElem *pElem;
   303         -  Hash temp1;
   304         -  Hash temp2;
   305    393     int i, j;
   306    394   
   307    395     assert( iDb>=0 && iDb<db->nDb );
   308    396     db->flags &= ~SQLITE_Initialized;
   309    397     for(i=iDb; i<db->nDb; i++){
   310    398       Db *pDb = &db->aDb[i];
   311         -    temp1 = pDb->tblHash;
   312         -    temp2 = pDb->trigHash;
   313         -    sqlite3HashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
   314         -    sqlite3HashClear(&pDb->aFKey);
   315         -    sqlite3HashClear(&pDb->idxHash);
   316         -    for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
   317         -      sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
          399  +    if( pDb->pSchema ){
          400  +      sqlite3SchemaFree(pDb->pSchema);
   318    401       }
   319         -    sqlite3HashClear(&temp2);
   320         -    sqlite3HashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
   321         -    for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
   322         -      Table *pTab = sqliteHashData(pElem);
   323         -      sqlite3DeleteTable(db, pTab);
   324         -    }
   325         -    sqlite3HashClear(&temp1);
   326         -    pDb->pSeqTab = 0;
   327         -    DbClearProperty(db, i, DB_SchemaLoaded);
   328    402       if( iDb>0 ) return;
   329    403     }
   330    404     assert( iDb==0 );
   331    405     db->flags &= ~SQLITE_InternChanges;
   332    406   
   333    407     /* If one or more of the auxiliary database files has been closed,
   334         -  ** then remove then from the auxiliary database list.  We take the
          408  +  ** then remove them from the auxiliary database list.  We take the
   335    409     ** opportunity to do this here since we have just deleted all of the
   336    410     ** schema hash tables and therefore do not have to make any changes
   337    411     ** to any of those tables.
   338    412     */
   339    413     for(i=0; i<db->nDb; i++){
   340    414       struct Db *pDb = &db->aDb[i];
   341    415       if( pDb->pBt==0 ){
................................................................................
   415    489   ** data structure if db!=NULL.  If db==NULL, indices attached to
   416    490   ** the table are deleted, but it is assumed they have already been
   417    491   ** unlinked.
   418    492   */
   419    493   void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
   420    494     Index *pIndex, *pNext;
   421    495     FKey *pFKey, *pNextFKey;
          496  +
          497  +  db = 0;
   422    498   
   423    499     if( pTable==0 ) return;
   424    500   
   425    501     /* Do not delete the table until the reference count reaches zero. */
   426    502     pTable->nRef--;
   427    503     if( pTable->nRef>0 ){
   428    504       return;
................................................................................
   429    505     }
   430    506     assert( pTable->nRef==0 );
   431    507   
   432    508     /* Delete all indices associated with this table
   433    509     */
   434    510     for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   435    511       pNext = pIndex->pNext;
   436         -    assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
          512  +    assert( pIndex->pSchema==pTable->pSchema );
   437    513       sqliteDeleteIndex(db, pIndex);
   438    514     }
   439    515   
   440    516   #ifndef SQLITE_OMIT_FOREIGN_KEY
   441    517     /* Delete all foreign keys associated with this table.  The keys
   442    518     ** should have already been unlinked from the db->aFKey hash table 
   443    519     */
   444    520     for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
   445    521       pNextFKey = pFKey->pNextFrom;
   446         -    assert( pTable->iDb<db->nDb );
   447         -    assert( sqlite3HashFind(&db->aDb[pTable->iDb].aFKey,
          522  +    assert( sqlite3HashFind(&pTable->pSchema->aFKey,
   448    523                              pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
   449    524       sqliteFree(pFKey);
   450    525     }
   451    526   #endif
   452    527   
   453    528     /* Delete the Table structure itself.
   454    529     */
   455    530     sqliteResetColumnNames(pTable);
   456    531     sqliteFree(pTable->zName);
   457    532     sqliteFree(pTable->zColAff);
   458    533     sqlite3SelectDelete(pTable->pSelect);
          534  +#ifndef SQLITE_OMIT_CHECK
          535  +  sqlite3ExprDelete(pTable->pCheck);
          536  +#endif
   459    537     sqliteFree(pTable);
   460    538   }
   461    539   
   462    540   /*
   463    541   ** Unlink the given table from the hash tables and the delete the
   464    542   ** table structure with all its indices and foreign keys.
   465    543   */
................................................................................
   468    546     FKey *pF1, *pF2;
   469    547     Db *pDb;
   470    548   
   471    549     assert( db!=0 );
   472    550     assert( iDb>=0 && iDb<db->nDb );
   473    551     assert( zTabName && zTabName[0] );
   474    552     pDb = &db->aDb[iDb];
   475         -  p = sqlite3HashInsert(&pDb->tblHash, zTabName, strlen(zTabName)+1, 0);
          553  +  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
   476    554     if( p ){
   477    555   #ifndef SQLITE_OMIT_FOREIGN_KEY
   478    556       for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
   479    557         int nTo = strlen(pF1->zTo) + 1;
   480         -      pF2 = sqlite3HashFind(&pDb->aFKey, pF1->zTo, nTo);
          558  +      pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
   481    559         if( pF2==pF1 ){
   482         -        sqlite3HashInsert(&pDb->aFKey, pF1->zTo, nTo, pF1->pNextTo);
          560  +        sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
   483    561         }else{
   484    562           while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
   485    563           if( pF2 ){
   486    564             pF2->pNextTo = pF1->pNextTo;
   487    565           }
   488    566         }
   489    567       }
................................................................................
   502    580   ** Tokens are often just pointers into the original SQL text and so
   503    581   ** are not \000 terminated and are not persistent.  The returned string
   504    582   ** is \000 terminated and is persistent.
   505    583   */
   506    584   char *sqlite3NameFromToken(Token *pName){
   507    585     char *zName;
   508    586     if( pName ){
   509         -    zName = sqliteStrNDup(pName->z, pName->n);
          587  +    zName = sqliteStrNDup((char*)pName->z, pName->n);
   510    588       sqlite3Dequote(zName);
   511    589     }else{
   512    590       zName = 0;
   513    591     }
   514    592     return zName;
   515    593   }
   516    594   
   517    595   /*
   518    596   ** Open the sqlite_master table stored in database number iDb for
   519    597   ** writing. The table is opened using cursor 0.
   520    598   */
   521         -void sqlite3OpenMasterTable(Vdbe *v, int iDb){
          599  +void sqlite3OpenMasterTable(Parse *p, int iDb){
          600  +  Vdbe *v = sqlite3GetVdbe(p);
          601  +  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
   522    602     sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
   523    603     sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
   524    604     sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
   525    605   }
   526    606   
   527    607   /*
   528    608   ** The token *pName contains the name of a database (either "main" or
................................................................................
   628    708   */
   629    709   void sqlite3StartTable(
   630    710     Parse *pParse,   /* Parser context */
   631    711     Token *pStart,   /* The "CREATE" token */
   632    712     Token *pName1,   /* First part of the name of the table or view */
   633    713     Token *pName2,   /* Second part of the name of the table or view */
   634    714     int isTemp,      /* True if this is a TEMP table */
   635         -  int isView       /* True if this is a VIEW */
          715  +  int isView,      /* True if this is a VIEW */
          716  +  int noErr        /* Do nothing if table already exists */
   636    717   ){
   637    718     Table *pTable;
   638    719     char *zName = 0; /* The name of the new table */
   639    720     sqlite3 *db = pParse->db;
   640    721     Vdbe *v;
   641    722     int iDb;         /* Database number to create the table in */
   642    723     Token *pName;    /* Unqualified name of the table to create */
................................................................................
   706    787     ** it does.
   707    788     */
   708    789     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   709    790       goto begin_table_error;
   710    791     }
   711    792     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
   712    793     if( pTable ){
   713         -    sqlite3ErrorMsg(pParse, "table %T already exists", pName);
          794  +    if( !noErr ){
          795  +      sqlite3ErrorMsg(pParse, "table %T already exists", pName);
          796  +    }
   714    797       goto begin_table_error;
   715    798     }
   716    799     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
   717    800       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   718    801       goto begin_table_error;
   719    802     }
   720    803     pTable = sqliteMalloc( sizeof(Table) );
................................................................................
   724    807       goto begin_table_error;
   725    808     }
   726    809     pTable->zName = zName;
   727    810     pTable->nCol = 0;
   728    811     pTable->aCol = 0;
   729    812     pTable->iPKey = -1;
   730    813     pTable->pIndex = 0;
   731         -  pTable->iDb = iDb;
          814  +  pTable->pSchema = db->aDb[iDb].pSchema;
   732    815     pTable->nRef = 1;
   733    816     if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
   734    817     pParse->pNewTable = pTable;
   735    818   
   736    819     /* If this is the magic sqlite_sequence table used by autoincrement,
   737    820     ** then record a pointer to this table in the main database structure
   738    821     ** so that INSERT can find the table easily.
   739    822     */
   740    823   #ifndef SQLITE_OMIT_AUTOINCREMENT
   741    824     if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   742         -    db->aDb[iDb].pSeqTab = pTable;
          825  +    pTable->pSchema->pSeqTab = pTable;
   743    826     }
   744    827   #endif
   745    828   
   746    829     /* Begin generating the code that will insert the table record into
   747    830     ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   748    831     ** and allocate the record number for the table entry now.  Before any
   749    832     ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
................................................................................
   757    840   
   758    841       /* If the file format and encoding in the database have not been set, 
   759    842       ** set them now.
   760    843       */
   761    844       sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);   /* file_format */
   762    845       lbl = sqlite3VdbeMakeLabel(v);
   763    846       sqlite3VdbeAddOp(v, OP_If, 0, lbl);
   764         -    sqlite3VdbeAddOp(v, OP_Integer, db->file_format, 0);
          847  +    sqlite3VdbeAddOp(v, OP_Integer, SQLITE_DEFAULT_FILE_FORMAT, 0);
   765    848       sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
   766         -    sqlite3VdbeAddOp(v, OP_Integer, db->enc, 0);
          849  +    sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
   767    850       sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
   768    851       sqlite3VdbeResolveLabel(v, lbl);
   769    852   
   770    853       /* This just creates a place-holder record in the sqlite_master table.
   771    854       ** The record created does not contain anything yet.  It will be replaced
   772    855       ** by the real entry in code generated at sqlite3EndTable().
   773    856       **
................................................................................
   779    862       if( isView ){
   780    863         sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
   781    864       }else
   782    865   #endif
   783    866       {
   784    867         sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
   785    868       }
   786         -    sqlite3OpenMasterTable(v, iDb);
          869  +    sqlite3OpenMasterTable(pParse, iDb);
   787    870       sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
   788    871       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
   789    872       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
   790    873       sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
   791    874       sqlite3VdbeAddOp(v, OP_Close, 0, 0);
   792    875       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
   793    876     }
................................................................................
   887    970   ** Substring     | Affinity
   888    971   ** --------------------------------
   889    972   ** 'INT'         | SQLITE_AFF_INTEGER
   890    973   ** 'CHAR'        | SQLITE_AFF_TEXT
   891    974   ** 'CLOB'        | SQLITE_AFF_TEXT
   892    975   ** 'TEXT'        | SQLITE_AFF_TEXT
   893    976   ** 'BLOB'        | SQLITE_AFF_NONE
          977  +** 'REAL'        | SQLITE_AFF_REAL
          978  +** 'FLOA'        | SQLITE_AFF_REAL
          979  +** 'DOUB'        | SQLITE_AFF_REAL
   894    980   **
   895    981   ** If none of the substrings in the above table are found,
   896    982   ** SQLITE_AFF_NUMERIC is returned.
   897    983   */
   898    984   char sqlite3AffinityType(const Token *pType){
   899    985     u32 h = 0;
   900    986     char aff = SQLITE_AFF_NUMERIC;
................................................................................
   907    993       if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
   908    994         aff = SQLITE_AFF_TEXT; 
   909    995       }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
   910    996         aff = SQLITE_AFF_TEXT;
   911    997       }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
   912    998         aff = SQLITE_AFF_TEXT;
   913    999       }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
   914         -        && aff==SQLITE_AFF_NUMERIC ){
         1000  +        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
   915   1001         aff = SQLITE_AFF_NONE;
         1002  +#ifndef SQLITE_OMIT_FLOATING_POINT
         1003  +    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
         1004  +        && aff==SQLITE_AFF_NUMERIC ){
         1005  +      aff = SQLITE_AFF_REAL;
         1006  +    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
         1007  +        && aff==SQLITE_AFF_NUMERIC ){
         1008  +      aff = SQLITE_AFF_REAL;
         1009  +    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
         1010  +        && aff==SQLITE_AFF_NUMERIC ){
         1011  +      aff = SQLITE_AFF_REAL;
         1012  +#endif
   916   1013       }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
   917         -      aff = SQLITE_AFF_INTEGER; 
         1014  +      aff = SQLITE_AFF_INTEGER;
   918   1015         break;
   919   1016       }
   920   1017     }
   921   1018   
   922   1019     return aff;
   923   1020   }
   924   1021   
................................................................................
   989   1086   ** If the key is not an INTEGER PRIMARY KEY, then create a unique
   990   1087   ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
   991   1088   */
   992   1089   void sqlite3AddPrimaryKey(
   993   1090     Parse *pParse,    /* Parsing context */
   994   1091     ExprList *pList,  /* List of field names to be indexed */
   995   1092     int onError,      /* What to do with a uniqueness conflict */
   996         -  int autoInc       /* True if the AUTOINCREMENT keyword is present */
         1093  +  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
         1094  +  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
   997   1095   ){
   998   1096     Table *pTab = pParse->pNewTable;
   999   1097     char *zType = 0;
  1000   1098     int iCol = -1, i;
  1001   1099     if( pTab==0 ) goto primary_key_exit;
  1002   1100     if( pTab->hasPrimKey ){
  1003   1101       sqlite3ErrorMsg(pParse, 
................................................................................
  1020   1118         }
  1021   1119       }
  1022   1120       if( pList->nExpr>1 ) iCol = -1;
  1023   1121     }
  1024   1122     if( iCol>=0 && iCol<pTab->nCol ){
  1025   1123       zType = pTab->aCol[iCol].zType;
  1026   1124     }
  1027         -  if( zType && sqlite3StrICmp(zType, "INTEGER")==0 ){
         1125  +  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
         1126  +        && sortOrder==SQLITE_SO_ASC ){
  1028   1127       pTab->iPKey = iCol;
  1029   1128       pTab->keyConf = onError;
  1030   1129       pTab->autoInc = autoInc;
  1031   1130     }else if( autoInc ){
  1032   1131   #ifndef SQLITE_OMIT_AUTOINCREMENT
  1033   1132       sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  1034   1133          "INTEGER PRIMARY KEY");
  1035   1134   #endif
  1036   1135     }else{
  1037         -    sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0);
         1136  +    sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
  1038   1137       pList = 0;
  1039   1138     }
  1040   1139   
  1041   1140   primary_key_exit:
  1042   1141     sqlite3ExprListDelete(pList);
  1043   1142     return;
  1044   1143   }
         1144  +
         1145  +/*
         1146  +** Add a new CHECK constraint to the table currently under construction.
         1147  +*/
         1148  +void sqlite3AddCheckConstraint(
         1149  +  Parse *pParse,    /* Parsing context */
         1150  +  Expr *pCheckExpr  /* The check expression */
         1151  +){
         1152  +#ifndef SQLITE_OMIT_CHECK
         1153  +  Table *pTab = pParse->pNewTable;
         1154  +  if( pTab ){
         1155  +    /* The CHECK expression must be duplicated so that tokens refer
         1156  +    ** to malloced space and not the (ephemeral) text of the CREATE TABLE
         1157  +    ** statement */
         1158  +    pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
         1159  +  }
         1160  +#endif
         1161  +  sqlite3ExprDelete(pCheckExpr);
         1162  +}
  1045   1163   
  1046   1164   /*
  1047   1165   ** Set the collation function of the most recently parsed table column
  1048   1166   ** to the CollSeq given.
  1049   1167   */
  1050   1168   void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
  1051   1169     Table *p;
................................................................................
  1098   1216   **
  1099   1217   ** If no versions of the requested collations sequence are available, or
  1100   1218   ** another error occurs, NULL is returned and an error message written into
  1101   1219   ** pParse.
  1102   1220   */
  1103   1221   CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
  1104   1222     sqlite3 *db = pParse->db;
  1105         -  u8 enc = db->enc;
         1223  +  u8 enc = ENC(db);
  1106   1224     u8 initbusy = db->init.busy;
  1107   1225   
  1108   1226     CollSeq *pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
  1109   1227     if( !initbusy && (!pColl || !pColl->xCmp) ){
  1110   1228       pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
  1111   1229       if( !pColl ){
  1112   1230         if( nName<0 ){
................................................................................
  1134   1252   ** This plan is not completely bullet-proof.  It is possible for
  1135   1253   ** the schema to change multiple times and for the cookie to be
  1136   1254   ** set back to prior value.  But schema changes are infrequent
  1137   1255   ** and the probability of hitting the same cookie value is only
  1138   1256   ** 1 chance in 2^32.  So we're safe enough.
  1139   1257   */
  1140   1258   void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
  1141         -  sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].schema_cookie+1, 0);
         1259  +  sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
  1142   1260     sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
  1143   1261   }
  1144   1262   
  1145   1263   /*
  1146   1264   ** Measure the number of characters needed to output the given
  1147   1265   ** identifier.  The number returned includes any quotes used
  1148   1266   ** but does not include the null terminator.
................................................................................
  1182   1300   }
  1183   1301   
  1184   1302   /*
  1185   1303   ** Generate a CREATE TABLE statement appropriate for the given
  1186   1304   ** table.  Memory to hold the text of the statement is obtained
  1187   1305   ** from sqliteMalloc() and must be freed by the calling function.
  1188   1306   */
  1189         -static char *createTableStmt(Table *p){
         1307  +static char *createTableStmt(Table *p, int isTemp){
  1190   1308     int i, k, n;
  1191   1309     char *zStmt;
  1192   1310     char *zSep, *zSep2, *zEnd, *z;
  1193   1311     Column *pCol;
  1194   1312     n = 0;
  1195   1313     for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  1196   1314       n += identLength(pCol->zName);
................................................................................
  1208   1326       zSep = "\n  ";
  1209   1327       zSep2 = ",\n  ";
  1210   1328       zEnd = "\n)";
  1211   1329     }
  1212   1330     n += 35 + 6*p->nCol;
  1213   1331     zStmt = sqliteMallocRaw( n );
  1214   1332     if( zStmt==0 ) return 0;
  1215         -  strcpy(zStmt, !OMIT_TEMPDB&&p->iDb==1 ? "CREATE TEMP TABLE ":"CREATE TABLE ");
         1333  +  strcpy(zStmt, !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
  1216   1334     k = strlen(zStmt);
  1217   1335     identPut(zStmt, &k, p->zName);
  1218   1336     zStmt[k++] = '(';
  1219   1337     for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  1220   1338       strcpy(&zStmt[k], zSep);
  1221   1339       k += strlen(&zStmt[k]);
  1222   1340       zSep = zSep2;
................................................................................
  1255   1373     Parse *pParse,          /* Parse context */
  1256   1374     Token *pCons,           /* The ',' token after the last column defn. */
  1257   1375     Token *pEnd,            /* The final ')' token in the CREATE TABLE */
  1258   1376     Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
  1259   1377   ){
  1260   1378     Table *p;
  1261   1379     sqlite3 *db = pParse->db;
         1380  +  int iDb;
  1262   1381   
  1263         -  if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3_malloc_failed ) return;
         1382  +  if( (pEnd==0 && pSelect==0) || 
         1383  +      pParse->nErr || sqlite3ThreadData()->mallocFailed ) {
         1384  +    return;
         1385  +  }
  1264   1386     p = pParse->pNewTable;
  1265   1387     if( p==0 ) return;
  1266   1388   
  1267   1389     assert( !db->init.busy || !pSelect );
         1390  +
         1391  +  iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
         1392  +
         1393  +#ifndef SQLITE_OMIT_CHECK
         1394  +  /* Resolve names in all CHECK constraint expressions.
         1395  +  */
         1396  +  if( p->pCheck ){
         1397  +    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
         1398  +    NameContext sNC;                /* Name context for pParse->pNewTable */
         1399  +
         1400  +    memset(&sNC, 0, sizeof(sNC));
         1401  +    memset(&sSrc, 0, sizeof(sSrc));
         1402  +    sSrc.nSrc = 1;
         1403  +    sSrc.a[0].zName = p->zName;
         1404  +    sSrc.a[0].pTab = p;
         1405  +    sSrc.a[0].iCursor = -1;
         1406  +    sNC.pParse = pParse;
         1407  +    sNC.pSrcList = &sSrc;
         1408  +    sNC.isCheck = 1;
         1409  +    if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
         1410  +      return;
         1411  +    }
         1412  +  }
         1413  +#endif /* !defined(SQLITE_OMIT_CHECK) */
  1268   1414   
  1269   1415     /* If the db->init.busy is 1 it means we are reading the SQL off the
  1270   1416     ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  1271   1417     ** So do not write to the disk again.  Extract the root page number
  1272   1418     ** for the table from the db->init.newTnum field.  (The page number
  1273   1419     ** should have been put there by the sqliteOpenCb routine.)
  1274   1420     */
................................................................................
  1314   1460       /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  1315   1461       ** statement to populate the new table. The root-page number for the
  1316   1462       ** new table is on the top of the vdbe stack.
  1317   1463       **
  1318   1464       ** Once the SELECT has been coded by sqlite3Select(), it is in a
  1319   1465       ** suitable state to query for the column names and types to be used
  1320   1466       ** by the new table.
         1467  +    **
         1468  +    ** A shared-cache write-lock is not required to write to the new table,
         1469  +    ** as a schema-lock must have already been obtained to create it. Since
         1470  +    ** a schema-lock excludes all other database users, the write-lock would
         1471  +    ** be redundant.
  1321   1472       */
  1322   1473       if( pSelect ){
  1323   1474         Table *pSelTab;
  1324   1475         sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
  1325         -      sqlite3VdbeAddOp(v, OP_Integer, p->iDb, 0);
         1476  +      sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  1326   1477         sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
  1327   1478         pParse->nTab = 2;
  1328   1479         sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
  1329   1480         sqlite3VdbeAddOp(v, OP_Close, 1, 0);
  1330   1481         if( pParse->nErr==0 ){
  1331   1482           pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
  1332   1483           if( pSelTab==0 ) return;
................................................................................
  1337   1488           pSelTab->aCol = 0;
  1338   1489           sqlite3DeleteTable(0, pSelTab);
  1339   1490         }
  1340   1491       }
  1341   1492   
  1342   1493       /* Compute the complete text of the CREATE statement */
  1343   1494       if( pSelect ){
  1344         -      zStmt = createTableStmt(p);
         1495  +      zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema);
  1345   1496       }else{
  1346   1497         n = pEnd->z - pParse->sNameToken.z + 1;
  1347   1498         zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
  1348   1499       }
  1349   1500   
  1350   1501       /* A slot for the record has already been allocated in the 
  1351   1502       ** SQLITE_MASTER table.  We just need to update that slot with all
................................................................................
  1353   1504       ** slot is the 2nd item on the stack.  The top of the stack is the
  1354   1505       ** root page for the new table (or a 0 if this is a view).
  1355   1506       */
  1356   1507       sqlite3NestedParse(pParse,
  1357   1508         "UPDATE %Q.%s "
  1358   1509            "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
  1359   1510          "WHERE rowid=#1",
  1360         -      db->aDb[p->iDb].zName, SCHEMA_TABLE(p->iDb),
         1511  +      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  1361   1512         zType,
  1362   1513         p->zName,
  1363   1514         p->zName,
  1364   1515         zStmt
  1365   1516       );
  1366   1517       sqliteFree(zStmt);
  1367         -    sqlite3ChangeCookie(db, v, p->iDb);
         1518  +    sqlite3ChangeCookie(db, v, iDb);
  1368   1519   
  1369   1520   #ifndef SQLITE_OMIT_AUTOINCREMENT
  1370   1521       /* Check to see if we need to create an sqlite_sequence table for
  1371   1522       ** keeping track of autoincrement keys.
  1372   1523       */
  1373   1524       if( p->autoInc ){
  1374         -      Db *pDb = &db->aDb[p->iDb];
  1375         -      if( pDb->pSeqTab==0 ){
         1525  +      Db *pDb = &db->aDb[iDb];
         1526  +      if( pDb->pSchema->pSeqTab==0 ){
  1376   1527           sqlite3NestedParse(pParse,
  1377   1528             "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  1378   1529             pDb->zName
  1379   1530           );
  1380   1531         }
  1381   1532       }
  1382   1533   #endif
  1383   1534   
  1384   1535       /* Reparse everything to update our internal data structures */
  1385         -    sqlite3VdbeOp3(v, OP_ParseSchema, p->iDb, 0,
         1536  +    sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
  1386   1537           sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
  1387   1538     }
  1388   1539   
  1389   1540   
  1390   1541     /* Add the table to the in-memory representation of the database.
  1391   1542     */
  1392   1543     if( db->init.busy && pParse->nErr==0 ){
  1393   1544       Table *pOld;
  1394   1545       FKey *pFKey; 
  1395         -    Db *pDb = &db->aDb[p->iDb];
  1396         -    pOld = sqlite3HashInsert(&pDb->tblHash, p->zName, strlen(p->zName)+1, p);
         1546  +    Schema *pSchema = p->pSchema;
         1547  +    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
  1397   1548       if( pOld ){
  1398   1549         assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
  1399   1550         return;
  1400   1551       }
  1401   1552   #ifndef SQLITE_OMIT_FOREIGN_KEY
  1402   1553       for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  1403   1554         int nTo = strlen(pFKey->zTo) + 1;
  1404         -      pFKey->pNextTo = sqlite3HashFind(&pDb->aFKey, pFKey->zTo, nTo);
  1405         -      sqlite3HashInsert(&pDb->aFKey, pFKey->zTo, nTo, pFKey);
         1555  +      pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
         1556  +      sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
  1406   1557       }
  1407   1558   #endif
  1408   1559       pParse->pNewTable = 0;
  1409   1560       db->nTable++;
  1410   1561       db->flags |= SQLITE_InternChanges;
  1411   1562   
  1412   1563   #ifndef SQLITE_OMIT_ALTERTABLE
................................................................................
  1433   1584   ){
  1434   1585     Table *p;
  1435   1586     int n;
  1436   1587     const unsigned char *z;
  1437   1588     Token sEnd;
  1438   1589     DbFixer sFix;
  1439   1590     Token *pName;
         1591  +  int iDb;
  1440   1592   
  1441   1593     if( pParse->nVar>0 ){
  1442   1594       sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  1443   1595       sqlite3SelectDelete(pSelect);
  1444   1596       return;
  1445   1597     }
  1446         -  sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1);
         1598  +  sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1, 0);
  1447   1599     p = pParse->pNewTable;
  1448   1600     if( p==0 || pParse->nErr ){
  1449   1601       sqlite3SelectDelete(pSelect);
  1450   1602       return;
  1451   1603     }
  1452   1604     sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  1453         -  if( sqlite3FixInit(&sFix, pParse, p->iDb, "view", pName)
         1605  +  iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
         1606  +  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
  1454   1607       && sqlite3FixSelect(&sFix, pSelect)
  1455   1608     ){
  1456   1609       sqlite3SelectDelete(pSelect);
  1457   1610       return;
  1458   1611     }
  1459   1612   
  1460   1613     /* Make a copy of the entire SELECT statement that defines the view.
  1461   1614     ** This will force all the Expr.token.z values to be dynamically
  1462   1615     ** allocated rather than point to the input string - which means that
  1463   1616     ** they will persist after the current sqlite3_exec() call returns.
  1464   1617     */
  1465   1618     p->pSelect = sqlite3SelectDup(pSelect);
  1466   1619     sqlite3SelectDelete(pSelect);
         1620  +  if( sqlite3ThreadData()->mallocFailed ){
         1621  +    return;
         1622  +  }
  1467   1623     if( !pParse->db->init.busy ){
  1468   1624       sqlite3ViewGetColumnNames(pParse, p);
  1469   1625     }
  1470   1626   
  1471   1627     /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
  1472   1628     ** the end.
  1473   1629     */
................................................................................
  1530   1686     ** "*" elements in the results set of the view and will assign cursors
  1531   1687     ** to the elements of the FROM clause.  But we do not want these changes
  1532   1688     ** to be permanent.  So the computation is done on a copy of the SELECT
  1533   1689     ** statement that defines the view.
  1534   1690     */
  1535   1691     assert( pTable->pSelect );
  1536   1692     pSel = sqlite3SelectDup(pTable->pSelect);
  1537         -  n = pParse->nTab;
  1538         -  sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  1539         -  pTable->nCol = -1;
  1540         -  pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
  1541         -  pParse->nTab = n;
  1542         -  if( pSelTab ){
  1543         -    assert( pTable->aCol==0 );
  1544         -    pTable->nCol = pSelTab->nCol;
  1545         -    pTable->aCol = pSelTab->aCol;
  1546         -    pSelTab->nCol = 0;
  1547         -    pSelTab->aCol = 0;
  1548         -    sqlite3DeleteTable(0, pSelTab);
  1549         -    DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
  1550         -  }else{
  1551         -    pTable->nCol = 0;
         1693  +  if( pSel ){
         1694  +    n = pParse->nTab;
         1695  +    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
         1696  +    pTable->nCol = -1;
         1697  +    pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
         1698  +    pParse->nTab = n;
         1699  +    if( pSelTab ){
         1700  +      assert( pTable->aCol==0 );
         1701  +      pTable->nCol = pSelTab->nCol;
         1702  +      pTable->aCol = pSelTab->aCol;
         1703  +      pSelTab->nCol = 0;
         1704  +      pSelTab->aCol = 0;
         1705  +      sqlite3DeleteTable(0, pSelTab);
         1706  +      pTable->pSchema->flags |= DB_UnresetViews;
         1707  +    }else{
         1708  +      pTable->nCol = 0;
         1709  +      nErr++;
         1710  +    }
         1711  +    sqlite3SelectDelete(pSel);
         1712  +  } else {
  1552   1713       nErr++;
  1553   1714     }
  1554         -  sqlite3SelectDelete(pSel);
  1555   1715     return nErr;  
  1556   1716   }
  1557   1717   #endif /* SQLITE_OMIT_VIEW */
  1558   1718   
  1559   1719   #ifndef SQLITE_OMIT_VIEW
  1560   1720   /*
  1561   1721   ** Clear the column names from every VIEW in database idx.
  1562   1722   */
  1563   1723   static void sqliteViewResetAll(sqlite3 *db, int idx){
  1564   1724     HashElem *i;
  1565   1725     if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  1566         -  for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
         1726  +  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  1567   1727       Table *pTab = sqliteHashData(i);
  1568   1728       if( pTab->pSelect ){
  1569   1729         sqliteResetColumnNames(pTab);
  1570   1730       }
  1571   1731     }
  1572   1732     DbClearProperty(db, idx, DB_UnresetViews);
  1573   1733   }
................................................................................
  1580   1740   ** used by SQLite when the btree layer moves a table root page. The
  1581   1741   ** root-page of a table or index in database iDb has changed from iFrom
  1582   1742   ** to iTo.
  1583   1743   */
  1584   1744   #ifndef SQLITE_OMIT_AUTOVACUUM
  1585   1745   void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
  1586   1746     HashElem *pElem;
  1587         -  
  1588         -  for(pElem=sqliteHashFirst(&pDb->tblHash); pElem; pElem=sqliteHashNext(pElem)){
         1747  +  Hash *pHash;
         1748  +
         1749  +  pHash = &pDb->pSchema->tblHash;
         1750  +  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  1589   1751       Table *pTab = sqliteHashData(pElem);
  1590   1752       if( pTab->tnum==iFrom ){
  1591   1753         pTab->tnum = iTo;
  1592   1754         return;
  1593   1755       }
  1594   1756     }
  1595         -  for(pElem=sqliteHashFirst(&pDb->idxHash); pElem; pElem=sqliteHashNext(pElem)){
         1757  +  pHash = &pDb->pSchema->idxHash;
         1758  +  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  1596   1759       Index *pIdx = sqliteHashData(pElem);
  1597   1760       if( pIdx->tnum==iFrom ){
  1598   1761         pIdx->tnum = iTo;
  1599   1762         return;
  1600   1763       }
  1601   1764     }
  1602   1765     assert(0);
................................................................................
  1632   1795   ** Code to update the sqlite_master tables and internal schema definitions
  1633   1796   ** in case a root-page belonging to another table is moved by the btree layer
  1634   1797   ** is also added (this can happen with an auto-vacuum database).
  1635   1798   */
  1636   1799   static void destroyTable(Parse *pParse, Table *pTab){
  1637   1800   #ifdef SQLITE_OMIT_AUTOVACUUM
  1638   1801     Index *pIdx;
  1639         -  destroyRootPage(pParse, pTab->tnum, pTab->iDb);
         1802  +  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
         1803  +  destroyRootPage(pParse, pTab->tnum, iDb);
  1640   1804     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1641         -    destroyRootPage(pParse, pIdx->tnum, pIdx->iDb);
         1805  +    destroyRootPage(pParse, pIdx->tnum, iDb);
  1642   1806     }
  1643   1807   #else
  1644   1808     /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  1645   1809     ** is not defined), then it is important to call OP_Destroy on the
  1646   1810     ** table and index root-pages in order, starting with the numerically 
  1647   1811     ** largest root-page number. This guarantees that none of the root-pages
  1648   1812     ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
................................................................................
  1665   1829       int iLargest = 0;
  1666   1830   
  1667   1831       if( iDestroyed==0 || iTab<iDestroyed ){
  1668   1832         iLargest = iTab;
  1669   1833       }
  1670   1834       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1671   1835         int iIdx = pIdx->tnum;
  1672         -      assert( pIdx->iDb==pTab->iDb );
         1836  +      assert( pIdx->pSchema==pTab->pSchema );
  1673   1837         if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  1674   1838           iLargest = iIdx;
  1675   1839         }
  1676   1840       }
  1677         -    if( iLargest==0 ) return;
  1678         -    destroyRootPage(pParse, iLargest, pTab->iDb);
  1679         -    iDestroyed = iLargest;
         1841  +    if( iLargest==0 ){
         1842  +      return;
         1843  +    }else{
         1844  +      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
         1845  +      destroyRootPage(pParse, iLargest, iDb);
         1846  +      iDestroyed = iLargest;
         1847  +    }
  1680   1848     }
  1681   1849   #endif
  1682   1850   }
  1683   1851   
  1684   1852   /*
  1685   1853   ** This routine is called to do the work of a DROP TABLE statement.
  1686   1854   ** pName is the name of the table to be dropped.
  1687   1855   */
  1688         -void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView){
         1856  +void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  1689   1857     Table *pTab;
  1690   1858     Vdbe *v;
  1691   1859     sqlite3 *db = pParse->db;
  1692   1860     int iDb;
  1693   1861   
  1694         -  if( pParse->nErr || sqlite3_malloc_failed ) goto exit_drop_table;
         1862  +  if( pParse->nErr || sqlite3ThreadData()->mallocFailed ) goto exit_drop_table;
  1695   1863     assert( pName->nSrc==1 );
  1696   1864     pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
  1697   1865   
  1698         -  if( pTab==0 ) goto exit_drop_table;
  1699         -  iDb = pTab->iDb;
         1866  +  if( pTab==0 ){
         1867  +    if( noErr ){
         1868  +      sqlite3ErrorClear(pParse);
         1869  +    }
         1870  +    goto exit_drop_table;
         1871  +  }
         1872  +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  1700   1873     assert( iDb>=0 && iDb<db->nDb );
  1701   1874   #ifndef SQLITE_OMIT_AUTHORIZATION
  1702   1875     {
  1703   1876       int code;
  1704         -    const char *zTab = SCHEMA_TABLE(pTab->iDb);
  1705         -    const char *zDb = db->aDb[pTab->iDb].zName;
         1877  +    const char *zTab = SCHEMA_TABLE(iDb);
         1878  +    const char *zDb = db->aDb[iDb].zName;
  1706   1879       if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  1707   1880         goto exit_drop_table;
  1708   1881       }
  1709   1882       if( isView ){
  1710   1883         if( !OMIT_TEMPDB && iDb==1 ){
  1711   1884           code = SQLITE_DROP_TEMP_VIEW;
  1712   1885         }else{
................................................................................
  1723   1896         goto exit_drop_table;
  1724   1897       }
  1725   1898       if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  1726   1899         goto exit_drop_table;
  1727   1900       }
  1728   1901     }
  1729   1902   #endif
  1730         -  if( pTab->readOnly || pTab==db->aDb[iDb].pSeqTab ){
         1903  +  if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
  1731   1904       sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  1732   1905       goto exit_drop_table;
  1733   1906     }
  1734   1907   
  1735   1908   #ifndef SQLITE_OMIT_VIEW
  1736   1909     /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  1737   1910     ** on a table.
................................................................................
  1748   1921   
  1749   1922     /* Generate code to remove the table from the master table
  1750   1923     ** on disk.
  1751   1924     */
  1752   1925     v = sqlite3GetVdbe(pParse);
  1753   1926     if( v ){
  1754   1927       Trigger *pTrigger;
  1755         -    int iDb = pTab->iDb;
  1756   1928       Db *pDb = &db->aDb[iDb];
  1757   1929       sqlite3BeginWriteOperation(pParse, 0, iDb);
  1758   1930   
  1759   1931       /* Drop all triggers associated with the table being dropped. Code
  1760   1932       ** is generated to remove entries from sqlite_master and/or
  1761   1933       ** sqlite_temp_master if required.
  1762   1934       */
  1763   1935       pTrigger = pTab->pTrigger;
  1764   1936       while( pTrigger ){
  1765         -      assert( pTrigger->iDb==iDb || pTrigger->iDb==1 );
         1937  +      assert( pTrigger->pSchema==pTab->pSchema || 
         1938  +          pTrigger->pSchema==db->aDb[1].pSchema );
  1766   1939         sqlite3DropTriggerPtr(pParse, pTrigger, 1);
  1767   1940         pTrigger = pTrigger->pNext;
  1768   1941       }
  1769   1942   
  1770   1943   #ifndef SQLITE_OMIT_AUTOINCREMENT
  1771   1944       /* Remove any entries of the sqlite_sequence table associated with
  1772   1945       ** the table being dropped. This is done before the table is dropped
................................................................................
  1954   2127   static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  1955   2128     Table *pTab = pIndex->pTable;  /* The table that is indexed */
  1956   2129     int iTab = pParse->nTab;       /* Btree cursor used for pTab */
  1957   2130     int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
  1958   2131     int addr1;                     /* Address of top of loop */
  1959   2132     int tnum;                      /* Root page of index */
  1960   2133     Vdbe *v;                       /* Generate code into this virtual machine */
         2134  +  int iDb = sqlite3SchemaToIndex(pParse->db, pIndex->pSchema);
  1961   2135   
  1962   2136   #ifndef SQLITE_OMIT_AUTHORIZATION
  1963   2137     if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  1964         -      pParse->db->aDb[pIndex->iDb].zName ) ){
         2138  +      pParse->db->aDb[iDb].zName ) ){
  1965   2139       return;
  1966   2140     }
  1967   2141   #endif
  1968   2142   
  1969   2143     /* Ensure all the required collation sequences are available. This
  1970   2144     ** routine will invoke the collation-needed callback if necessary (and
  1971   2145     ** if one has been registered).
  1972   2146     */
  1973   2147     if( sqlite3CheckIndexCollSeq(pParse, pIndex) ){
  1974   2148       return;
  1975   2149     }
  1976   2150   
         2151  +  /* Require a write-lock on the table to perform this operation */
         2152  +  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
         2153  +
  1977   2154     v = sqlite3GetVdbe(pParse);
  1978   2155     if( v==0 ) return;
  1979   2156     if( memRootPage>=0 ){
  1980   2157       sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
  1981   2158       tnum = 0;
  1982   2159     }else{
  1983   2160       tnum = pIndex->tnum;
  1984         -    sqlite3VdbeAddOp(v, OP_Clear, tnum, pIndex->iDb);
         2161  +    sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
  1985   2162     }
  1986         -  sqlite3VdbeAddOp(v, OP_Integer, pIndex->iDb, 0);
         2163  +  sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  1987   2164     sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum,
  1988   2165                       (char*)&pIndex->keyInfo, P3_KEYINFO);
  1989         -  sqlite3OpenTableForReading(v, iTab, pTab);
         2166  +  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  1990   2167     addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
  1991   2168     sqlite3GenerateIndexKey(v, pIndex, iTab);
  1992   2169     if( pIndex->onError!=OE_None ){
  1993   2170       int curaddr = sqlite3VdbeCurrentAddr(v);
  1994   2171       int addr2 = curaddr+4;
  1995   2172       sqlite3VdbeChangeP2(v, curaddr-1, addr2);
  1996   2173       sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
................................................................................
  2023   2200     Parse *pParse,     /* All information about this parse */
  2024   2201     Token *pName1,     /* First part of index name. May be NULL */
  2025   2202     Token *pName2,     /* Second part of index name. May be NULL */
  2026   2203     SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  2027   2204     ExprList *pList,   /* A list of columns to be indexed */
  2028   2205     int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  2029   2206     Token *pStart,     /* The CREATE token that begins a CREATE TABLE statement */
  2030         -  Token *pEnd        /* The ")" that closes the CREATE INDEX statement */
         2207  +  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
         2208  +  int sortOrder,     /* Sort order of primary key when pList==NULL */
         2209  +  int ifNotExist     /* Omit error if index already exists */
  2031   2210   ){
  2032         -  Table *pTab = 0;   /* Table to be indexed */
  2033         -  Index *pIndex = 0; /* The index to be created */
  2034         -  char *zName = 0;
         2211  +  Table *pTab = 0;     /* Table to be indexed */
         2212  +  Index *pIndex = 0;   /* The index to be created */
         2213  +  char *zName = 0;     /* Name of the index */
         2214  +  int nName;           /* Number of characters in zName */
  2035   2215     int i, j;
  2036         -  Token nullId;    /* Fake token for an empty ID list */
  2037         -  DbFixer sFix;    /* For assigning database names to pTable */
         2216  +  Token nullId;        /* Fake token for an empty ID list */
         2217  +  DbFixer sFix;        /* For assigning database names to pTable */
         2218  +  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
  2038   2219     sqlite3 *db = pParse->db;
         2220  +  Db *pDb;             /* The specific table containing the indexed database */
         2221  +  int iDb;             /* Index of the database that is being written */
         2222  +  Token *pName = 0;    /* Unqualified name of the index to create */
         2223  +  struct ExprList_item *pListItem; /* For looping over pList */
  2039   2224   
  2040         -  int iDb;          /* Index of the database that is being written */
  2041         -  Token *pName = 0; /* Unqualified name of the index to create */
  2042         -
  2043         -  if( pParse->nErr || sqlite3_malloc_failed ) goto exit_create_index;
         2225  +  if( pParse->nErr || sqlite3ThreadData()->mallocFailed ){
         2226  +    goto exit_create_index;
         2227  +  }
  2044   2228   
  2045   2229     /*
  2046   2230     ** Find the table that is to be indexed.  Return early if not found.
  2047   2231     */
  2048   2232     if( pTblName!=0 ){
  2049   2233   
  2050   2234       /* Use the two-part index name to determine the database 
................................................................................
  2056   2240       if( iDb<0 ) goto exit_create_index;
  2057   2241   
  2058   2242   #ifndef SQLITE_OMIT_TEMPDB
  2059   2243       /* If the index name was unqualified, check if the the table
  2060   2244       ** is a temp table. If so, set the database to 1.
  2061   2245       */
  2062   2246       pTab = sqlite3SrcListLookup(pParse, pTblName);
  2063         -    if( pName2 && pName2->n==0 && pTab && pTab->iDb==1 ){
         2247  +    if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  2064   2248         iDb = 1;
  2065   2249       }
  2066   2250   #endif
  2067   2251   
  2068   2252       if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
  2069   2253           sqlite3FixSrcList(&sFix, pTblName)
  2070   2254       ){
................................................................................
  2071   2255         /* Because the parser constructs pTblName from a single identifier,
  2072   2256         ** sqlite3FixSrcList can never fail. */
  2073   2257         assert(0);
  2074   2258       }
  2075   2259       pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName, 
  2076   2260           pTblName->a[0].zDatabase);
  2077   2261       if( !pTab ) goto exit_create_index;
  2078         -    assert( iDb==pTab->iDb );
         2262  +    assert( db->aDb[iDb].pSchema==pTab->pSchema );
  2079   2263     }else{
  2080   2264       assert( pName==0 );
  2081         -    pTab =  pParse->pNewTable;
  2082         -    iDb = pTab->iDb;
         2265  +    pTab = pParse->pNewTable;
         2266  +    if( !pTab ) goto exit_create_index;
         2267  +    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  2083   2268     }
         2269  +  pDb = &db->aDb[iDb];
  2084   2270   
  2085   2271     if( pTab==0 || pParse->nErr ) goto exit_create_index;
  2086   2272     if( pTab->readOnly ){
  2087   2273       sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  2088   2274       goto exit_create_index;
  2089   2275     }
  2090   2276   #ifndef SQLITE_OMIT_VIEW
................................................................................
  2112   2298       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
  2113   2299       if( zName==0 ) goto exit_create_index;
  2114   2300       if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  2115   2301         goto exit_create_index;
  2116   2302       }
  2117   2303       if( !db->init.busy ){
  2118   2304         if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
  2119         -      if( sqlite3FindIndex(db, zName, db->aDb[iDb].zName)!=0 ){
  2120         -        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
         2305  +      if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
         2306  +        if( !ifNotExist ){
         2307  +          sqlite3ErrorMsg(pParse, "index %s already exists", zName);
         2308  +        }
  2121   2309           goto exit_create_index;
  2122   2310         }
  2123   2311         if( sqlite3FindTable(db, zName, 0)!=0 ){
  2124   2312           sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  2125   2313           goto exit_create_index;
  2126   2314         }
  2127   2315       }
................................................................................
  2136   2324       if( zName==0 ) goto exit_create_index;
  2137   2325     }
  2138   2326   
  2139   2327     /* Check for authorization to create an index.
  2140   2328     */
  2141   2329   #ifndef SQLITE_OMIT_AUTHORIZATION
  2142   2330     {
  2143         -    const char *zDb = db->aDb[iDb].zName;
         2331  +    const char *zDb = pDb->zName;
  2144   2332       if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  2145   2333         goto exit_create_index;
  2146   2334       }
  2147   2335       i = SQLITE_CREATE_INDEX;
  2148   2336       if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  2149   2337       if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  2150   2338         goto exit_create_index;
................................................................................
  2153   2341   #endif
  2154   2342   
  2155   2343     /* If pList==0, it means this routine was called to make a primary
  2156   2344     ** key out of the last column added to the table under construction.
  2157   2345     ** So create a fake list to simulate this.
  2158   2346     */
  2159   2347     if( pList==0 ){
  2160         -    nullId.z = pTab->aCol[pTab->nCol-1].zName;
  2161         -    nullId.n = strlen(nullId.z);
         2348  +    nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
         2349  +    nullId.n = strlen((char*)nullId.z);
  2162   2350       pList = sqlite3ExprListAppend(0, 0, &nullId);
  2163   2351       if( pList==0 ) goto exit_create_index;
         2352  +    pList->a[0].sortOrder = sortOrder;
  2164   2353     }
  2165   2354   
  2166   2355     /* 
  2167   2356     ** Allocate the index structure. 
  2168   2357     */
  2169         -  pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 + sizeof(int) +
  2170         -                        (sizeof(int)*2 + sizeof(CollSeq*))*pList->nExpr );
  2171         -  if( sqlite3_malloc_failed ) goto exit_create_index;
         2358  +  nName = strlen(zName);
         2359  +  pIndex = sqliteMalloc( sizeof(Index) + nName + 2 + sizeof(int) +
         2360  +                        (sizeof(int)*2 + sizeof(CollSeq*) + 1)*pList->nExpr );
         2361  +  if( sqlite3ThreadData()->mallocFailed ) goto exit_create_index;
  2172   2362     pIndex->aiColumn = (int*)&pIndex->keyInfo.aColl[pList->nExpr];
  2173   2363     pIndex->aiRowEst = (unsigned*)&pIndex->aiColumn[pList->nExpr];
  2174   2364     pIndex->zName = (char*)&pIndex->aiRowEst[pList->nExpr+1];
         2365  +  pIndex->keyInfo.aSortOrder = &pIndex->zName[nName+1];
  2175   2366     strcpy(pIndex->zName, zName);
  2176   2367     pIndex->pTable = pTab;
  2177   2368     pIndex->nColumn = pList->nExpr;
  2178   2369     pIndex->onError = onError;
  2179   2370     pIndex->autoIndex = pName==0;
  2180         -  pIndex->iDb = iDb;
         2371  +  pIndex->pSchema = db->aDb[iDb].pSchema;
         2372  +
         2373  +  /* Check to see if we should honor DESC requests on index columns
         2374  +  */
         2375  +  if( pDb->pSchema->file_format>=4 ){
         2376  +    sortOrderMask = -1;   /* Honor DESC */
         2377  +  }else{
         2378  +    sortOrderMask = 0;    /* Ignore DESC */
         2379  +  }
  2181   2380   
  2182   2381     /* Scan the names of the columns of the table to be indexed and
  2183   2382     ** load the column indices into the Index structure.  Report an error
  2184   2383     ** if any column is not found.
  2185   2384     */
  2186         -  for(i=0; i<pList->nExpr; i++){
  2187         -    for(j=0; j<pTab->nCol; j++){
  2188         -      if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
         2385  +  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
         2386  +    const char *zColName = pListItem->zName;
         2387  +    Column *pTabCol;
         2388  +    int requestedSortOrder;
         2389  +    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
         2390  +      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  2189   2391       }
  2190   2392       if( j>=pTab->nCol ){
  2191   2393         sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  2192         -        pTab->zName, pList->a[i].zName);
         2394  +        pTab->zName, zColName);
  2193   2395         goto exit_create_index;
  2194   2396       }
  2195   2397       pIndex->aiColumn[i] = j;
  2196         -    if( pList->a[i].pExpr ){
  2197         -      assert( pList->a[i].pExpr->pColl );
  2198         -      pIndex->keyInfo.aColl[i] = pList->a[i].pExpr->pColl;
         2398  +    if( pListItem->pExpr ){
         2399  +      assert( pListItem->pExpr->pColl );
         2400  +      pIndex->keyInfo.aColl[i] = pListItem->pExpr->pColl;
  2199   2401       }else{
  2200   2402         pIndex->keyInfo.aColl[i] = pTab->aCol[j].pColl;
  2201   2403       }
  2202   2404       assert( pIndex->keyInfo.aColl[i] );
  2203   2405       if( !db->init.busy && 
  2204   2406           sqlite3CheckCollSeq(pParse, pIndex->keyInfo.aColl[i]) 
  2205   2407       ){
  2206   2408         goto exit_create_index;
  2207   2409       }
         2410  +    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
         2411  +    pIndex->keyInfo.aSortOrder[i] = requestedSortOrder;
  2208   2412     }
  2209   2413     pIndex->keyInfo.nField = pList->nExpr;
  2210   2414     sqlite3DefaultRowEst(pIndex);
  2211   2415   
  2212   2416     if( pTab==pParse->pNewTable ){
  2213   2417       /* This routine has been called to create an automatic index as a
  2214   2418       ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
................................................................................
  2230   2434         assert( pIdx->autoIndex );
  2231   2435         assert( pIndex->onError!=OE_None );
  2232   2436   
  2233   2437         if( pIdx->nColumn!=pIndex->nColumn ) continue;
  2234   2438         for(k=0; k<pIdx->nColumn; k++){
  2235   2439           if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  2236   2440           if( pIdx->keyInfo.aColl[k]!=pIndex->keyInfo.aColl[k] ) break;
         2441  +        if( pIdx->keyInfo.aSortOrder[k]!=pIndex->keyInfo.aSortOrder[k] ) break;
  2237   2442         }
  2238   2443         if( k==pIdx->nColumn ){
  2239   2444           if( pIdx->onError!=pIndex->onError ){
  2240   2445             /* This constraint creates the same index as a previous
  2241   2446             ** constraint specified somewhere in the CREATE TABLE statement.
  2242   2447             ** However the ON CONFLICT clauses are different. If both this 
  2243   2448             ** constraint and the previous equivalent constraint have explicit
................................................................................
  2258   2463     }
  2259   2464   
  2260   2465     /* Link the new Index structure to its table and to the other
  2261   2466     ** in-memory database structures. 
  2262   2467     */
  2263   2468     if( db->init.busy ){
  2264   2469       Index *p;
  2265         -    p = sqlite3HashInsert(&db->aDb[pIndex->iDb].idxHash, 
         2470  +    p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
  2266   2471                            pIndex->zName, strlen(pIndex->zName)+1, pIndex);
  2267   2472       if( p ){
  2268   2473         assert( p==pIndex );  /* Malloc must have failed */
  2269   2474         goto exit_create_index;
  2270   2475       }
  2271   2476       db->flags |= SQLITE_InternChanges;
  2272   2477       if( pTblName!=0 ){
................................................................................
  2292   2497     else if( db->init.busy==0 ){
  2293   2498       Vdbe *v;
  2294   2499       char *zStmt;
  2295   2500       int iMem = pParse->nMem++;
  2296   2501   
  2297   2502       v = sqlite3GetVdbe(pParse);
  2298   2503       if( v==0 ) goto exit_create_index;
         2504  +
  2299   2505   
  2300   2506       /* Create the rootpage for the index
  2301   2507       */
  2302   2508       sqlite3BeginWriteOperation(pParse, 1, iDb);
  2303   2509       sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
  2304   2510       sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
  2305   2511   
................................................................................
  2369   2575       freeIndex(pIndex);
  2370   2576     }
  2371   2577     sqlite3ExprListDelete(pList);
  2372   2578     sqlite3SrcListDelete(pTblName);
  2373   2579     sqliteFree(zName);
  2374   2580     return;
  2375   2581   }
         2582  +
         2583  +/*
         2584  +** Generate code to make sure the file format number is at least minFormat.
         2585  +** The generated code will increase the file format number if necessary.
         2586  +*/
         2587  +void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
         2588  +  Vdbe *v;
         2589  +  v = sqlite3GetVdbe(pParse);
         2590  +  if( v ){
         2591  +    sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
         2592  +    sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
         2593  +    sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
         2594  +    sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
         2595  +    sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
         2596  +  }
         2597  +}
  2376   2598   
  2377   2599   /*
  2378   2600   ** Fill the Index.aiRowEst[] array with default information - information
  2379   2601   ** to be used when we have not run the ANALYZE command.
  2380   2602   **
  2381   2603   ** aiRowEst[0] is suppose to contain the number of elements in the index.
  2382   2604   ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
................................................................................
  2405   2627     }
  2406   2628   }
  2407   2629   
  2408   2630   /*
  2409   2631   ** This routine will drop an existing named index.  This routine
  2410   2632   ** implements the DROP INDEX statement.
  2411   2633   */
  2412         -void sqlite3DropIndex(Parse *pParse, SrcList *pName){
         2634  +void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  2413   2635     Index *pIndex;
  2414   2636     Vdbe *v;
  2415   2637     sqlite3 *db = pParse->db;
         2638  +  int iDb;
  2416   2639   
  2417         -  if( pParse->nErr || sqlite3_malloc_failed ){
         2640  +  if( pParse->nErr || sqlite3ThreadData()->mallocFailed ){
  2418   2641       goto exit_drop_index;
  2419   2642     }
  2420   2643     assert( pName->nSrc==1 );
  2421   2644     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  2422   2645       goto exit_drop_index;
  2423   2646     }
  2424   2647     pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  2425   2648     if( pIndex==0 ){
  2426         -    sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
         2649  +    if( !ifExists ){
         2650  +      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
         2651  +    }
  2427   2652       pParse->checkSchema = 1;
  2428   2653       goto exit_drop_index;
  2429   2654     }
  2430   2655     if( pIndex->autoIndex ){
  2431   2656       sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  2432   2657         "or PRIMARY KEY constraint cannot be dropped", 0);
  2433   2658       goto exit_drop_index;
  2434   2659     }
         2660  +  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  2435   2661   #ifndef SQLITE_OMIT_AUTHORIZATION
  2436   2662     {
  2437   2663       int code = SQLITE_DROP_INDEX;
  2438   2664       Table *pTab = pIndex->pTable;
  2439         -    const char *zDb = db->aDb[pIndex->iDb].zName;
  2440         -    const char *zTab = SCHEMA_TABLE(pIndex->iDb);
         2665  +    const char *zDb = db->aDb[iDb].zName;
         2666  +    const char *zTab = SCHEMA_TABLE(iDb);
  2441   2667       if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  2442   2668         goto exit_drop_index;
  2443   2669       }
  2444         -    if( !OMIT_TEMPDB && pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
         2670  +    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  2445   2671       if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  2446   2672         goto exit_drop_index;
  2447   2673       }
  2448   2674     }
  2449   2675   #endif
  2450   2676   
  2451   2677     /* Generate code to remove the index and from the master table */
  2452   2678     v = sqlite3GetVdbe(pParse);
  2453   2679     if( v ){
  2454         -    int iDb = pIndex->iDb;
  2455   2680       sqlite3NestedParse(pParse,
  2456   2681          "DELETE FROM %Q.%s WHERE name=%Q",
  2457   2682          db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  2458   2683          pIndex->zName
  2459   2684       );
  2460   2685       sqlite3ChangeCookie(db, v, iDb);
  2461   2686       destroyRootPage(pParse, pIndex->tnum, iDb);
................................................................................
  2617   2842   
  2618   2843   /*
  2619   2844   ** Assign cursors to all tables in a SrcList
  2620   2845   */
  2621   2846   void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  2622   2847     int i;
  2623   2848     struct SrcList_item *pItem;
  2624         -  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  2625         -    if( pItem->iCursor>=0 ) break;
  2626         -    pItem->iCursor = pParse->nTab++;
  2627         -    if( pItem->pSelect ){
  2628         -      sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
         2849  +  assert(pList || sqlite3ThreadData()->mallocFailed);
         2850  +  if( pList ){
         2851  +    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
         2852  +      if( pItem->iCursor>=0 ) break;
         2853  +      pItem->iCursor = pParse->nTab++;
         2854  +      if( pItem->pSelect ){
         2855  +        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
         2856  +      }
  2629   2857       }
  2630   2858     }
  2631   2859   }
  2632   2860   
  2633   2861   /*
  2634   2862   ** Add an alias to the last identifier on the given identifier list.
  2635   2863   */
................................................................................
  2663   2891   */
  2664   2892   void sqlite3BeginTransaction(Parse *pParse, int type){
  2665   2893     sqlite3 *db;
  2666   2894     Vdbe *v;
  2667   2895     int i;
  2668   2896   
  2669   2897     if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  2670         -  if( pParse->nErr || sqlite3_malloc_failed ) return;
         2898  +  if( pParse->nErr || sqlite3ThreadData()->mallocFailed ) return;
  2671   2899     if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
  2672   2900   
  2673   2901     v = sqlite3GetVdbe(pParse);
  2674   2902     if( !v ) return;
  2675   2903     if( type!=TK_DEFERRED ){
  2676   2904       for(i=0; i<db->nDb; i++){
  2677   2905         sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
................................................................................
  2684   2912   ** Commit a transaction
  2685   2913   */
  2686   2914   void sqlite3CommitTransaction(Parse *pParse){
  2687   2915     sqlite3 *db;
  2688   2916     Vdbe *v;
  2689   2917   
  2690   2918     if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  2691         -  if( pParse->nErr || sqlite3_malloc_failed ) return;
         2919  +  if( pParse->nErr || sqlite3ThreadData()->mallocFailed ) return;
  2692   2920     if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
  2693   2921   
  2694   2922     v = sqlite3GetVdbe(pParse);
  2695   2923     if( v ){
  2696   2924       sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
  2697   2925     }
  2698   2926   }
................................................................................
  2701   2929   ** Rollback a transaction
  2702   2930   */
  2703   2931   void sqlite3RollbackTransaction(Parse *pParse){
  2704   2932     sqlite3 *db;
  2705   2933     Vdbe *v;
  2706   2934   
  2707   2935     if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  2708         -  if( pParse->nErr || sqlite3_malloc_failed ) return;
         2936  +  if( pParse->nErr || sqlite3ThreadData()->mallocFailed ) return;
  2709   2937     if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
  2710   2938   
  2711   2939     v = sqlite3GetVdbe(pParse);
  2712   2940     if( v ){
  2713   2941       sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
  2714   2942     }
  2715   2943   }
................................................................................
  2733   2961         if( rc!=SQLITE_OK ){
  2734   2962           sqlite3ErrorMsg(pParse, "unable to get a write lock on "
  2735   2963             "the temporary database file");
  2736   2964           pParse->rc = rc;
  2737   2965           return 1;
  2738   2966         }
  2739   2967       }
         2968  +    assert( db->aDb[1].pSchema );
  2740   2969     }
  2741   2970     return 0;
  2742   2971   }
  2743   2972   
  2744   2973   /*
  2745   2974   ** Generate VDBE code that will verify the schema cookie and start
  2746   2975   ** a read-transaction for all named database files.
................................................................................
  2777   3006     if( iDb>=0 ){
  2778   3007       assert( iDb<db->nDb );
  2779   3008       assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  2780   3009       assert( iDb<32 );
  2781   3010       mask = 1<<iDb;
  2782   3011       if( (pParse->cookieMask & mask)==0 ){
  2783   3012         pParse->cookieMask |= mask;
  2784         -      pParse->cookieValue[iDb] = db->aDb[iDb].schema_cookie;
         3013  +      pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  2785   3014         if( !OMIT_TEMPDB && iDb==1 ){
  2786   3015           sqlite3OpenTempDatabase(pParse);
  2787   3016         }
  2788   3017       }
  2789   3018     }
  2790   3019   }
  2791   3020   
................................................................................
  2842   3071   */
  2843   3072   #ifndef SQLITE_OMIT_REINDEX
  2844   3073   static void reindexTable(Parse *pParse, Table *pTab, CollSeq *pColl){
  2845   3074     Index *pIndex;              /* An index associated with pTab */
  2846   3075   
  2847   3076     for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  2848   3077       if( pColl==0 || collationMatch(pColl,pIndex) ){
  2849         -      sqlite3BeginWriteOperation(pParse, 0, pTab->iDb);
         3078  +      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
         3079  +      sqlite3BeginWriteOperation(pParse, 0, iDb);
  2850   3080         sqlite3RefillIndex(pParse, pIndex, -1);
  2851   3081       }
  2852   3082     }
  2853   3083   }
  2854   3084   #endif
  2855   3085   
  2856   3086   /*
................................................................................
  2864   3094     int iDb;                    /* The database index number */
  2865   3095     sqlite3 *db = pParse->db;   /* The database connection */
  2866   3096     HashElem *k;                /* For looping over tables in pDb */
  2867   3097     Table *pTab;                /* A table in the database */
  2868   3098   
  2869   3099     for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  2870   3100       if( pDb==0 ) continue;
  2871         -    for(k=sqliteHashFirst(&pDb->tblHash);  k; k=sqliteHashNext(k)){
         3101  +    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
  2872   3102         pTab = (Table*)sqliteHashData(k);
  2873   3103         reindexTable(pParse, pTab, pColl);
  2874   3104       }
  2875   3105     }
  2876   3106   }
  2877   3107   #endif
  2878   3108   
................................................................................
  2906   3136       return;
  2907   3137     }
  2908   3138   
  2909   3139     if( pName1==0 || pName1->z==0 ){
  2910   3140       reindexDatabases(pParse, 0);
  2911   3141       return;
  2912   3142     }else if( pName2==0 || pName2->z==0 ){
  2913         -    pColl = sqlite3FindCollSeq(db, db->enc, pName1->z, pName1->n, 0);
         3143  +    pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
  2914   3144       if( pColl ){
  2915   3145         reindexDatabases(pParse, pColl);
  2916   3146         return;
  2917   3147       }
  2918   3148     }
  2919   3149     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  2920   3150     if( iDb<0 ) return;

Changes to SQLite.Interop/src/callback.c.

     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   **
    13     13   ** This file contains functions used to access the internal hash tables
    14     14   ** of user defined functions and collation sequences.
    15     15   **
    16         -** $Id: callback.c,v 1.6 2005/12/19 17:57:46 rmsimpson Exp $
           16  +** $Id: callback.c,v 1.7 2006/01/10 18:40:37 rmsimpson Exp $
    17     17   */
    18     18   
    19     19   #include "sqliteInt.h"
    20     20   
    21     21   /*
    22     22   ** Invoke the 'collation needed' callback to request a collation sequence
    23     23   ** in the database text encoding of name zName, length nName.
................................................................................
    25     25   */
    26     26   static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
    27     27     assert( !db->xCollNeeded || !db->xCollNeeded16 );
    28     28     if( nName<0 ) nName = strlen(zName);
    29     29     if( db->xCollNeeded ){
    30     30       char *zExternal = sqliteStrNDup(zName, nName);
    31     31       if( !zExternal ) return;
    32         -    db->xCollNeeded(db->pCollNeededArg, db, (int)db->enc, zExternal);
           32  +    db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
    33     33       sqliteFree(zExternal);
    34     34     }
    35     35   #ifndef SQLITE_OMIT_UTF16
    36     36     if( db->xCollNeeded16 ){
    37     37       char const *zExternal;
    38         -    sqlite3_value *pTmp = sqlite3GetTransientValue(db);
    39         -    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
           38  +    sqlite3_value *pTmp = sqlite3ValueNew();
           39  +    sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
    40     40       zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
    41         -    if( !zExternal ) return;
    42         -    db->xCollNeeded16(db->pCollNeededArg, db, (int)db->enc, zExternal);
           41  +    if( zExternal ){
           42  +      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
           43  +    }
           44  +    sqlite3ValueFree(pTmp);
    43     45     }
    44     46   #endif
    45     47   }
    46     48   
    47     49   /*
    48     50   ** This routine is called if the collation factory fails to deliver a
    49     51   ** collation function in the best encoding but there may be other versions
................................................................................
    86     88     const char *zName, 
    87     89     int nName
    88     90   ){
    89     91     CollSeq *p;
    90     92   
    91     93     p = pColl;
    92     94     if( !p ){
    93         -    p = sqlite3FindCollSeq(db, db->enc, zName, nName, 0);
           95  +    p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
    94     96     }
    95     97     if( !p || !p->xCmp ){
    96     98       /* No collation sequence of this type for this encoding is registered.
    97     99       ** Call the collation factory to see if it can supply us with one.
    98    100       */
    99    101       callCollNeeded(db, zName, nName);
   100         -    p = sqlite3FindCollSeq(db, db->enc, zName, nName, 0);
          102  +    p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
   101    103     }
   102    104     if( p && !p->xCmp && synthCollSeq(db, p) ){
   103    105       p = 0;
   104    106     }
   105    107     assert( !p || p->xCmp );
   106    108     return p;
   107    109   }
................................................................................
   171    173         pColl[0].zName[nName] = 0;
   172    174         pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
   173    175   
   174    176         /* If a malloc() failure occured in sqlite3HashInsert(), it will 
   175    177         ** return the pColl pointer to be deleted (because it wasn't added
   176    178         ** to the hash table).
   177    179         */
   178         -      assert( !pDel || (sqlite3_malloc_failed && pDel==pColl) );
          180  +      assert( !pDel || (sqlite3ThreadData()->mallocFailed && pDel==pColl) );
   179    181         sqliteFree(pDel);
   180    182       }
   181    183     }
   182    184     return pColl;
   183    185   }
   184    186   
   185    187   /*
................................................................................
   282    284     }
   283    285   
   284    286     /* If the createFlag parameter is true, and the seach did not reveal an
   285    287     ** exact match for the name, number of arguments and encoding, then add a
   286    288     ** new entry to the hash table and return it.
   287    289     */
   288    290     if( createFlag && bestmatch<6 && 
   289         -      (pBest = sqliteMalloc(sizeof(*pBest)+nName)) ){
          291  +      (pBest = sqliteMalloc(sizeof(*pBest)+nName))!=0 ){
   290    292       pBest->nArg = nArg;
   291    293       pBest->pNext = pFirst;
   292    294       pBest->iPrefEnc = enc;
   293    295       memcpy(pBest->zName, zName, nName);
   294    296       pBest->zName[nName] = 0;
   295    297       if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
   296    298         sqliteFree(pBest);

Changes to SQLite.Interop/src/complete.c.

    12     12   ** An tokenizer for SQL
    13     13   **
    14     14   ** This file contains C code that implements the sqlite3_complete() API.
    15     15   ** This code used to be part of the tokenizer.c source file.  But by
    16     16   ** separating it out, the code will be automatically omitted from
    17     17   ** static links that do not use it.
    18     18   **
    19         -** $Id: complete.c,v 1.4 2005/12/19 17:57:46 rmsimpson Exp $
           19  +** $Id: complete.c,v 1.5 2006/01/10 18:40:37 rmsimpson Exp $
    20     20   */
    21     21   #include "sqliteInt.h"
    22     22   #ifndef SQLITE_OMIT_COMPLETE
    23     23   
    24     24   /*
    25     25   ** This is defined in tokenize.c.  We just have to import the definition.
    26     26   */
................................................................................
   251    251     int rc = 0;
   252    252   
   253    253     pVal = sqlite3ValueNew();
   254    254     sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   255    255     zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   256    256     if( zSql8 ){
   257    257       rc = sqlite3_complete(zSql8);
          258  +  }else if( zSql ){
          259  +    rc = SQLITE_NOMEM;
          260  +    sqlite3MallocClearFailed();
   258    261     }
   259    262     sqlite3ValueFree(pVal);
   260    263     return rc;
   261    264   }
   262    265   #endif /* SQLITE_OMIT_UTF16 */
   263    266   #endif /* SQLITE_OMIT_COMPLETE */

Changes to SQLite.Interop/src/date.c.

    12     12   ** This file contains the C functions that implement date and time
    13     13   ** functions for SQLite.  
    14     14   **
    15     15   ** There is only one exported symbol in this file - the function
    16     16   ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
    17     17   ** All other code has file scope.
    18     18   **
    19         -** $Id: date.c,v 1.10 2005/12/19 17:57:46 rmsimpson Exp $
           19  +** $Id: date.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    20     20   **
    21     21   ** NOTES:
    22     22   **
    23     23   ** SQLite processes all times and dates as Julian Day numbers.  The
    24     24   ** dates and times are stored as the number of days since noon
    25     25   ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
    26     26   ** calendar system.
................................................................................
   232    232     X2 = 30.6001*(M+1);
   233    233     p->rJD = X1 + X2 + D + B - 1524.5;
   234    234     p->validJD = 1;
   235    235     p->validYMD = 0;
   236    236     if( p->validHMS ){
   237    237       p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
   238    238       if( p->validTZ ){
   239         -      p->rJD += p->tz*60/86400.0;
          239  +      p->rJD -= p->tz*60/86400.0;
   240    240         p->validHMS = 0;
   241    241         p->validTZ = 0;
   242    242       }
   243    243     }
   244    244   }
   245    245   
   246    246   /*
................................................................................
   635    635   ** the resulting time into the DateTime structure p.  Return 0
   636    636   ** on success and 1 if there are any errors.
   637    637   */
   638    638   static int isDate(int argc, sqlite3_value **argv, DateTime *p){
   639    639     int i;
   640    640     if( argc==0 ) return 1;
   641    641     if( SQLITE_NULL==sqlite3_value_type(argv[0]) || 
   642         -      parseDateOrTime(sqlite3_value_text(argv[0]), p) ) return 1;
          642  +      parseDateOrTime((char*)sqlite3_value_text(argv[0]), p) ) return 1;
   643    643     for(i=1; i<argc; i++){
   644    644       if( SQLITE_NULL==sqlite3_value_type(argv[i]) || 
   645         -        parseModifier(sqlite3_value_text(argv[i]), p) ) return 1;
          645  +        parseModifier((char*)sqlite3_value_text(argv[i]), p) ) return 1;
   646    646     }
   647    647     return 0;
   648    648   }
   649    649   
   650    650   
   651    651   /*
   652    652   ** The following routines implement the various date and time functions
................................................................................
   751    751     sqlite3_context *context,
   752    752     int argc,
   753    753     sqlite3_value **argv
   754    754   ){
   755    755     DateTime x;
   756    756     int n, i, j;
   757    757     char *z;
   758         -  const char *zFmt = sqlite3_value_text(argv[0]);
          758  +  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
   759    759     char zBuf[100];
   760    760     if( zFmt==0 || isDate(argc-1, argv+1, &x) ) return;
   761    761     for(i=0, n=1; zFmt[i]; i++, n++){
   762    762       if( zFmt[i]=='%' ){
   763    763         switch( zFmt[i+1] ){
   764    764           case 'd':
   765    765           case 'H':

Changes to SQLite.Interop/src/delete.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains C code routines that are called by the parser
    13     13   ** in order to generate code for DELETE FROM statements.
    14     14   **
    15         -** $Id: delete.c,v 1.10 2005/12/19 17:57:46 rmsimpson Exp $
           15  +** $Id: delete.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   /*
    20     20   ** Look up every table that is named in pSrc.  If any table is not found,
    21     21   ** add an error message to pParse->zErrMsg and return NULL.  If all tables
    22     22   ** are found, return a pointer to the last table.
................................................................................
    55     55   #endif
    56     56     return 0;
    57     57   }
    58     58   
    59     59   /*
    60     60   ** Generate code that will open a table for reading.
    61     61   */
    62         -void sqlite3OpenTableForReading(
    63         -  Vdbe *v,        /* Generate code into this VDBE */
           62  +void sqlite3OpenTable(
           63  +  Parse *p,       /* Generate code into this VDBE */
    64     64     int iCur,       /* The cursor number of the table */
    65         -  Table *pTab     /* The table to be opened */
           65  +  int iDb,        /* The database index in sqlite3.aDb[] */
           66  +  Table *pTab,    /* The table to be opened */
           67  +  int opcode      /* OP_OpenRead or OP_OpenWrite */
    66     68   ){
    67         -  sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
           69  +  Vdbe *v = sqlite3GetVdbe(p);
           70  +  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
           71  +  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
           72  +  sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
    68     73     VdbeComment((v, "# %s", pTab->zName));
    69         -  sqlite3VdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
           74  +  sqlite3VdbeAddOp(v, opcode, iCur, pTab->tnum);
    70     75     sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, pTab->nCol);
    71     76   }
    72     77   
    73     78   
    74     79   /*
    75     80   ** Generate code for a DELETE FROM statement.
    76     81   **
................................................................................
    91     96     WhereInfo *pWInfo;     /* Information about the WHERE clause */
    92     97     Index *pIdx;           /* For looping over indices of the table */
    93     98     int iCur;              /* VDBE Cursor number for pTab */
    94     99     sqlite3 *db;           /* Main database structure */
    95    100     AuthContext sContext;  /* Authorization context */
    96    101     int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
    97    102     NameContext sNC;       /* Name context to resolve expressions in */
          103  +  int iDb;
    98    104   
    99    105   #ifndef SQLITE_OMIT_TRIGGER
   100    106     int isView;                  /* True if attempting to delete from a view */
   101    107     int triggers_exist = 0;      /* True if any triggers exist */
   102    108   #endif
   103    109   
   104    110     sContext.pParse = 0;
   105         -  if( pParse->nErr || sqlite3_malloc_failed ){
          111  +  if( pParse->nErr || sqlite3ThreadData()->mallocFailed ){
   106    112       goto delete_from_cleanup;
   107    113     }
   108    114     db = pParse->db;
   109    115     assert( pTabList->nSrc==1 );
   110    116   
   111    117     /* Locate the table which we want to delete.  This table has to be
   112    118     ** put in an SrcList structure because some of the subroutines we
................................................................................
   130    136   # undef isView
   131    137   # define isView 0
   132    138   #endif
   133    139   
   134    140     if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
   135    141       goto delete_from_cleanup;
   136    142     }
   137         -  assert( pTab->iDb<db->nDb );
   138         -  zDb = db->aDb[pTab->iDb].zName;
          143  +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
          144  +  assert( iDb<db->nDb );
          145  +  zDb = db->aDb[iDb].zName;
   139    146     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
   140    147       goto delete_from_cleanup;
   141    148     }
   142    149   
   143    150     /* If pTab is really a view, make sure it has been initialized.
   144    151     */
   145    152     if( isView && sqlite3ViewGetColumnNames(pParse, pTab) ){
................................................................................
   172    179     /* Begin generating code.
   173    180     */
   174    181     v = sqlite3GetVdbe(pParse);
   175    182     if( v==0 ){
   176    183       goto delete_from_cleanup;
   177    184     }
   178    185     if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   179         -  sqlite3BeginWriteOperation(pParse, triggers_exist, pTab->iDb);
          186  +  sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
   180    187   
   181    188     /* If we are trying to delete from a view, realize that view into
   182    189     ** a ephemeral table.
   183    190     */
   184    191     if( isView ){
   185    192       Select *pView = sqlite3SelectDup(pTab->pSelect);
   186    193       sqlite3Select(pParse, pView, SRT_VirtualTab, iCur, 0, 0, 0, 0);
................................................................................
   201    208     if( pWhere==0 && !triggers_exist ){
   202    209       if( db->flags & SQLITE_CountRows ){
   203    210         /* If counting rows deleted, just count the total number of
   204    211         ** entries in the table. */
   205    212         int endOfLoop = sqlite3VdbeMakeLabel(v);
   206    213         int addr;
   207    214         if( !isView ){
   208         -        sqlite3OpenTableForReading(v, iCur, pTab);
          215  +        sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   209    216         }
   210    217         sqlite3VdbeAddOp(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
   211    218         addr = sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
   212    219         sqlite3VdbeAddOp(v, OP_Next, iCur, addr);
   213    220         sqlite3VdbeResolveLabel(v, endOfLoop);
   214    221         sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
   215    222       }
   216    223       if( !isView ){
   217         -      sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, pTab->iDb);
          224  +      sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, iDb);
          225  +      if( !pParse->nested ){
          226  +        sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
          227  +      }
   218    228         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   219         -        sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, pIdx->iDb);
          229  +        assert( pIdx->pSchema==pTab->pSchema );
          230  +        sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, iDb);
   220    231         }
   221    232       }
   222    233     }
   223    234   
   224    235     /* The usual case: There is a WHERE clause so we have to scan through
   225    236     ** the table and pick which records to delete.
   226    237     */
................................................................................
   265    276       /* This is the beginning of the delete loop when there are
   266    277       ** row triggers.
   267    278       */
   268    279       if( triggers_exist ){
   269    280         addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
   270    281         if( !isView ){
   271    282           sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
   272         -        sqlite3OpenTableForReading(v, iCur, pTab);
          283  +        sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   273    284         }
   274    285         sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
   275    286         sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
   276    287         sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
   277    288         sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
   278    289         if( !isView ){
   279    290           sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
................................................................................
   376    387     int iCur,          /* Cursor number for the table */
   377    388     int count          /* Increment the row change counter */
   378    389   ){
   379    390     int addr;
   380    391     addr = sqlite3VdbeAddOp(v, OP_NotExists, iCur, 0);
   381    392     sqlite3GenerateRowIndexDelete(db, v, pTab, iCur, 0);
   382    393     sqlite3VdbeAddOp(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
          394  +  if( count ){
          395  +    sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
          396  +  }
   383    397     sqlite3VdbeJumpHere(v, addr);
   384    398   }
   385    399   
   386    400   /*
   387    401   ** This routine generates VDBE code that causes the deletion of all
   388    402   ** index entries associated with a single row of a single table.
   389    403   **

Added SQLite.Interop/src/experimental.c.

            1  +/*
            2  +** 2005 January 20
            3  +**
            4  +** The author disclaims copyright to this source code.  In place of
            5  +** a legal notice, here is a blessing:
            6  +**
            7  +**    May you do good and not evil.
            8  +**    May you find forgiveness for yourself and forgive others.
            9  +**    May you share freely, never taking more than you give.
           10  +**
           11  +*************************************************************************
           12  +** This file contains C code routines that are not a part of the official
           13  +** SQLite API.  These routines are unsupported.
           14  +**
           15  +** $Id: experimental.c,v 1.1 2006/01/10 18:41:09 rmsimpson Exp $
           16  +*/
           17  +#include "sqliteInt.h"
           18  +
           19  +/*
           20  +** Set all the parameters in the compiled SQL statement to NULL.
           21  +*/
           22  +int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
           23  +  int i;
           24  +  int rc = SQLITE_OK;
           25  +  for(i=1; rc==SQLITE_OK && i<=sqlite3_bind_parameter_count(pStmt); i++){
           26  +    rc = sqlite3_bind_null(pStmt, i);
           27  +  }
           28  +  return rc;
           29  +}
           30  +
           31  +/*
           32  +** Sleep for a little while.  Return the amount of time slept.
           33  +*/
           34  +int sqlite3_sleep(int ms){
           35  +  return sqlite3OsSleep(ms);
           36  +}

Changes to SQLite.Interop/src/expr.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains routines used for analyzing expressions and
    13     13   ** for generating VDBE code that evaluates expressions in SQLite.
    14     14   **
    15         -** $Id: expr.c,v 1.17 2005/12/19 17:57:46 rmsimpson Exp $
           15  +** $Id: expr.c,v 1.18 2006/01/10 18:40:37 rmsimpson Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   #include <ctype.h>
    19     19   
    20     20   /*
    21     21   ** Return the 'affinity' of the expression pExpr if any.
    22     22   **
................................................................................
    71     71   ** pExpr is an operand of a comparison operator.  aff2 is the
    72     72   ** type affinity of the other operand.  This routine returns the
    73     73   ** type affinity that should be used for the comparison operator.
    74     74   */
    75     75   char sqlite3CompareAffinity(Expr *pExpr, char aff2){
    76     76     char aff1 = sqlite3ExprAffinity(pExpr);
    77     77     if( aff1 && aff2 ){
    78         -    /* Both sides of the comparison are columns. If one has numeric or
    79         -    ** integer affinity, use that. Otherwise use no affinity.
           78  +    /* Both sides of the comparison are columns. If one has numeric
           79  +    ** affinity, use that. Otherwise use no affinity.
    80     80       */
    81         -    if( aff1==SQLITE_AFF_INTEGER || aff2==SQLITE_AFF_INTEGER ){
    82         -      return SQLITE_AFF_INTEGER;
    83         -    }else if( aff1==SQLITE_AFF_NUMERIC || aff2==SQLITE_AFF_NUMERIC ){
           81  +    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
    84     82         return SQLITE_AFF_NUMERIC;
    85     83       }else{
    86     84         return SQLITE_AFF_NONE;
    87     85       }
    88     86     }else if( !aff1 && !aff2 ){
    89     87       /* Neither side of the comparison is a column.  Compare the
    90     88       ** results directly.
    91     89       */
    92         -    /* return SQLITE_AFF_NUMERIC;  // Ticket #805 */
    93     90       return SQLITE_AFF_NONE;
    94     91     }else{
    95     92       /* One side is a column, the other is not. Use the columns affinity. */
    96     93       assert( aff1==0 || aff2==0 );
    97     94       return (aff1 + aff2);
    98     95     }
    99     96   }
................................................................................
   125    122   ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
   126    123   ** idx_affinity is the affinity of an indexed column. Return true
   127    124   ** if the index with affinity idx_affinity may be used to implement
   128    125   ** the comparison in pExpr.
   129    126   */
   130    127   int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
   131    128     char aff = comparisonAffinity(pExpr);
   132         -  return 
   133         -    (aff==SQLITE_AFF_NONE) ||
   134         -    (aff==SQLITE_AFF_NUMERIC && idx_affinity==SQLITE_AFF_INTEGER) ||
   135         -    (aff==SQLITE_AFF_INTEGER && idx_affinity==SQLITE_AFF_NUMERIC) ||
   136         -    (aff==idx_affinity);
          129  +  switch( aff ){
          130  +    case SQLITE_AFF_NONE:
          131  +      return 1;
          132  +    case SQLITE_AFF_TEXT:
          133  +      return idx_affinity==SQLITE_AFF_TEXT;
          134  +    default:
          135  +      return sqlite3IsNumericAffinity(idx_affinity);
          136  +  }
   137    137   }
   138    138   
   139    139   /*
   140    140   ** Return the P1 value that should be used for a binary comparison
   141    141   ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
   142    142   ** If jumpIfNull is true, then set the low byte of the returned
   143    143   ** P1 value to tell the opcode to jump if either expression
................................................................................
   231    231       return 0;
   232    232     }
   233    233     if( v==0 ) return 0;
   234    234     p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
   235    235     if( p==0 ){
   236    236       return 0;  /* Malloc failed */
   237    237     }
   238         -  depth = atoi(&pToken->z[1]);
          238  +  depth = atoi((char*)&pToken->z[1]);
   239    239     p->iTable = pParse->nMem++;
   240    240     sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
   241    241     sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
   242    242     return p;
   243    243   }
   244    244   
   245    245   /*
................................................................................
   259    259   /*
   260    260   ** Set the Expr.span field of the given expression to span all
   261    261   ** text between the two given tokens.
   262    262   */
   263    263   void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
   264    264     assert( pRight!=0 );
   265    265     assert( pLeft!=0 );
   266         -  if( !sqlite3_malloc_failed && pRight->z && pLeft->z ){
          266  +  if( !sqlite3ThreadData()->mallocFailed && pRight->z && pLeft->z ){
   267    267       assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
   268    268       if( pLeft->dyn==0 && pRight->dyn==0 ){
   269    269         pExpr->span.z = pLeft->z;
   270    270         pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
   271    271       }else{
   272    272         pExpr->span.z = 0;
   273    273       }
................................................................................
   323    323     if( pToken->n==1 ){
   324    324       /* Wildcard of the form "?".  Assign the next variable number */
   325    325       pExpr->iTable = ++pParse->nVar;
   326    326     }else if( pToken->z[0]=='?' ){
   327    327       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
   328    328       ** use it as the variable number */
   329    329       int i;
   330         -    pExpr->iTable = i = atoi(&pToken->z[1]);
          330  +    pExpr->iTable = i = atoi((char*)&pToken->z[1]);
   331    331       if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
   332    332         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
   333    333             SQLITE_MAX_VARIABLE_NUMBER);
   334    334       }
   335    335       if( i>pParse->nVar ){
   336    336         pParse->nVar = i;
   337    337       }
................................................................................
   354    354       if( i>=pParse->nVarExpr ){
   355    355         pExpr->iTable = ++pParse->nVar;
   356    356         if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
   357    357           pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
   358    358           sqlite3ReallocOrFree((void**)&pParse->apVarExpr,
   359    359                          pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
   360    360         }
   361         -      if( !sqlite3_malloc_failed ){
          361  +      if( !sqlite3ThreadData()->mallocFailed ){
   362    362           assert( pParse->apVarExpr!=0 );
   363    363           pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
   364    364         }
   365    365       }
   366    366     } 
   367    367   }
   368    368   
................................................................................
   411    411   Expr *sqlite3ExprDup(Expr *p){
   412    412     Expr *pNew;
   413    413     if( p==0 ) return 0;
   414    414     pNew = sqliteMallocRaw( sizeof(*p) );
   415    415     if( pNew==0 ) return 0;
   416    416     memcpy(pNew, p, sizeof(*pNew));
   417    417     if( p->token.z!=0 ){
   418         -    pNew->token.z = sqliteStrNDup(p->token.z, p->token.n);
          418  +    pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
   419    419       pNew->token.dyn = 1;
   420    420     }else{
   421    421       assert( pNew->token.z==0 );
   422    422     }
   423    423     pNew->span.z = 0;
   424    424     pNew->pLeft = sqlite3ExprDup(p->pLeft);
   425    425     pNew->pRight = sqlite3ExprDup(p->pRight);
................................................................................
   428    428     pNew->pTab = p->pTab;
   429    429     return pNew;
   430    430   }
   431    431   void sqlite3TokenCopy(Token *pTo, Token *pFrom){
   432    432     if( pTo->dyn ) sqliteFree((char*)pTo->z);
   433    433     if( pFrom->z ){
   434    434       pTo->n = pFrom->n;
   435         -    pTo->z = sqliteStrNDup(pFrom->z, pFrom->n);
          435  +    pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
   436    436       pTo->dyn = 1;
   437    437     }else{
   438    438       pTo->z = 0;
   439    439     }
   440    440   }
   441    441   ExprList *sqlite3ExprListDup(ExprList *p){
   442    442     ExprList *pNew;
................................................................................
   458    458       if( pOldExpr->span.z!=0 && pNewExpr ){
   459    459         /* Always make a copy of the span for top-level expressions in the
   460    460         ** expression list.  The logic in SELECT processing that determines
   461    461         ** the names of columns in the result set needs this information */
   462    462         sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
   463    463       }
   464    464       assert( pNewExpr==0 || pNewExpr->span.z!=0 
   465         -            || pOldExpr->span.z==0 || sqlite3_malloc_failed );
          465  +            || pOldExpr->span.z==0 || sqlite3ThreadData()->mallocFailed );
   466    466       pItem->zName = sqliteStrDup(pOldItem->zName);
   467    467       pItem->sortOrder = pOldItem->sortOrder;
   468    468       pItem->isAgg = pOldItem->isAgg;
   469    469       pItem->done = 0;
   470    470     }
   471    471     return pNew;
   472    472   }
................................................................................
   748    748   ** to fit in a 32-bit integer, return 1 and put the value of the integer
   749    749   ** in *pValue.  If the expression is not an integer or if it is too big
   750    750   ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
   751    751   */
   752    752   int sqlite3ExprIsInteger(Expr *p, int *pValue){
   753    753     switch( p->op ){
   754    754       case TK_INTEGER: {
   755         -      if( sqlite3GetInt32(p->token.z, pValue) ){
          755  +      if( sqlite3GetInt32((char*)p->token.z, pValue) ){
   756    756           return 1;
   757    757         }
   758    758         break;
   759    759       }
   760    760       case TK_UPLUS: {
   761    761         return sqlite3ExprIsInteger(p->pLeft, pValue);
   762    762       }
................................................................................
   805    805   ** means that the form of the name is Z and that columns from any table
   806    806   ** can be used.
   807    807   **
   808    808   ** If the name cannot be resolved unambiguously, leave an error message
   809    809   ** in pParse and return non-zero.  Return zero on success.
   810    810   */
   811    811   static int lookupName(
   812         -  Parse *pParse,      /* The parsing context */
          812  +  Parse *pParse,       /* The parsing context */
   813    813     Token *pDbToken,     /* Name of the database containing table, or NULL */
   814    814     Token *pTableToken,  /* Name of table containing column, or NULL */
   815    815     Token *pColumnToken, /* Name of the column. */
   816    816     NameContext *pNC,    /* The name context used to resolve the name */
   817    817     Expr *pExpr          /* Make this EXPR node point to the selected column */
   818    818   ){
   819    819     char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
................................................................................
   827    827     struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   828    828     NameContext *pTopNC = pNC;        /* First namecontext in the list */
   829    829   
   830    830     assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
   831    831     zDb = sqlite3NameFromToken(pDbToken);
   832    832     zTab = sqlite3NameFromToken(pTableToken);
   833    833     zCol = sqlite3NameFromToken(pColumnToken);
   834         -  if( sqlite3_malloc_failed ){
          834  +  if( sqlite3ThreadData()->mallocFailed ){
   835    835       goto lookupname_end;
   836    836     }
   837    837   
   838    838     pExpr->iTable = -1;
   839    839     while( pNC && cnt==0 ){
          840  +    ExprList *pEList;
   840    841       SrcList *pSrcList = pNC->pSrcList;
   841         -    ExprList *pEList = pNC->pEList;
   842    842   
   843         -    /* assert( zTab==0 || pEList==0 ); */
   844    843       if( pSrcList ){
   845    844         for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
   846    845           Table *pTab = pItem->pTab;
          846  +        int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   847    847           Column *pCol;
   848    848     
   849    849           if( pTab==0 ) continue;
   850    850           assert( pTab->nCol>0 );
   851    851           if( zTab ){
   852    852             if( pItem->zAlias ){
   853    853               char *zTabName = pItem->zAlias;
   854    854               if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
   855    855             }else{
   856    856               char *zTabName = pTab->zName;
   857    857               if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
   858         -            if( zDb!=0 && sqlite3StrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
          858  +            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
   859    859                 continue;
   860    860               }
   861    861             }
   862    862           }
   863    863           if( 0==(cntTab++) ){
   864    864             pExpr->iTable = pItem->iCursor;
   865         -          pExpr->iDb = pTab->iDb;
          865  +          pExpr->pSchema = pTab->pSchema;
   866    866             pMatch = pItem;
   867    867           }
   868    868           for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
   869    869             if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   870    870               IdList *pUsing;
   871    871               cnt++;
   872    872               pExpr->iTable = pItem->iCursor;
   873    873               pMatch = pItem;
   874         -            pExpr->iDb = pTab->iDb;
          874  +            pExpr->pSchema = pTab->pSchema;
   875    875               /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
   876    876               pExpr->iColumn = j==pTab->iPKey ? -1 : j;
   877    877               pExpr->affinity = pTab->aCol[j].affinity;
   878    878               pExpr->pColl = pTab->aCol[j].pColl;
   879    879               if( pItem->jointype & JT_NATURAL ){
   880    880                 /* If this match occurred in the left table of a natural join,
   881    881                 ** then skip the right table to avoid a duplicate match */
................................................................................
   918    918           pTab = pTriggerStack->pTab;
   919    919         }
   920    920   
   921    921         if( pTab ){ 
   922    922           int j;
   923    923           Column *pCol = pTab->aCol;
   924    924   
   925         -        pExpr->iDb = pTab->iDb;
          925  +        pExpr->pSchema = pTab->pSchema;
   926    926           cntTab++;
   927    927           for(j=0; j < pTab->nCol; j++, pCol++) {
   928    928             if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   929    929               cnt++;
   930    930               pExpr->iColumn = j==pTab->iPKey ? -1 : j;
   931    931               pExpr->affinity = pTab->aCol[j].affinity;
   932    932               pExpr->pColl = pTab->aCol[j].pColl;
................................................................................
   955    955       **     SELECT a+b AS x FROM table WHERE x<10;
   956    956       **
   957    957       ** In cases like this, replace pExpr with a copy of the expression that
   958    958       ** forms the result set entry ("a+b" in the example) and return immediately.
   959    959       ** Note that the expression in the result set should have already been
   960    960       ** resolved by the time the WHERE clause is resolved.
   961    961       */
   962         -    if( cnt==0 && pEList!=0 && zTab==0 ){
          962  +    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
   963    963         for(j=0; j<pEList->nExpr; j++){
   964    964           char *zAs = pEList->a[j].zName;
   965    965           if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   966    966             assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   967    967             pExpr->op = TK_AS;
   968    968             pExpr->iColumn = j;
   969    969             pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
................................................................................
  1002   1002     ** more matches.  Either way, we have an error.
  1003   1003     */
  1004   1004     if( cnt!=1 ){
  1005   1005       char *z = 0;
  1006   1006       char *zErr;
  1007   1007       zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
  1008   1008       if( zDb ){
  1009         -      sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, 0);
         1009  +      sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
  1010   1010       }else if( zTab ){
  1011         -      sqlite3SetString(&z, zTab, ".", zCol, 0);
         1011  +      sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
  1012   1012       }else{
  1013   1013         z = sqliteStrDup(zCol);
  1014   1014       }
  1015   1015       sqlite3ErrorMsg(pParse, zErr, z);
  1016   1016       sqliteFree(z);
  1017   1017       pTopNC->nErr++;
  1018   1018     }
................................................................................
  1084   1084     assert( pNC!=0 );
  1085   1085     pSrcList = pNC->pSrcList;
  1086   1086     pParse = pNC->pParse;
  1087   1087   
  1088   1088     if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
  1089   1089     ExprSetProperty(pExpr, EP_Resolved);
  1090   1090   #ifndef NDEBUG
  1091         -  if( pSrcList ){
         1091  +  if( pSrcList && pSrcList->nAlloc>0 ){
  1092   1092       int i;
  1093   1093       for(i=0; i<pSrcList->nSrc; i++){
  1094   1094         assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  1095   1095       }
  1096   1096     }
  1097   1097   #endif
  1098   1098     switch( pExpr->op ){
................................................................................
  1145   1145         int no_such_func = 0;       /* True if no such function exists */
  1146   1146         int wrong_num_args = 0;     /* True if wrong number of arguments */
  1147   1147         int is_agg = 0;             /* True if is an aggregate function */
  1148   1148         int i;
  1149   1149         int nId;                    /* Number of characters in function name */
  1150   1150         const char *zId;            /* The function name. */
  1151   1151         FuncDef *pDef;              /* Information about the function */
  1152         -      int enc = pParse->db->enc;  /* The database encoding */
         1152  +      int enc = ENC(pParse->db);  /* The database encoding */
  1153   1153   
  1154         -      zId = pExpr->token.z;
         1154  +      zId = (char*)pExpr->token.z;
  1155   1155         nId = pExpr->token.n;
  1156   1156         pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  1157   1157         if( pDef==0 ){
  1158   1158           pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
  1159   1159           if( pDef==0 ){
  1160   1160             no_such_func = 1;
  1161   1161           }else{
................................................................................
  1193   1193   #ifndef SQLITE_OMIT_SUBQUERY
  1194   1194       case TK_SELECT:
  1195   1195       case TK_EXISTS:
  1196   1196   #endif
  1197   1197       case TK_IN: {
  1198   1198         if( pExpr->pSelect ){
  1199   1199           int nRef = pNC->nRef;
         1200  +#ifndef SQLITE_OMIT_CHECK
         1201  +        if( pNC->isCheck ){
         1202  +          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
         1203  +        }
         1204  +#endif
  1200   1205           sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
  1201   1206           assert( pNC->nRef>=nRef );
  1202   1207           if( nRef!=pNC->nRef ){
  1203   1208             ExprSetProperty(pExpr, EP_VarSelect);
  1204   1209           }
  1205   1210         }
         1211  +      break;
  1206   1212       }
         1213  +#ifndef SQLITE_OMIT_CHECK
         1214  +    case TK_VARIABLE: {
         1215  +      if( pNC->isCheck ){
         1216  +        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
         1217  +      }
         1218  +      break;
         1219  +    }
         1220  +#endif
  1207   1221     }
  1208   1222     return 0;
  1209   1223   }
  1210   1224   
  1211   1225   /*
  1212   1226   ** This routine walks an expression tree and resolves references to
  1213   1227   ** table columns.  Nodes of the form ID.ID or ID resolve into an
................................................................................
  1257   1271   struct QueryCoder {
  1258   1272     Parse *pParse;       /* The parsing context */
  1259   1273     NameContext *pNC;    /* Namespace of first enclosing query */
  1260   1274   };
  1261   1275   
  1262   1276   
  1263   1277   /*
  1264         -** Generate code for subqueries and IN operators.
  1265         -**
  1266         -** IN operators comes in two forms:
         1278  +** Generate code for scalar subqueries used as an expression
         1279  +** and IN operators.  Examples:
  1267   1280   **
  1268         -**           expr IN (exprlist)
  1269         -** and
  1270         -**           expr IN (SELECT ...)
         1281  +**     (SELECT a FROM b)          -- subquery
         1282  +**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
         1283  +**     x IN (4,5,11)              -- IN operator with list on right-hand side
         1284  +**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
  1271   1285   **
  1272         -** The first form is handled by creating a set holding the list
  1273         -** of allowed values.  The second form causes the SELECT to generate 
  1274         -** a temporary table.
         1286  +** The pExpr parameter describes the expression that contains the IN
         1287  +** operator or subquery.
  1275   1288   */
  1276   1289   #ifndef SQLITE_OMIT_SUBQUERY
  1277   1290   void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
  1278   1291     int testAddr = 0;                       /* One-time test address */
  1279   1292     Vdbe *v = sqlite3GetVdbe(pParse);
  1280   1293     if( v==0 ) return;
  1281   1294   
................................................................................
  1289   1302     ** If all of the above are false, then we can run this code just once
  1290   1303     ** save the results, and reuse the same result on subsequent invocations.
  1291   1304     */
  1292   1305     if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
  1293   1306       int mem = pParse->nMem++;
  1294   1307       sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
  1295   1308       testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
  1296         -    assert( testAddr>0 || sqlite3_malloc_failed );
         1309  +    assert( testAddr>0 || sqlite3ThreadData()->mallocFailed );
  1297   1310       sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
  1298   1311     }
  1299   1312   
  1300   1313     switch( pExpr->op ){
  1301   1314       case TK_IN: {
  1302   1315         char affinity;
  1303   1316         KeyInfo keyInfo;
................................................................................
  1386   1399   
  1387   1400       case TK_EXISTS:
  1388   1401       case TK_SELECT: {
  1389   1402         /* This has to be a scalar SELECT.  Generate code to put the
  1390   1403         ** value of this select in a memory cell and record the number
  1391   1404         ** of the memory cell in iColumn.
  1392   1405         */
  1393         -      int sop;
         1406  +      static const Token one = { (u8*)"1", 0, 1 };
  1394   1407         Select *pSel;
         1408  +      int iMem;
         1409  +      int sop;
  1395   1410   
  1396         -      pExpr->iColumn = pParse->nMem++;
         1411  +      pExpr->iColumn = iMem = pParse->nMem++;
  1397   1412         pSel = pExpr->pSelect;
  1398   1413         if( pExpr->op==TK_SELECT ){
  1399   1414           sop = SRT_Mem;
         1415  +        sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
         1416  +        VdbeComment((v, "# Init subquery result"));
  1400   1417         }else{
  1401         -        static const Token one = { "1", 0, 1 };
  1402   1418           sop = SRT_Exists;
  1403         -        sqlite3ExprListDelete(pSel->pEList);
  1404         -        pSel->pEList = sqlite3ExprListAppend(0, 
  1405         -                          sqlite3Expr(TK_INTEGER, 0, 0, &one), 0);
         1419  +        sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
         1420  +        VdbeComment((v, "# Init EXISTS result"));
  1406   1421         }
  1407         -      sqlite3Select(pParse, pSel, sop, pExpr->iColumn, 0, 0, 0, 0);
         1422  +      sqlite3ExprDelete(pSel->pLimit);
         1423  +      pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
         1424  +      sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0);
  1408   1425         break;
  1409   1426       }
  1410   1427     }
  1411   1428   
  1412   1429     if( testAddr ){
  1413   1430       sqlite3VdbeJumpHere(v, testAddr);
  1414   1431     }
................................................................................
  1440   1457   ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
  1441   1458   ** the make process cause these values to align.  Assert()s in the code
  1442   1459   ** below verify that the numbers are aligned correctly.
  1443   1460   */
  1444   1461   void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
  1445   1462     Vdbe *v = pParse->pVdbe;
  1446   1463     int op;
         1464  +  int stackChng = 1;    /* Amount of change to stack depth */
         1465  +
  1447   1466     if( v==0 ) return;
  1448   1467     if( pExpr==0 ){
  1449   1468       sqlite3VdbeAddOp(v, OP_Null, 0, 0);
  1450   1469       return;
  1451   1470     }
  1452   1471     op = pExpr->op;
  1453   1472     switch( op ){
................................................................................
  1461   1480           sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
  1462   1481                                 pCol->iSorterColumn);
  1463   1482           break;
  1464   1483         }
  1465   1484         /* Otherwise, fall thru into the TK_COLUMN case */
  1466   1485       }
  1467   1486       case TK_COLUMN: {
  1468         -      if( pExpr->iColumn>=0 ){
  1469         -        sqlite3VdbeAddOp(v, OP_Column, pExpr->iTable, pExpr->iColumn);
  1470         -        sqlite3ColumnDefault(v, pExpr->pTab, pExpr->iColumn);
         1487  +      if( pExpr->iTable<0 ){
         1488  +        /* This only happens when coding check constraints */
         1489  +        assert( pParse->ckOffset>0 );
         1490  +        sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
         1491  +      }else if( pExpr->iColumn>=0 ){
         1492  +        Table *pTab = pExpr->pTab;
         1493  +        int iCol = pExpr->iColumn;
         1494  +        sqlite3VdbeAddOp(v, OP_Column, pExpr->iTable, iCol);
         1495  +        sqlite3ColumnDefault(v, pTab, iCol);
         1496  +#ifndef SQLITE_OMIT_FLOATING_POINT
         1497  +        if( pTab && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
         1498  +          sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
         1499  +        }
         1500  +#endif
  1471   1501         }else{
  1472   1502           sqlite3VdbeAddOp(v, OP_Rowid, pExpr->iTable, 0);
  1473   1503         }
  1474   1504         break;
  1475   1505       }
  1476   1506       case TK_INTEGER: {
  1477         -      codeInteger(v, pExpr->token.z, pExpr->token.n);
         1507  +      codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
  1478   1508         break;
  1479   1509       }
  1480   1510       case TK_FLOAT:
  1481   1511       case TK_STRING: {
  1482   1512         assert( TK_FLOAT==OP_Real );
  1483   1513         assert( TK_STRING==OP_String8 );
  1484   1514         sqlite3DequoteExpr(pExpr);
  1485         -      sqlite3VdbeOp3(v, op, 0, 0, pExpr->token.z, pExpr->token.n);
         1515  +      sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
  1486   1516         break;
  1487   1517       }
  1488   1518       case TK_NULL: {
  1489   1519         sqlite3VdbeAddOp(v, OP_Null, 0, 0);
  1490   1520         break;
  1491   1521       }
  1492   1522   #ifndef SQLITE_OMIT_BLOB_LITERAL
  1493   1523       case TK_BLOB: {
  1494   1524         int n;
  1495   1525         const char *z;
  1496   1526         assert( TK_BLOB==OP_HexBlob );
  1497   1527         n = pExpr->token.n - 3;
  1498         -      z = pExpr->token.z + 2;
         1528  +      z = (char*)pExpr->token.z + 2;
  1499   1529         assert( n>=0 );
  1500   1530         if( n==0 ){
  1501   1531           z = "";
  1502   1532         }
  1503   1533         sqlite3VdbeOp3(v, op, 0, 0, z, n);
  1504   1534         break;
  1505   1535       }
  1506   1536   #endif
  1507   1537       case TK_VARIABLE: {
  1508   1538         sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
  1509   1539         if( pExpr->token.n>1 ){
  1510         -        sqlite3VdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
         1540  +        sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
  1511   1541         }
  1512   1542         break;
  1513   1543       }
  1514   1544       case TK_REGISTER: {
  1515   1545         sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
  1516   1546         break;
  1517   1547       }
  1518   1548   #ifndef SQLITE_OMIT_CAST
  1519   1549       case TK_CAST: {
  1520   1550         /* Expressions of the form:   CAST(pLeft AS token) */
  1521   1551         int aff, op;
  1522   1552         sqlite3ExprCode(pParse, pExpr->pLeft);
  1523   1553         aff = sqlite3AffinityType(&pExpr->token);
  1524         -      switch( aff ){
  1525         -        case SQLITE_AFF_INTEGER:   op = OP_ToInt;      break;
  1526         -        case SQLITE_AFF_NUMERIC:   op = OP_ToNumeric;  break;
  1527         -        case SQLITE_AFF_TEXT:      op = OP_ToText;     break;
  1528         -        case SQLITE_AFF_NONE:      op = OP_ToBlob;     break;
  1529         -      }
         1554  +      op = aff - SQLITE_AFF_TEXT + OP_ToText;
         1555  +      assert( op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
         1556  +      assert( op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
         1557  +      assert( op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
         1558  +      assert( op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
         1559  +      assert( op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
  1530   1560         sqlite3VdbeAddOp(v, op, 0, 0);
         1561  +      stackChng = 0;
  1531   1562         break;
  1532   1563       }
  1533   1564   #endif /* SQLITE_OMIT_CAST */
  1534   1565       case TK_LT:
  1535   1566       case TK_LE:
  1536   1567       case TK_GT:
  1537   1568       case TK_GE:
................................................................................
  1542   1573         assert( TK_GT==OP_Gt );
  1543   1574         assert( TK_GE==OP_Ge );
  1544   1575         assert( TK_EQ==OP_Eq );
  1545   1576         assert( TK_NE==OP_Ne );
  1546   1577         sqlite3ExprCode(pParse, pExpr->pLeft);
  1547   1578         sqlite3ExprCode(pParse, pExpr->pRight);
  1548   1579         codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
         1580  +      stackChng = -1;
  1549   1581         break;
  1550   1582       }
  1551   1583       case TK_AND:
  1552   1584       case TK_OR:
  1553   1585       case TK_PLUS:
  1554   1586       case TK_STAR:
  1555   1587       case TK_MINUS:
................................................................................
  1570   1602         assert( TK_SLASH==OP_Divide );
  1571   1603         assert( TK_LSHIFT==OP_ShiftLeft );
  1572   1604         assert( TK_RSHIFT==OP_ShiftRight );
  1573   1605         assert( TK_CONCAT==OP_Concat );
  1574   1606         sqlite3ExprCode(pParse, pExpr->pLeft);
  1575   1607         sqlite3ExprCode(pParse, pExpr->pRight);
  1576   1608         sqlite3VdbeAddOp(v, op, 0, 0);
         1609  +      stackChng = -1;
  1577   1610         break;
  1578   1611       }
  1579   1612       case TK_UMINUS: {
  1580   1613         Expr *pLeft = pExpr->pLeft;
  1581   1614         assert( pLeft );
  1582   1615         if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
  1583   1616           Token *p = &pLeft->token;
  1584         -        char *z = sqliteMalloc( p->n + 2 );
  1585         -        sprintf(z, "-%.*s", p->n, p->z);
         1617  +        char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
  1586   1618           if( pLeft->op==TK_FLOAT ){
  1587   1619             sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
  1588   1620           }else{
  1589   1621             codeInteger(v, z, p->n+1);
  1590   1622           }
  1591   1623           sqliteFree(z);
  1592   1624           break;
................................................................................
  1595   1627       }
  1596   1628       case TK_BITNOT:
  1597   1629       case TK_NOT: {
  1598   1630         assert( TK_BITNOT==OP_BitNot );
  1599   1631         assert( TK_NOT==OP_Not );
  1600   1632         sqlite3ExprCode(pParse, pExpr->pLeft);
  1601   1633         sqlite3VdbeAddOp(v, op, 0, 0);
         1634  +      stackChng = 0;
  1602   1635         break;
  1603   1636       }
  1604   1637       case TK_ISNULL:
  1605   1638       case TK_NOTNULL: {
  1606   1639         int dest;
  1607   1640         assert( TK_ISNULL==OP_IsNull );
  1608   1641         assert( TK_NOTNULL==OP_NotNull );
  1609   1642         sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
  1610   1643         sqlite3ExprCode(pParse, pExpr->pLeft);
  1611   1644         dest = sqlite3VdbeCurrentAddr(v) + 2;
  1612   1645         sqlite3VdbeAddOp(v, op, 1, dest);
  1613   1646         sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
         1647  +      stackChng = 0;
  1614   1648         break;
  1615   1649       }
  1616   1650       case TK_AGG_FUNCTION: {
  1617   1651         AggInfo *pInfo = pExpr->pAggInfo;
  1618         -      sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
         1652  +      if( pInfo==0 ){
         1653  +        sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
         1654  +            &pExpr->span);
         1655  +      }else{
         1656  +        sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
         1657  +      }
  1619   1658         break;
  1620   1659       }
  1621   1660       case TK_CONST_FUNC:
  1622   1661       case TK_FUNCTION: {
  1623   1662         ExprList *pList = pExpr->pList;
  1624   1663         int nExpr = pList ? pList->nExpr : 0;
  1625   1664         FuncDef *pDef;
  1626   1665         int nId;
  1627   1666         const char *zId;
  1628   1667         int constMask = 0;
  1629   1668         int i;
  1630         -      u8 enc = pParse->db->enc;
         1669  +      u8 enc = ENC(pParse->db);
  1631   1670         CollSeq *pColl = 0;
  1632         -      zId = pExpr->token.z;
         1671  +      zId = (char*)pExpr->token.z;
  1633   1672         nId = pExpr->token.n;
  1634   1673         pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
  1635   1674         assert( pDef!=0 );
  1636   1675         nExpr = sqlite3ExprCodeExprList(pParse, pList);
  1637   1676         for(i=0; i<nExpr && i<32; i++){
  1638   1677           if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
  1639   1678             constMask |= (1<<i);
................................................................................
  1643   1682           }
  1644   1683         }
  1645   1684         if( pDef->needCollSeq ){
  1646   1685           if( !pColl ) pColl = pParse->db->pDfltColl; 
  1647   1686           sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
  1648   1687         }
  1649   1688         sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
         1689  +      stackChng = 1-nExpr;
  1650   1690         break;
  1651   1691       }
  1652   1692   #ifndef SQLITE_OMIT_SUBQUERY
  1653   1693       case TK_EXISTS:
  1654   1694       case TK_SELECT: {
  1655   1695         sqlite3CodeSubselect(pParse, pExpr);
  1656   1696         sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
................................................................................
  1701   1741         codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
  1702   1742         sqlite3VdbeAddOp(v, OP_And, 0, 0);
  1703   1743         break;
  1704   1744       }
  1705   1745       case TK_UPLUS:
  1706   1746       case TK_AS: {
  1707   1747         sqlite3ExprCode(pParse, pExpr->pLeft);
         1748  +      stackChng = 0;
  1708   1749         break;
  1709   1750       }
  1710   1751       case TK_CASE: {
  1711   1752         int expr_end_label;
  1712   1753         int jumpInst;
  1713   1754         int nExpr;
  1714   1755         int i;
................................................................................
  1759   1800         }
  1760   1801         if( pExpr->iColumn!=OE_Ignore ){
  1761   1802            assert( pExpr->iColumn==OE_Rollback ||
  1762   1803                    pExpr->iColumn == OE_Abort ||
  1763   1804                    pExpr->iColumn == OE_Fail );
  1764   1805            sqlite3DequoteExpr(pExpr);
  1765   1806            sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
  1766         -                        pExpr->token.z, pExpr->token.n);
         1807  +                        (char*)pExpr->token.z, pExpr->token.n);
  1767   1808         } else {
  1768   1809            assert( pExpr->iColumn == OE_Ignore );
  1769   1810            sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
  1770   1811            sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
  1771   1812            VdbeComment((v, "# raise(IGNORE)"));
  1772   1813         }
         1814  +      stackChng = 0;
         1815  +      break;
  1773   1816       }
  1774   1817   #endif
  1775         -    break;
         1818  +  }
         1819  +
         1820  +  if( pParse->ckOffset ){
         1821  +    pParse->ckOffset += stackChng;
         1822  +    assert( pParse->ckOffset );
  1776   1823     }
  1777   1824   }
  1778   1825   
  1779   1826   #ifndef SQLITE_OMIT_TRIGGER
  1780   1827   /*
  1781   1828   ** Generate code that evalutes the given expression and leaves the result
  1782   1829   ** on the stack.  See also sqlite3ExprCode().
................................................................................
  1836   1883   ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
  1837   1884   ** the make process cause these values to align.  Assert()s in the code
  1838   1885   ** below verify that the numbers are aligned correctly.
  1839   1886   */
  1840   1887   void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  1841   1888     Vdbe *v = pParse->pVdbe;
  1842   1889     int op = 0;
         1890  +  int ckOffset = pParse->ckOffset;
  1843   1891     if( v==0 || pExpr==0 ) return;
  1844   1892     op = pExpr->op;
  1845   1893     switch( op ){
  1846   1894       case TK_AND: {
  1847   1895         int d2 = sqlite3VdbeMakeLabel(v);
  1848   1896         sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
  1849   1897         sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
................................................................................
  1910   1958       }
  1911   1959       default: {
  1912   1960         sqlite3ExprCode(pParse, pExpr);
  1913   1961         sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
  1914   1962         break;
  1915   1963       }
  1916   1964     }
         1965  +  pParse->ckOffset = ckOffset;
  1917   1966   }
  1918   1967   
  1919   1968   /*
  1920   1969   ** Generate code for a boolean expression such that a jump is made
  1921   1970   ** to the label "dest" if the expression is false but execution
  1922   1971   ** continues straight thru if the expression is true.
  1923   1972   **
  1924   1973   ** If the expression evaluates to NULL (neither true nor false) then
  1925   1974   ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
  1926   1975   */
  1927   1976   void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  1928   1977     Vdbe *v = pParse->pVdbe;
  1929   1978     int op = 0;
         1979  +  int ckOffset = pParse->ckOffset;
  1930   1980     if( v==0 || pExpr==0 ) return;
  1931   1981   
  1932   1982     /* The value of pExpr->op and op are related as follows:
  1933   1983     **
  1934   1984     **       pExpr->op            op
  1935   1985     **       ---------          ----------
  1936   1986     **       TK_ISNULL          OP_NotNull
................................................................................
  2019   2069       }
  2020   2070       default: {
  2021   2071         sqlite3ExprCode(pParse, pExpr);
  2022   2072         sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
  2023   2073         break;
  2024   2074       }
  2025   2075     }
         2076  +  pParse->ckOffset = ckOffset;
  2026   2077   }
  2027   2078   
  2028   2079   /*
  2029   2080   ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
  2030   2081   ** if they are identical and return FALSE if they differ in any way.
  2031   2082   */
  2032   2083   int sqlite3ExprCompare(Expr *pA, Expr *pB){
................................................................................
  2052   2103       return 0;
  2053   2104     }
  2054   2105     if( pA->pSelect || pB->pSelect ) return 0;
  2055   2106     if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
  2056   2107     if( pA->token.z ){
  2057   2108       if( pB->token.z==0 ) return 0;
  2058   2109       if( pB->token.n!=pA->token.n ) return 0;
  2059         -    if( sqlite3StrNICmp(pA->token.z, pB->token.z, pB->token.n)!=0 ) return 0;
         2110  +    if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
         2111  +      return 0;
         2112  +    }
  2060   2113     }
  2061   2114     return 1;
  2062   2115   }
  2063   2116   
  2064   2117   
  2065   2118   /*
  2066   2119   ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
................................................................................
  2176   2229             if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
  2177   2230               break;
  2178   2231             }
  2179   2232           }
  2180   2233           if( i>=pAggInfo->nFunc ){
  2181   2234             /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
  2182   2235             */
  2183         -          u8 enc = pParse->db->enc;
         2236  +          u8 enc = ENC(pParse->db);
  2184   2237             i = addAggInfoFunc(pAggInfo);
  2185   2238             if( i>=0 ){
  2186   2239               pItem = &pAggInfo->aFunc[i];
  2187   2240               pItem->pExpr = pExpr;
  2188   2241               pItem->iMem = pParse->nMem++;
  2189   2242               pItem->pFunc = sqlite3FindFunction(pParse->db,
  2190         -                   pExpr->token.z, pExpr->token.n,
         2243  +                   (char*)pExpr->token.z, pExpr->token.n,
  2191   2244                      pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
  2192   2245               if( pExpr->flags & EP_Distinct ){
  2193   2246                 pItem->iDistinct = pParse->nTab++;
  2194   2247               }else{
  2195   2248                 pItem->iDistinct = -1;
  2196   2249               }
  2197   2250             }

Changes to SQLite.Interop/src/func.c.

    12     12   ** This file contains the C functions that implement various SQL
    13     13   ** functions of SQLite.  
    14     14   **
    15     15   ** There is only one exported symbol in this file - the function
    16     16   ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
    17     17   ** All other code has file scope.
    18     18   **
    19         -** $Id: func.c,v 1.11 2005/12/19 17:57:46 rmsimpson Exp $
           19  +** $Id: func.c,v 1.12 2006/01/10 18:40:37 rmsimpson Exp $
    20     20   */
    21     21   #include "sqliteInt.h"
    22     22   #include <ctype.h>
    23         -#include <math.h>
           23  +/* #include <math.h> */
    24     24   #include <stdlib.h>
    25     25   #include <assert.h>
    26     26   #include "vdbeInt.h"
    27     27   #include "os.h"
    28     28   
    29     29   /*
    30     30   ** Return the collating function associated with a function.
................................................................................
    97     97       case SQLITE_BLOB:
    98     98       case SQLITE_INTEGER:
    99     99       case SQLITE_FLOAT: {
   100    100         sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
   101    101         break;
   102    102       }
   103    103       case SQLITE_TEXT: {
   104         -      const char *z = sqlite3_value_text(argv[0]);
          104  +      const unsigned char *z = sqlite3_value_text(argv[0]);
   105    105         for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
   106    106         sqlite3_result_int(context, len);
   107    107         break;
   108    108       }
   109    109       default: {
   110    110         sqlite3_result_null(context);
   111    111         break;
................................................................................
   142    142   ** Implementation of the substr() function
   143    143   */
   144    144   static void substrFunc(
   145    145     sqlite3_context *context,
   146    146     int argc,
   147    147     sqlite3_value **argv
   148    148   ){
   149         -  const char *z;
   150         -  const char *z2;
          149  +  const unsigned char *z;
          150  +  const unsigned char *z2;
   151    151     int i;
   152    152     int p1, p2, len;
   153    153   
   154    154     assert( argc==3 );
   155    155     z = sqlite3_value_text(argv[0]);
   156    156     if( z==0 ) return;
   157    157     p1 = sqlite3_value_int(argv[1]);
................................................................................
   174    174     }
   175    175     while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
   176    176     for(; i<p1+p2 && z[i]; i++){
   177    177       if( (z[i]&0xc0)==0x80 ) p2++;
   178    178     }
   179    179     while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
   180    180     if( p2<0 ) p2 = 0;
   181         -  sqlite3_result_text(context, &z[p1], p2, SQLITE_TRANSIENT);
          181  +  sqlite3_result_text(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
   182    182   }
   183    183   
   184    184   /*
   185    185   ** Implementation of the round() function
   186    186   */
   187    187   static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   188    188     int n = 0;
................................................................................
   206    206   */
   207    207   static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   208    208     unsigned char *z;
   209    209     int i;
   210    210     if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
   211    211     z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
   212    212     if( z==0 ) return;
   213         -  strcpy(z, sqlite3_value_text(argv[0]));
          213  +  strcpy((char*)z, (char*)sqlite3_value_text(argv[0]));
   214    214     for(i=0; z[i]; i++){
   215    215       z[i] = toupper(z[i]);
   216    216     }
   217         -  sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
          217  +  sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
   218    218     sqliteFree(z);
   219    219   }
   220    220   static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   221    221     unsigned char *z;
   222    222     int i;
   223    223     if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
   224    224     z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
   225    225     if( z==0 ) return;
   226         -  strcpy(z, sqlite3_value_text(argv[0]));
          226  +  strcpy((char*)z, (char*)sqlite3_value_text(argv[0]));
   227    227     for(i=0; z[i]; i++){
   228    228       z[i] = tolower(z[i]);
   229    229     }
   230         -  sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
          230  +  sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
   231    231     sqliteFree(z);
   232    232   }
   233    233   
   234    234   /*
   235    235   ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
   236    236   ** All three do the same thing.  They return the first non-NULL
   237    237   ** argument.
................................................................................
   491    491     const unsigned char *zB = sqlite3_value_text(argv[1]);
   492    492     int escape = 0;
   493    493     if( argc==3 ){
   494    494       /* The escape character string must consist of a single UTF-8 character.
   495    495       ** Otherwise, return an error.
   496    496       */
   497    497       const unsigned char *zEsc = sqlite3_value_text(argv[2]);
   498         -    if( sqlite3utf8CharLen(zEsc, -1)!=1 ){
          498  +    if( sqlite3utf8CharLen((char*)zEsc, -1)!=1 ){
   499    499         sqlite3_result_error(context, 
   500    500             "ESCAPE expression must be a single character", -1);
   501    501         return;
   502    502       }
   503    503       escape = sqlite3ReadUtf8(zEsc);
   504    504     }
   505    505     if( zA && zB ){
................................................................................
   588    588           sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
   589    589           sqliteFree(zText);
   590    590         }
   591    591         break;
   592    592       }
   593    593       case SQLITE_TEXT: {
   594    594         int i,j,n;
   595         -      const char *zArg = sqlite3_value_text(argv[0]);
          595  +      const unsigned char *zArg = sqlite3_value_text(argv[0]);
   596    596         char *z;
   597    597   
   598    598         for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   599    599         z = sqliteMalloc( i+n+3 );
   600    600         if( z==0 ) return;
   601    601         z[0] = '\'';
   602    602         for(i=0, j=1; zArg[i]; i++){
................................................................................
   688    688     }
   689    689     assert( n<sizeof(zBuf) );
   690    690     sqlite3Randomness(n, zBuf);
   691    691     for(i=0; i<n; i++){
   692    692       zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
   693    693     }
   694    694     zBuf[n] = 0;
   695         -  sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
          695  +  sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
   696    696   }
   697    697   #endif /* SQLITE_TEST */
   698    698   
   699    699   #ifdef SQLITE_TEST
   700    700   /*
   701    701   ** The following two SQL functions are used to test returning a text
   702    702   ** result with a destructor. Function 'test_destructor' takes one argument
................................................................................
   724    724     char *zVal;
   725    725     int len;
   726    726     sqlite3 *db = sqlite3_user_data(pCtx);
   727    727    
   728    728     test_destructor_count_var++;
   729    729     assert( nArg==1 );
   730    730     if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   731         -  len = sqlite3ValueBytes(argv[0], db->enc); 
          731  +  len = sqlite3ValueBytes(argv[0], ENC(db)); 
   732    732     zVal = sqliteMalloc(len+3);
   733    733     zVal[len] = 0;
   734    734     zVal[len-1] = 0;
   735    735     assert( zVal );
   736    736     zVal++;
   737         -  memcpy(zVal, sqlite3ValueText(argv[0], db->enc), len);
   738         -  if( db->enc==SQLITE_UTF8 ){
          737  +  memcpy(zVal, sqlite3ValueText(argv[0], ENC(db)), len);
          738  +  if( ENC(db)==SQLITE_UTF8 ){
   739    739       sqlite3_result_text(pCtx, zVal, -1, destructor);
   740    740   #ifndef SQLITE_OMIT_UTF16
   741         -  }else if( db->enc==SQLITE_UTF16LE ){
          741  +  }else if( ENC(db)==SQLITE_UTF16LE ){
   742    742       sqlite3_result_text16le(pCtx, zVal, -1, destructor);
   743    743     }else{
   744    744       sqlite3_result_text16be(pCtx, zVal, -1, destructor);
   745    745   #endif /* SQLITE_OMIT_UTF16 */
   746    746     }
   747    747   }
   748    748   static void test_destructor_count(
................................................................................
   772    772     int nArg,
   773    773     sqlite3_value **argv
   774    774   ){
   775    775     int i;
   776    776     char *zRet = sqliteMalloc(nArg*2);
   777    777     if( !zRet ) return;
   778    778     for(i=0; i<nArg; i++){
   779         -    char const *z = sqlite3_value_text(argv[i]);
          779  +    char const *z = (char*)sqlite3_value_text(argv[i]);
   780    780       if( z ){
   781    781         char *zAux = sqlite3_get_auxdata(pCtx, i);
   782    782         if( zAux ){
   783    783           zRet[i*2] = '1';
   784    784           if( strcmp(zAux, z) ){
   785    785             sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
   786    786             return;
................................................................................
   803    803   ** returns a copy of it's first argument as an error.
   804    804   */
   805    805   static void test_error(
   806    806     sqlite3_context *pCtx, 
   807    807     int nArg,
   808    808     sqlite3_value **argv
   809    809   ){
   810         -  sqlite3_result_error(pCtx, sqlite3_value_text(argv[0]), 0);
          810  +  sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), 0);
   811    811   }
   812    812   #endif /* SQLITE_TEST */
   813    813   
   814    814   /*
   815    815   ** An instance of the following structure holds the context of a
   816    816   ** sum() or avg() aggregate computation.
   817    817   */
................................................................................
  1021   1021           pFunc->needCollSeq = 1;
  1022   1022         }
  1023   1023       }
  1024   1024     }
  1025   1025   #ifndef SQLITE_OMIT_ALTERTABLE
  1026   1026     sqlite3AlterFunctions(db);
  1027   1027   #endif
         1028  +#ifndef SQLITE_OMIT_PARSER
         1029  +  sqlite3AttachFunctions(db);
         1030  +#endif
  1028   1031     for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
  1029   1032       void *pArg = 0;
  1030   1033       switch( aAggs[i].argType ){
  1031   1034         case 1: pArg = db; break;
  1032   1035         case 2: pArg = (void *)(-1); break;
  1033   1036       }
  1034   1037       sqlite3_create_function(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8, 
................................................................................
  1095   1098     FuncDef *pDef;
  1096   1099     if( pExpr->op!=TK_FUNCTION ){
  1097   1100       return 0;
  1098   1101     }
  1099   1102     if( pExpr->pList->nExpr!=2 ){
  1100   1103       return 0;
  1101   1104     }
  1102         -  pDef = sqlite3FindFunction(db, pExpr->token.z, pExpr->token.n, 2,
         1105  +  pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
  1103   1106                                SQLITE_UTF8, 0);
  1104   1107     if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
  1105   1108       return 0;
  1106   1109     }
  1107   1110   
  1108   1111     /* The memcpy() statement assumes that the wildcard characters are
  1109   1112     ** the first three statements in the compareInfo structure.  The

Changes to SQLite.Interop/src/hash.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This is the implementation of generic hash-tables
    13     13   ** used in SQLite.
    14     14   **
    15         -** $Id: hash.c,v 1.10 2005/12/19 17:57:47 rmsimpson Exp $
           15  +** $Id: hash.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   #include <assert.h>
    19     19   
    20     20   /* Turn bulk memory into a hash table object by initializing the
    21     21   ** fields of the Hash structure.
    22     22   **
................................................................................
   290    290       pEntry->chain = 0;
   291    291     }
   292    292     if( pH->copyKey && elem->pKey ){
   293    293       sqliteFree(elem->pKey);
   294    294     }
   295    295     sqliteFree( elem );
   296    296     pH->count--;
          297  +  if( pH->count<=0 ){
          298  +    assert( pH->first==0 );
          299  +    assert( pH->count==0 );
          300  +    sqlite3HashClear(pH);
          301  +  }
   297    302   }
   298    303   
   299    304   /* Attempt to locate an element of the hash table pH with a key
   300    305   ** that matches pKey,nKey.  Return the data for this element if it is
   301    306   ** found, or NULL if there is no match.
   302    307   */
   303    308   void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){

Changes to SQLite.Interop/src/hash.h.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This is the header file for the generic hash-table implemenation
    13     13   ** used in SQLite.
    14     14   **
    15         -** $Id: hash.h,v 1.10 2005/12/19 17:57:47 rmsimpson Exp $
           15  +** $Id: hash.h,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    16     16   */
    17     17   #ifndef _SQLITE_HASH_H_
    18     18   #define _SQLITE_HASH_H_
    19     19   
    20     20   /* Forward declarations of structures. */
    21     21   typedef struct Hash Hash;
    22     22   typedef struct HashElem HashElem;

Changes to SQLite.Interop/src/insert.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains C code routines that are called by the parser
    13     13   ** to handle INSERT statements in SQLite.
    14     14   **
    15         -** $Id: insert.c,v 1.10 2005/12/19 17:57:47 rmsimpson Exp $
           15  +** $Id: insert.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   /*
    20     20   ** Set P3 of the most recently inserted opcode to a column affinity
    21     21   ** string for index pIdx. A column affinity string has one character
    22     22   ** for each column in the table, according to the affinity of the column:
    23     23   **
    24     24   **  Character      Column affinity
    25     25   **  ------------------------------
    26         -**  'n'            NUMERIC
    27         -**  'i'            INTEGER
    28         -**  't'            TEXT
    29         -**  'o'            NONE
           26  +**  'a'            TEXT
           27  +**  'b'            NONE
           28  +**  'c'            NUMERIC
           29  +**  'd'            INTEGER
           30  +**  'e'            REAL
    30     31   */
    31     32   void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
    32     33     if( !pIdx->zColAff ){
    33     34       /* The first time a column affinity string for a particular index is
    34     35       ** required, it is allocated and populated here. It is then stored as
    35     36       ** a member of the Index structure for subsequent use.
    36     37       **
................................................................................
    57     58   ** Set P3 of the most recently inserted opcode to a column affinity
    58     59   ** string for table pTab. A column affinity string has one character
    59     60   ** for each column indexed by the index, according to the affinity of the
    60     61   ** column:
    61     62   **
    62     63   **  Character      Column affinity
    63     64   **  ------------------------------
    64         -**  'n'            NUMERIC
    65         -**  'i'            INTEGER
    66         -**  't'            TEXT
    67         -**  'o'            NONE
           65  +**  'a'            TEXT
           66  +**  'b'            NONE
           67  +**  'c'            NUMERIC
           68  +**  'd'            INTEGER
           69  +**  'e'            REAL
    68     70   */
    69     71   void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
    70     72     /* The first time a column affinity string for a particular table
    71     73     ** is required, it is allocated and populated here. It is then 
    72     74     ** stored as a member of the Table structure for subsequent use.
    73     75     **
    74     76     ** The column affinity string will eventually be deleted by
................................................................................
    98    100   ** Return non-zero if SELECT statement p opens the table with rootpage
    99    101   ** iTab in database iDb.  This is used to see if a statement of the form 
   100    102   ** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
   101    103   ** table for the results of the SELECT. 
   102    104   **
   103    105   ** No checking is done for sub-selects that are part of expressions.
   104    106   */
   105         -static int selectReadsTable(Select *p, int iDb, int iTab){
          107  +static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
   106    108     int i;
   107    109     struct SrcList_item *pItem;
   108    110     if( p->pSrc==0 ) return 0;
   109    111     for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
   110    112       if( pItem->pSelect ){
   111         -      if( selectReadsTable(pItem->pSelect, iDb, iTab) ) return 1;
          113  +      if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
   112    114       }else{
   113         -      if( pItem->pTab->iDb==iDb && pItem->pTab->tnum==iTab ) return 1;
          115  +      if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
   114    116       }
   115    117     }
   116    118     return 0;
   117    119   }
   118    120   
   119    121   /*
   120    122   ** This routine is call to handle SQL of the following forms:
................................................................................
   208    210     int iSelectLoop = 0;  /* Address of code that implements the SELECT */
   209    211     int iCleanup = 0;     /* Address of the cleanup code */
   210    212     int iInsertBlock = 0; /* Address of the subroutine used to insert data */
   211    213     int iCntMem = 0;      /* Memory cell used for the row counter */
   212    214     int newIdx = -1;      /* Cursor for the NEW table */
   213    215     Db *pDb;              /* The database containing table being inserted into */
   214    216     int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
          217  +  int iDb;
   215    218   
   216    219   #ifndef SQLITE_OMIT_TRIGGER
   217    220     int isView;                 /* True if attempting to insert into a view */
   218    221     int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
   219    222   #endif
   220    223   
   221    224   #ifndef SQLITE_OMIT_AUTOINCREMENT
   222    225     int counterRowid;     /* Memory cell holding rowid of autoinc counter */
   223    226   #endif
   224    227   
   225         -  if( pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup;
          228  +  if( pParse->nErr || sqlite3ThreadData()->mallocFailed ) goto insert_cleanup;
   226    229     db = pParse->db;
   227    230   
   228    231     /* Locate the table into which we will be inserting new information.
   229    232     */
   230    233     assert( pTabList->nSrc==1 );
   231    234     zTab = pTabList->a[0].zName;
   232    235     if( zTab==0 ) goto insert_cleanup;
   233    236     pTab = sqlite3SrcListLookup(pParse, pTabList);
   234    237     if( pTab==0 ){
   235    238       goto insert_cleanup;
   236    239     }
   237         -  assert( pTab->iDb<db->nDb );
   238         -  pDb = &db->aDb[pTab->iDb];
          240  +  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
          241  +  assert( iDb<db->nDb );
          242  +  pDb = &db->aDb[iDb];
   239    243     zDb = pDb->zName;
   240    244     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
   241    245       goto insert_cleanup;
   242    246     }
   243    247   
   244    248     /* Figure out if we have any triggers and if the table being
   245    249     ** inserted into is a view
................................................................................
   279    283     }
   280    284   
   281    285     /* Allocate a VDBE
   282    286     */
   283    287     v = sqlite3GetVdbe(pParse);
   284    288     if( v==0 ) goto insert_cleanup;
   285    289     if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   286         -  sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, pTab->iDb);
          290  +  sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
   287    291   
   288    292     /* if there are row triggers, allocate a temp table for new.* references. */
   289    293     if( triggers_exist ){
   290    294       newIdx = pParse->nTab++;
   291    295     }
   292    296   
   293    297   #ifndef SQLITE_OMIT_AUTOINCREMENT
................................................................................
   297    301     ** counterRowid.
   298    302     */
   299    303     if( pTab->autoInc ){
   300    304       int iCur = pParse->nTab;
   301    305       int base = sqlite3VdbeCurrentAddr(v);
   302    306       counterRowid = pParse->nMem++;
   303    307       counterMem = pParse->nMem++;
   304         -    sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
   305         -    sqlite3VdbeAddOp(v, OP_OpenRead, iCur, pDb->pSeqTab->tnum);
   306         -    sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, 2);
          308  +    sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   307    309       sqlite3VdbeAddOp(v, OP_Rewind, iCur, base+13);
   308    310       sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
   309    311       sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
   310         -    sqlite3VdbeAddOp(v, OP_Ne, 28417, base+12);
          312  +    sqlite3VdbeAddOp(v, OP_Ne, 0x100, base+12);
   311    313       sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
   312    314       sqlite3VdbeAddOp(v, OP_MemStore, counterRowid, 1);
   313    315       sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
   314    316       sqlite3VdbeAddOp(v, OP_MemStore, counterMem, 1);
   315    317       sqlite3VdbeAddOp(v, OP_Goto, 0, base+13);
   316    318       sqlite3VdbeAddOp(v, OP_Next, iCur, base+4);
   317    319       sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
................................................................................
   332    334       int rc, iInitCode;
   333    335       iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
   334    336       iSelectLoop = sqlite3VdbeCurrentAddr(v);
   335    337       iInsertBlock = sqlite3VdbeMakeLabel(v);
   336    338   
   337    339       /* Resolve the expressions in the SELECT statement and execute it. */
   338    340       rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
   339         -    if( rc || pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup;
          341  +    if( rc || pParse->nErr || sqlite3ThreadData()->mallocFailed ) goto insert_cleanup;
   340    342   
   341    343       iCleanup = sqlite3VdbeMakeLabel(v);
   342    344       sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
   343    345       assert( pSelect->pEList );
   344    346       nColumn = pSelect->pEList->nExpr;
   345    347   
   346    348       /* Set useTempTable to TRUE if the result of the SELECT statement
................................................................................
   347    349       ** should be written into a temporary table.  Set to FALSE if each
   348    350       ** row of the SELECT can be written directly into the result table.
   349    351       **
   350    352       ** A temp table must be used if the table being updated is also one
   351    353       ** of the tables being read by the SELECT statement.  Also use a 
   352    354       ** temp table in the case of row triggers.
   353    355       */
   354         -    if( triggers_exist || selectReadsTable(pSelect, pTab->iDb, pTab->tnum) ){
          356  +    if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
   355    357         useTempTable = 1;
   356    358       }
   357    359   
   358    360       if( useTempTable ){
   359    361         /* Generate the subroutine that SELECT calls to process each row of
   360    362         ** the result.  Store the result in a temporary table
   361    363         */
   362    364         srcTab = pParse->nTab++;
   363    365         sqlite3VdbeResolveLabel(v, iInsertBlock);
   364    366         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
   365         -      sqlite3TableAffinityStr(v, pTab);
   366    367         sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
   367    368         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
   368    369         sqlite3VdbeAddOp(v, OP_Insert, srcTab, 0);
   369    370         sqlite3VdbeAddOp(v, OP_Return, 0, 0);
   370    371   
   371    372         /* The following code runs first because the GOTO at the very top
   372    373         ** of the program jumps to it.  Create the temporary table, then jump
................................................................................
   631    632       sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
   632    633                               (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1);
   633    634     }
   634    635   
   635    636     /* Update the count of rows that are inserted
   636    637     */
   637    638     if( (db->flags & SQLITE_CountRows)!=0 ){
   638         -    sqlite3VdbeAddOp(v, OP_MemIncr, iCntMem, 0);
          639  +    sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
   639    640     }
   640    641   
   641    642     if( triggers_exist ){
   642    643       /* Close all tables opened */
   643    644       if( !isView ){
   644    645         sqlite3VdbeAddOp(v, OP_Close, base, 0);
   645    646         for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
................................................................................
   679    680     /* Update the sqlite_sequence table by storing the content of the
   680    681     ** counter value in memory counterMem back into the sqlite_sequence
   681    682     ** table.
   682    683     */
   683    684     if( pTab->autoInc ){
   684    685       int iCur = pParse->nTab;
   685    686       int base = sqlite3VdbeCurrentAddr(v);
   686         -    sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
   687         -    sqlite3VdbeAddOp(v, OP_OpenWrite, iCur, pDb->pSeqTab->tnum);
   688         -    sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, 2);
          687  +    sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   689    688       sqlite3VdbeAddOp(v, OP_MemLoad, counterRowid, 0);
   690    689       sqlite3VdbeAddOp(v, OP_NotNull, -1, base+7);
   691    690       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
   692    691       sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
   693    692       sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
   694    693       sqlite3VdbeAddOp(v, OP_MemLoad, counterMem, 0);
   695    694       sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
................................................................................
   866    865         }
   867    866       }
   868    867       sqlite3VdbeJumpHere(v, addr);
   869    868     }
   870    869   
   871    870     /* Test all CHECK constraints
   872    871     */
   873         -  /**** TBD ****/
          872  +#ifndef SQLITE_OMIT_CHECK
          873  +  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
          874  +    int allOk = sqlite3VdbeMakeLabel(v);
          875  +    assert( pParse->ckOffset==0 );
          876  +    pParse->ckOffset = nCol;
          877  +    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
          878  +    assert( pParse->ckOffset==nCol );
          879  +    pParse->ckOffset = 0;
          880  +    sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort);
          881  +    sqlite3VdbeResolveLabel(v, allOk);
          882  +  }
          883  +#endif /* !defined(SQLITE_OMIT_CHECK) */
   874    884   
   875    885     /* If we have an INTEGER PRIMARY KEY, make sure the primary key
   876    886     ** of the new record does not previously exist.  Except, if this
   877    887     ** is an UPDATE and the primary key is not changing, that is OK.
   878    888     */
   879    889     if( rowidChng ){
   880    890       onError = pTab->keyConf;
................................................................................
  1063   1073       sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
  1064   1074       sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
  1065   1075     }
  1066   1076   #endif
  1067   1077     if( pParse->nested ){
  1068   1078       pik_flags = 0;
  1069   1079     }else{
  1070         -    pik_flags = (OPFLAG_NCHANGE|(isUpdate?0:OPFLAG_LASTROWID));
         1080  +    pik_flags = OPFLAG_NCHANGE;
         1081  +    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  1071   1082     }
  1072   1083     sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
         1084  +  if( !pParse->nested ){
         1085  +    sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
         1086  +  }
  1073   1087     
  1074   1088     if( isUpdate && rowidChng ){
  1075   1089       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  1076   1090     }
  1077   1091   }
  1078   1092   
  1079   1093   /*
................................................................................
  1084   1098   void sqlite3OpenTableAndIndices(
  1085   1099     Parse *pParse,   /* Parsing context */
  1086   1100     Table *pTab,     /* Table to be opened */
  1087   1101     int base,        /* Cursor number assigned to the table */
  1088   1102     int op           /* OP_OpenRead or OP_OpenWrite */
  1089   1103   ){
  1090   1104     int i;
         1105  +  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  1091   1106     Index *pIdx;
  1092   1107     Vdbe *v = sqlite3GetVdbe(pParse);
  1093   1108     assert( v!=0 );
  1094         -  sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
  1095         -  VdbeComment((v, "# %s", pTab->zName));
  1096         -  sqlite3VdbeAddOp(v, op, base, pTab->tnum);
  1097         -  sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol);
         1109  +  sqlite3OpenTable(pParse, base, iDb, pTab, op);
  1098   1110     for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  1099         -    sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
         1111  +    assert( pIdx->pSchema==pTab->pSchema );
         1112  +    sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  1100   1113       VdbeComment((v, "# %s", pIdx->zName));
  1101   1114       sqlite3VdbeOp3(v, op, i+base, pIdx->tnum,
  1102   1115                      (char*)&pIdx->keyInfo, P3_KEYINFO);
  1103   1116     }
  1104   1117     if( pParse->nTab<=base+i ){
  1105   1118       pParse->nTab = base+i;
  1106   1119     }
  1107   1120   }

Changes to SQLite.Interop/src/keywordhash.h.

     1         -/* Hash score: 158 */
            1  +/* Hash score: 159 */
     2      2   static int keywordCode(const char *z, int n){
     3         -  static const char zText[535] =
            3  +  static const char zText[537] =
     4      4       "ABORTABLEFTEMPORARYADDATABASELECTHENDEFAULTRANSACTIONATURALTER"
     5      5       "AISEACHECKEYAFTEREFERENCESCAPELSEXCEPTRIGGEREGEXPLAINITIALLYANALYZE"
     6      6       "XCLUSIVEXISTSTATEMENTANDEFERRABLEATTACHAVINGLOBEFOREIGNOREINDEX"
     7      7       "AUTOINCREMENTBEGINNERENAMEBETWEENOTNULLIKEBYCASCADEFERREDELETE"
     8      8       "CASECASTCOLLATECOLUMNCOMMITCONFLICTCONSTRAINTERSECTCREATECROSS"
     9      9       "CURRENT_DATECURRENT_TIMESTAMPLANDESCDETACHDISTINCTDROPRAGMATCH"
    10         -    "FAILIMITFROMFULLGROUPDATEIMMEDIATEINSERTINSTEADINTOFFSETISNULL"
           10  +    "FAILIMITFROMFULLGROUPDATEIFIMMEDIATEINSERTINSTEADINTOFFSETISNULL"
    11     11       "JOINORDEREPLACEOUTERESTRICTPRIMARYQUERYRIGHTROLLBACKROWHENUNION"
    12     12       "UNIQUEUSINGVACUUMVALUESVIEWHERE";
    13     13     static const unsigned char aHash[127] = {
    14         -      91,  80, 106,  90,   0,   4,   0,   0, 113,   0,  83,   0,   0,
    15         -      94,  44,  76,  92,   0, 105, 108,  96,   0,   0,  10,   0,   0,
    16         -     112,   0, 109, 102,   0,  28,  48,   0,  41,   0,   0,  65,  71,
    17         -       0,  63,  19,   0, 104,  36, 103,   0, 107,  74,   0,   0,  33,
    18         -       0,  61,  37,   0,   8,   0, 114,  38,  12,   0,  77,  40,  25,
           14  +      92,  80, 107,  91,   0,   4,   0,   0, 114,   0,  83,   0,   0,
           15  +      96,  44,  76,  93,   0, 106, 109,  97,  90,   0,  10,   0,   0,
           16  +     113,   0, 110, 103,   0,  28,  48,   0,  41,   0,   0,  65,  71,
           17  +       0,  63,  19,   0, 105,  36, 104,   0, 108,  75,   0,   0,  33,
           18  +       0,  61,  37,   0,   8,   0, 115,  38,  12,   0,  77,  40,  25,
    19     19         66,   0,   0,  31,  81,  53,  30,  50,  20,  88,   0,  34,   0,
    20         -      75,  26,   0,  72,   0,   0,   0,  64,  47,  67,  22,  87,  29,
    21         -      69,  86,   0,   1,   0,   9, 100,  58,  18,   0, 111,  82,  98,
    22         -      54,   6,  85,   0,   0,  49,  93,   0, 101,   0,  70,   0,   0,
    23         -      15,   0, 115,  51,  56,   0,   2,  55,   0, 110,
           20  +      74,  26,   0,  72,   0,   0,   0,  64,  47,  67,  22,  87,  29,
           21  +      69,  86,   0,   1,   0,   9, 101,  58,  18,   0, 112,  82,  99,
           22  +      55,   6,  85,   0,   0,  49,  94,   0, 102,   0,  70,   0,   0,
           23  +      15,   0, 116,  51,  56,   0,   2,  54,   0, 111,
    24     24     };
    25         -  static const unsigned char aNext[115] = {
           25  +  static const unsigned char aNext[116] = {
    26     26          0,   0,   0,   0,   0,   3,   0,   0,   0,   0,   0,   0,   0,
    27     27          0,   0,   0,   0,   0,   0,   0,   0,  17,   0,   0,   0,   0,
    28     28          0,  11,   0,   0,   0,   0,   5,  13,   0,   7,   0,   0,   0,
    29         -       0,   0,   0,   0,   0,   0,   0,  43,   0,   0,   0,   0,   0,
    30         -       0,   0,  16,   0,  23,  52,   0,   0,   0,   0,  45,   0,  59,
    31         -       0,   0,   0,   0,   0,   0,   0,   0,  73,  42,   0,  24,  60,
           29  +       0,   0,   0,   0,   0,   0,   0,  42,   0,   0,   0,   0,   0,
           30  +       0,  16,   0,   0,  23,  52,   0,   0,   0,   0,  45,   0,  59,
           31  +       0,   0,   0,   0,   0,   0,   0,   0,  43,  73,   0,  24,  60,
    32     32         21,   0,  79,   0,   0,  68,   0,   0,  84,  46,   0,   0,   0,
    33         -       0,   0,   0,   0,  39,  95,  97,   0,   0,  99,   0,  32,   0,
    34         -      14,  27,  78,   0,  57,  89,   0,  35,   0,  62,   0,
           33  +       0,   0,   0,   0,   0,  39,  95,  98,   0,   0, 100,   0,  32,
           34  +       0,  14,  27,  78,   0,  57,  89,   0,  35,   0,  62,   0,
    35     35     };
    36         -  static const unsigned char aLen[115] = {
           36  +  static const unsigned char aLen[116] = {
    37     37          5,   5,   4,   4,   9,   2,   3,   8,   2,   6,   4,   3,   7,
    38     38         11,   2,   7,   5,   5,   4,   5,   3,   5,  10,   6,   4,   6,
    39     39          7,   6,   7,   9,   3,   7,   9,   6,   9,   3,  10,   6,   6,
    40         -       4,   6,   3,   7,   6,   7,   5,  13,   2,   2,   5,   5,   6,
    41         -       7,   3,   7,   4,   4,   2,   7,   3,   8,   6,   4,   4,   7,
    42         -       6,   6,   8,  10,   9,   6,   5,  12,  12,  17,   4,   4,   6,
    43         -       8,   2,   4,   6,   5,   4,   5,   4,   4,   5,   6,   9,   6,
    44         -       7,   4,   2,   6,   3,   6,   4,   5,   7,   5,   8,   7,   5,
    45         -       5,   8,   3,   4,   5,   6,   5,   6,   6,   4,   5,
           40  +       4,   6,   7,   3,   6,   7,   5,  13,   2,   2,   5,   5,   6,
           41  +       7,   7,   3,   4,   4,   2,   7,   3,   8,   6,   4,   4,   7,
           42  +       6,   6,   8,  10,   9,   6,   5,  12,  17,  12,   4,   4,   6,
           43  +       8,   2,   4,   6,   5,   4,   5,   4,   4,   5,   6,   2,   9,
           44  +       6,   7,   4,   6,   2,   3,   6,   4,   5,   7,   5,   8,   7,
           45  +       5,   5,   8,   3,   4,   5,   6,   5,   6,   6,   4,   5,
    46     46     };
    47         -  static const unsigned short int aOffset[115] = {
           47  +  static const unsigned short int aOffset[116] = {
    48     48          0,   4,   7,  10,  10,  14,  19,  21,  26,  27,  32,  34,  36,
    49     49         42,  51,  52,  57,  61,  65,  67,  71,  74,  78,  86,  91,  94,
    50     50         99, 105, 108, 113, 118, 122, 128, 136, 141, 150, 152, 162, 167,
    51     51        172, 175, 177, 177, 181, 185, 187, 192, 194, 196, 205, 208, 212,
    52     52        218, 224, 224, 227, 230, 234, 236, 237, 241, 248, 254, 258, 262,
    53     53        269, 275, 281, 289, 296, 305, 311, 316, 328, 328, 344, 348, 352,
    54         -     358, 359, 366, 369, 373, 378, 381, 386, 390, 394, 397, 403, 412,
    55         -     418, 425, 428, 428, 431, 434, 440, 444, 448, 455, 459, 467, 474,
    56         -     479, 484, 492, 494, 498, 503, 509, 514, 520, 526, 529,
           54  +     358, 359, 366, 369, 373, 378, 381, 386, 390, 394, 397, 403, 405,
           55  +     414, 420, 427, 430, 430, 433, 436, 442, 446, 450, 457, 461, 469,
           56  +     476, 481, 486, 494, 496, 500, 505, 511, 516, 522, 528, 531,
    57     57     };
    58         -  static const unsigned char aCode[115] = {
           58  +  static const unsigned char aCode[116] = {
    59     59       TK_ABORT,      TK_TABLE,      TK_JOIN_KW,    TK_TEMP,       TK_TEMP,       
    60     60       TK_OR,         TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     
    61     61       TK_THEN,       TK_END,        TK_DEFAULT,    TK_TRANSACTION,TK_ON,         
    62     62       TK_JOIN_KW,    TK_ALTER,      TK_RAISE,      TK_EACH,       TK_CHECK,      
    63     63       TK_KEY,        TK_AFTER,      TK_REFERENCES, TK_ESCAPE,     TK_ELSE,       
    64     64       TK_EXCEPT,     TK_TRIGGER,    TK_LIKE_KW,    TK_EXPLAIN,    TK_INITIALLY,  
    65     65       TK_ALL,        TK_ANALYZE,    TK_EXCLUSIVE,  TK_EXISTS,     TK_STATEMENT,  
    66     66       TK_AND,        TK_DEFERRABLE, TK_ATTACH,     TK_HAVING,     TK_LIKE_KW,    
    67         -    TK_BEFORE,     TK_FOR,        TK_FOREIGN,    TK_IGNORE,     TK_REINDEX,    
           67  +    TK_BEFORE,     TK_FOREIGN,    TK_FOR,        TK_IGNORE,     TK_REINDEX,    
    68     68       TK_INDEX,      TK_AUTOINCR,   TK_TO,         TK_IN,         TK_BEGIN,      
    69         -    TK_JOIN_KW,    TK_RENAME,     TK_BETWEEN,    TK_NOT,        TK_NOTNULL,    
           69  +    TK_JOIN_KW,    TK_RENAME,     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        
    70     70       TK_NULL,       TK_LIKE_KW,    TK_BY,         TK_CASCADE,    TK_ASC,        
    71     71       TK_DEFERRED,   TK_DELETE,     TK_CASE,       TK_CAST,       TK_COLLATE,    
    72     72       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_CONSTRAINT, TK_INTERSECT,  
    73     73       TK_CREATE,     TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_CTIME_KW,   
    74     74       TK_PLAN,       TK_DESC,       TK_DETACH,     TK_DISTINCT,   TK_IS,         
    75     75       TK_DROP,       TK_PRAGMA,     TK_MATCH,      TK_FAIL,       TK_LIMIT,      
    76         -    TK_FROM,       TK_JOIN_KW,    TK_GROUP,      TK_UPDATE,     TK_IMMEDIATE,  
    77         -    TK_INSERT,     TK_INSTEAD,    TK_INTO,       TK_OF,         TK_OFFSET,     
    78         -    TK_SET,        TK_ISNULL,     TK_JOIN,       TK_ORDER,      TK_REPLACE,    
    79         -    TK_JOIN_KW,    TK_RESTRICT,   TK_PRIMARY,    TK_QUERY,      TK_JOIN_KW,    
    80         -    TK_ROLLBACK,   TK_ROW,        TK_WHEN,       TK_UNION,      TK_UNIQUE,     
    81         -    TK_USING,      TK_VACUUM,     TK_VALUES,     TK_VIEW,       TK_WHERE,      
           76  +    TK_FROM,       TK_JOIN_KW,    TK_GROUP,      TK_UPDATE,     TK_IF,         
           77  +    TK_IMMEDIATE,  TK_INSERT,     TK_INSTEAD,    TK_INTO,       TK_OFFSET,     
           78  +    TK_OF,         TK_SET,        TK_ISNULL,     TK_JOIN,       TK_ORDER,      
           79  +    TK_REPLACE,    TK_JOIN_KW,    TK_RESTRICT,   TK_PRIMARY,    TK_QUERY,      
           80  +    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_WHEN,       TK_UNION,      
           81  +    TK_UNIQUE,     TK_USING,      TK_VACUUM,     TK_VALUES,     TK_VIEW,       
           82  +    TK_WHERE,      
    82     83     };
    83     84     int h, i;
    84     85     if( n<2 ) return TK_ID;
    85     86     h = ((sqlite3UpperToLower[((unsigned char*)z)[0]]*4) ^
    86     87         (sqlite3UpperToLower[((unsigned char*)z)[n-1]]*3) ^
    87     88         n) % 127;
    88     89     for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
    89     90       if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
    90     91         return aCode[i];
    91     92       }
    92     93     }
    93     94     return TK_ID;
    94     95   }
    95         -int sqlite3KeywordCode(const char *z, int n){
    96         -  return keywordCode(z, n);
           96  +int sqlite3KeywordCode(const unsigned char *z, int n){
           97  +  return keywordCode((char*)z, n);
    97     98   }

Changes to SQLite.Interop/src/legacy.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** Main file for the SQLite library.  The routines in this file
    13     13   ** implement the programmer interface to the library.  Routines in
    14     14   ** other files are for internal use by SQLite and should not be
    15     15   ** accessed by users of the library.
    16     16   **
    17         -** $Id: legacy.c,v 1.10 2005/12/19 17:57:47 rmsimpson Exp $
           17  +** $Id: legacy.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    18     18   */
    19     19   
    20     20   #include "sqliteInt.h"
    21     21   #include "os.h"
    22     22   #include <ctype.h>
    23     23   
    24     24   /*
................................................................................
    66     66   
    67     67       db->nChange += nChange;
    68     68       nCallback = 0;
    69     69   
    70     70       nCol = sqlite3_column_count(pStmt);
    71     71       azCols = sqliteMalloc(2*nCol*sizeof(const char *));
    72     72       if( nCol && !azCols ){
    73         -      rc = SQLITE_NOMEM;
    74     73         goto exec_out;
    75     74       }
    76     75   
    77     76       while( 1 ){
    78     77         int i;
    79     78         rc = sqlite3_step(pStmt);
    80     79   
................................................................................
   118    117       azCols = 0;
   119    118     }
   120    119   
   121    120   exec_out:
   122    121     if( pStmt ) sqlite3_finalize(pStmt);
   123    122     if( azCols ) sqliteFree(azCols);
   124    123   
   125         -  if( sqlite3_malloc_failed ){
          124  +  if( sqlite3ThreadData()->mallocFailed ){
   126    125       rc = SQLITE_NOMEM;
          126  +    sqlite3MallocClearFailed();
   127    127     }
          128  +
   128    129     if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
   129    130       *pzErrMsg = malloc(1+strlen(sqlite3_errmsg(db)));
   130    131       if( *pzErrMsg ){
   131    132         strcpy(*pzErrMsg, sqlite3_errmsg(db));
   132    133       }
   133    134     }else if( pzErrMsg ){
   134    135       *pzErrMsg = 0;
   135    136     }
   136    137   
   137    138     return rc;
   138    139   }

Changes to SQLite.Interop/src/main.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** Main file for the SQLite library.  The routines in this file
    13     13   ** implement the programmer interface to the library.  Routines in
    14     14   ** other files are for internal use by SQLite and should not be
    15     15   ** accessed by users of the library.
    16     16   **
    17         -** $Id: main.c,v 1.10 2005/12/19 17:57:47 rmsimpson Exp $
           17  +** $Id: main.c,v 1.11 2006/01/10 18:40:37 rmsimpson Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   #include "os.h"
    21     21   #include <ctype.h>
    22     22   
    23     23   /*
    24     24   ** The following constant value is used by the SQLITE_BIGENDIAN and
    25     25   ** SQLITE_LITTLEENDIAN macros.
    26     26   */
    27     27   const int sqlite3one = 1;
    28     28   
    29         -#ifndef SQLITE_OMIT_GLOBALRECOVER
    30         -/*
    31         -** Linked list of all open database handles. This is used by the 
    32         -** sqlite3_global_recover() function. Entries are added to the list
    33         -** by openDatabase() and removed by sqlite3_close().
    34         -*/
    35         -static sqlite3 *pDbList = 0;
    36         -#endif
    37         -
    38         -#ifndef SQLITE_OMIT_UTF16
    39         -/* 
    40         -** Return the transient sqlite3_value object used for encoding conversions
    41         -** during SQL compilation.
    42         -*/
    43         -sqlite3_value *sqlite3GetTransientValue(sqlite3 *db){
    44         -  if( !db->pValue ){
    45         -    db->pValue = sqlite3ValueNew();
    46         -  }
    47         -  return db->pValue;
    48         -}
    49         -#endif
    50         -
    51     29   /*
    52     30   ** The version of the library
    53     31   */
    54     32   const char rcsid3[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
    55     33   const char sqlite3_version[] = SQLITE_VERSION;
    56     34   const char *sqlite3_libversion(void){ return sqlite3_version; }
    57     35   int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
................................................................................
   148    126     ** that case. But maybe there should be an extra magic value for the
   149    127     ** "failed to open" state.
   150    128     */
   151    129     if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){
   152    130       /* printf("DID NOT CLOSE\n"); fflush(stdout); */
   153    131       return SQLITE_ERROR;
   154    132     }
          133  +
          134  +  /* sqlite3_close() may not invoke sqliteMalloc(). */
          135  +  sqlite3MallocDisallow();
   155    136   
   156    137     for(j=0; j<db->nDb; j++){
   157    138       struct Db *pDb = &db->aDb[j];
   158    139       if( pDb->pBt ){
   159    140         sqlite3BtreeClose(pDb->pBt);
   160    141         pDb->pBt = 0;
          142  +      if( j!=1 ){
          143  +        pDb->pSchema = 0;
          144  +      }
   161    145       }
   162    146     }
   163    147     sqlite3ResetInternalSchema(db, 0);
   164    148     assert( db->nDb<=2 );
   165    149     assert( db->aDb==db->aDbStatic );
   166    150     for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
   167    151       FuncDef *pFunc, *pNext;
................................................................................
   175    159       CollSeq *pColl = (CollSeq *)sqliteHashData(i);
   176    160       sqliteFree(pColl);
   177    161     }
   178    162     sqlite3HashClear(&db->aCollSeq);
   179    163   
   180    164     sqlite3HashClear(&db->aFunc);
   181    165     sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
   182         -  if( db->pValue ){
   183         -    sqlite3ValueFree(db->pValue);
   184         -  }
   185    166     if( db->pErr ){
   186    167       sqlite3ValueFree(db->pErr);
   187    168     }
   188    169   
   189         -#ifndef SQLITE_OMIT_GLOBALRECOVER
   190         -  {
   191         -    sqlite3 *pPrev;
   192         -    sqlite3OsEnterMutex();
   193         -    pPrev = pDbList;
   194         -    while( pPrev && pPrev->pNext!=db ){
   195         -      pPrev = pPrev->pNext;
   196         -    }
   197         -    if( pPrev ){
   198         -      pPrev->pNext = db->pNext;
   199         -    }else{
   200         -      assert( pDbList==db );
   201         -      pDbList = db->pNext;
   202         -    }
   203         -    sqlite3OsLeaveMutex();
   204         -  }
   205         -#endif
   206         -
   207    170     db->magic = SQLITE_MAGIC_ERROR;
          171  +
          172  +  /* The temp-database schema is allocated differently from the other schema
          173  +  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
          174  +  ** So it needs to be freed here. Todo: Why not roll the temp schema into
          175  +  ** the same sqliteMalloc() as the one that allocates the database 
          176  +  ** structure?
          177  +  */
          178  +  sqliteFree(db->aDb[1].pSchema);
          179  +
   208    180     sqliteFree(db);
          181  +  sqlite3MallocAllow();
   209    182     return SQLITE_OK;
   210    183   }
   211    184   
   212    185   /*
   213    186   ** Rollback all database files.
   214    187   */
   215    188   void sqlite3RollbackAll(sqlite3 *db){
   216    189     int i;
          190  +  int inTrans = 0;
   217    191     for(i=0; i<db->nDb; i++){
   218    192       if( db->aDb[i].pBt ){
          193  +      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
          194  +        inTrans = 1;
          195  +      }
   219    196         sqlite3BtreeRollback(db->aDb[i].pBt);
   220    197         db->aDb[i].inTrans = 0;
   221    198       }
   222    199     }
   223         -  sqlite3ResetInternalSchema(db, 0);
          200  +  if( db->flags&SQLITE_InternChanges ){
          201  +    sqlite3ResetInternalSchema(db, 0);
          202  +  }
          203  +
          204  +  /* If one has been configured, invoke the rollback-hook callback */
          205  +  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
          206  +    db->xRollbackCallback(db->pRollbackArg);
          207  +  }
   224    208   }
   225    209   
   226    210   /*
   227    211   ** Return a static string that describes the kind of error specified in the
   228    212   ** argument.
   229    213   */
   230    214   const char *sqlite3ErrStr(int rc){
................................................................................
   486    470     int eTextRep,
   487    471     void *pUserData,
   488    472     void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   489    473     void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   490    474     void (*xFinal)(sqlite3_context*)
   491    475   ){
   492    476     int rc;
   493         -  char const *zFunc8;
   494         -  sqlite3_value *pTmp;
          477  +  char *zFunc8;
   495    478   
   496    479     if( sqlite3SafetyCheck(db) ){
   497    480       return SQLITE_MISUSE;
   498    481     }
   499         -  pTmp = sqlite3GetTransientValue(db);
   500         -  sqlite3ValueSetStr(pTmp, -1, zFunctionName, SQLITE_UTF16NATIVE,SQLITE_STATIC);
   501         -  zFunc8 = sqlite3ValueText(pTmp, SQLITE_UTF8);
   502         -
          482  +  zFunc8 = sqlite3utf16to8(zFunctionName, -1);
   503    483     if( !zFunc8 ){
   504    484       return SQLITE_NOMEM;
   505    485     }
   506    486     rc = sqlite3_create_function(db, zFunc8, nArg, eTextRep, 
   507    487         pUserData, xFunc, xStep, xFinal);
          488  +  sqliteFree(zFunc8);
   508    489     return rc;
   509    490   }
   510    491   #endif
   511    492   
   512    493   #ifndef SQLITE_OMIT_TRACE
   513    494   /*
   514    495   ** Register a trace function.  The pArg from the previously registered trace
................................................................................
   543    524     return pOld;
   544    525   }
   545    526   #endif /* SQLITE_OMIT_TRACE */
   546    527   
   547    528   /*** EXPERIMENTAL ***
   548    529   **
   549    530   ** Register a function to be invoked when a transaction comments.
   550         -** If either function returns non-zero, then the commit becomes a
          531  +** If the invoked function returns non-zero, then the commit becomes a
   551    532   ** rollback.
   552    533   */
   553    534   void *sqlite3_commit_hook(
   554    535     sqlite3 *db,              /* Attach the hook to this database */
   555    536     int (*xCallback)(void*),  /* Function to invoke on each commit */
   556    537     void *pArg                /* Argument to the function */
   557    538   ){
   558    539     void *pOld = db->pCommitArg;
   559    540     db->xCommitCallback = xCallback;
   560    541     db->pCommitArg = pArg;
   561    542     return pOld;
   562    543   }
   563    544   
          545  +/*
          546  +** Register a callback to be invoked each time a row is updated,
          547  +** inserted or deleted using this database connection.
          548  +*/
          549  +void *sqlite3_update_hook(
          550  +  sqlite3 *db,              /* Attach the hook to this database */
          551  +  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
          552  +  void *pArg                /* Argument to the function */
          553  +){
          554  +  void *pRet = db->pUpdateArg;
          555  +  db->xUpdateCallback = xCallback;
          556  +  db->pUpdateArg = pArg;
          557  +  return pRet;
          558  +}
          559  +
          560  +/*
          561  +** Register a callback to be invoked each time a transaction is rolled
          562  +** back by this database connection.
          563  +*/
          564  +void *sqlite3_rollback_hook(
          565  +  sqlite3 *db,              /* Attach the hook to this database */
          566  +  void (*xCallback)(void*), /* Callback function */
          567  +  void *pArg                /* Argument to the function */
          568  +){
          569  +  void *pRet = db->pRollbackArg;
          570  +  db->xRollbackCallback = xCallback;
          571  +  db->pRollbackArg = pArg;
          572  +  return pRet;
          573  +}
   564    574   
   565    575   /*
   566    576   ** This routine is called to create a connection to a database BTree
   567    577   ** driver.  If zFilename is the name of a file, then that file is
   568    578   ** opened and used.  If zFilename is the magic name ":memory:" then
   569    579   ** the database is stored in memory (and is thus forgotten as soon as
   570    580   ** the connection is closed.)  If zFilename is NULL then the database
................................................................................
   617    627   #endif
   618    628   #if TEMP_STORE==3
   619    629       zFilename = ":memory:";
   620    630   #endif
   621    631   #endif /* SQLITE_OMIT_MEMORYDB */
   622    632     }
   623    633   
   624         -  rc = sqlite3BtreeOpen(zFilename, ppBtree, btree_flags);
          634  +  rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btree_flags);
   625    635     if( rc==SQLITE_OK ){
   626    636       sqlite3BtreeSetBusyHandler(*ppBtree, (void*)&db->busyHandler);
   627    637       sqlite3BtreeSetCacheSize(*ppBtree, nCache);
   628    638     }
   629    639     return rc;
   630    640   }
   631    641   
   632    642   /*
   633    643   ** Return UTF-8 encoded English language explanation of the most recent
   634    644   ** error.
   635    645   */
   636    646   const char *sqlite3_errmsg(sqlite3 *db){
   637    647     const char *z;
   638         -  if( sqlite3_malloc_failed ){
          648  +  if( sqlite3ThreadData()->mallocFailed ){
   639    649       return sqlite3ErrStr(SQLITE_NOMEM);
   640    650     }
   641    651     if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
   642    652       return sqlite3ErrStr(SQLITE_MISUSE);
   643    653     }
   644         -  z = sqlite3_value_text(db->pErr);
          654  +  z = (char*)sqlite3_value_text(db->pErr);
   645    655     if( z==0 ){
   646    656       z = sqlite3ErrStr(db->errCode);
   647    657     }
   648    658     return z;
   649    659   }
   650    660   
   651    661   #ifndef SQLITE_OMIT_UTF16
................................................................................
   670    680       0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
   671    681       0, 'o', 0, 'u', 0, 't', 0, ' ', 
   672    682       0, 'o', 0, 'f', 0, ' ', 
   673    683       0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
   674    684     };
   675    685   
   676    686     const void *z;
   677         -  if( sqlite3_malloc_failed ){
          687  +  if( sqlite3ThreadData()->mallocFailed ){
   678    688       return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
   679    689     }
   680    690     if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
   681    691       return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
   682    692     }
   683    693     z = sqlite3_value_text16(db->pErr);
   684    694     if( z==0 ){
................................................................................
   687    697       z = sqlite3_value_text16(db->pErr);
   688    698     }
   689    699     return z;
   690    700   }
   691    701   #endif /* SQLITE_OMIT_UTF16 */
   692    702   
   693    703   /*
   694         -** Return the most recent error code generated by an SQLite routine.
          704  +** Return the most recent error code generated by an SQLite routine. If NULL is
          705  +** passed to this function, we assume a malloc() failed during sqlite3_open().
   695    706   */
   696    707   int sqlite3_errcode(sqlite3 *db){
   697         -  if( sqlite3_malloc_failed ){
          708  +  if( !db || sqlite3ThreadData()->mallocFailed ){
   698    709       return SQLITE_NOMEM;
   699    710     }
   700    711     if( sqlite3SafetyCheck(db) ){
   701    712       return SQLITE_MISUSE;
   702    713     }
   703    714     return db->errCode;
   704    715   }
................................................................................
   709    720   ** is UTF-8 encoded.
   710    721   */
   711    722   static int openDatabase(
   712    723     const char *zFilename, /* Database filename UTF-8 encoded */
   713    724     sqlite3 **ppDb         /* OUT: Returned database handle */
   714    725   ){
   715    726     sqlite3 *db;
   716         -  int rc, i;
          727  +  int rc;
   717    728     CollSeq *pColl;
          729  +
          730  +  assert( !sqlite3ThreadData()->mallocFailed );
   718    731   
   719    732     /* Allocate the sqlite data structure */
   720    733     db = sqliteMalloc( sizeof(sqlite3) );
   721    734     if( db==0 ) goto opendb_out;
   722    735     db->priorNewRowid = 0;
   723    736     db->magic = SQLITE_MAGIC_BUSY;
   724    737     db->nDb = 2;
   725    738     db->aDb = db->aDbStatic;
   726         -  db->enc = SQLITE_UTF8;
   727    739     db->autoCommit = 1;
   728    740     db->flags |= SQLITE_ShortColNames;
   729    741     sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
   730    742     sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
          743  +
          744  +#if 0
   731    745     for(i=0; i<db->nDb; i++){
   732    746       sqlite3HashInit(&db->aDb[i].tblHash, SQLITE_HASH_STRING, 0);
   733    747       sqlite3HashInit(&db->aDb[i].idxHash, SQLITE_HASH_STRING, 0);
   734    748       sqlite3HashInit(&db->aDb[i].trigHash, SQLITE_HASH_STRING, 0);
   735    749       sqlite3HashInit(&db->aDb[i].aFKey, SQLITE_HASH_STRING, 1);
   736    750     }
   737         -  
          751  +#endif
          752  + 
   738    753     /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   739    754     ** and UTF-16, so add a version for each to avoid any unnecessary
   740    755     ** conversions. The only error that can occur here is a malloc() failure.
   741    756     */
   742    757     if( sqlite3_create_collation(db, "BINARY", SQLITE_UTF8, 0,binCollFunc) ||
   743    758         sqlite3_create_collation(db, "BINARY", SQLITE_UTF16, 0,binCollFunc) ||
   744         -      !(db->pDfltColl = sqlite3FindCollSeq(db, db->enc, "BINARY", 6, 0)) ){
   745         -    rc = db->errCode;
   746         -    assert( rc!=SQLITE_OK );
          759  +      (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0 
          760  +  ){
          761  +    /* sqlite3_create_collation() is an external API. So the mallocFailed flag
          762  +    ** will have been cleared before returning. So set it explicitly here.
          763  +    */
          764  +    sqlite3ThreadData()->mallocFailed = 1;
   747    765       db->magic = SQLITE_MAGIC_CLOSED;
   748    766       goto opendb_out;
   749    767     }
   750    768   
   751    769     /* Also add a UTF-8 case-insensitive collation sequence. */
   752    770     sqlite3_create_collation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc);
   753    771   
................................................................................
   761    779     /* Open the backend database driver */
   762    780     rc = sqlite3BtreeFactory(db, zFilename, 0, MAX_PAGES, &db->aDb[0].pBt);
   763    781     if( rc!=SQLITE_OK ){
   764    782       sqlite3Error(db, rc, 0);
   765    783       db->magic = SQLITE_MAGIC_CLOSED;
   766    784       goto opendb_out;
   767    785     }
          786  +#ifndef SQLITE_OMIT_PARSER
          787  +  db->aDb[0].pSchema = sqlite3SchemaGet(db->aDb[0].pBt);
          788  +  db->aDb[1].pSchema = sqlite3SchemaGet(0);
          789  +#endif
          790  +
          791  +  if( db->aDb[0].pSchema ){
          792  +    ENC(db) = SQLITE_UTF8;
          793  +  }
   768    794   
   769    795     /* The default safety_level for the main database is 'full'; for the temp
   770    796     ** database it is 'NONE'. This matches the pager layer defaults.  
   771    797     */
   772    798     db->aDb[0].zName = "main";
   773    799     db->aDb[0].safety_level = 3;
   774    800   #ifndef SQLITE_OMIT_TEMPDB
   775    801     db->aDb[1].zName = "temp";
   776    802     db->aDb[1].safety_level = 1;
   777    803   #endif
   778    804   
   779         -
   780    805     /* Register all built-in functions, but do not attempt to read the
   781    806     ** database schema yet. This is delayed until the first time the database
   782    807     ** is accessed.
   783    808     */
   784    809     sqlite3RegisterBuiltinFunctions(db);
   785    810     sqlite3Error(db, SQLITE_OK, 0);
   786    811     db->magic = SQLITE_MAGIC_OPEN;
   787    812   
   788    813   opendb_out:
   789         -  if( sqlite3_errcode(db)==SQLITE_OK && sqlite3_malloc_failed ){
   790         -    sqlite3Error(db, SQLITE_NOMEM, 0);
          814  +  if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
          815  +    sqlite3_close(db);
          816  +    db = 0;
   791    817     }
   792    818     *ppDb = db;
   793         -#ifndef SQLITE_OMIT_GLOBALRECOVER
   794         -  if( db ){
   795         -    sqlite3OsEnterMutex();
   796         -    db->pNext = pDbList;
   797         -    pDbList = db;
   798         -    sqlite3OsLeaveMutex();
   799         -  }
   800         -#endif
   801         -  return sqlite3_errcode(db);
          819  +  sqlite3MallocClearFailed();
          820  +  return rc;
   802    821   }
   803    822   
   804    823   /*
   805    824   ** Open a new database handle.
   806    825   */
   807    826   int sqlite3_open(
   808    827     const char *zFilename, 
................................................................................
   819    838     const void *zFilename, 
   820    839     sqlite3 **ppDb
   821    840   ){
   822    841     char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
   823    842     int rc = SQLITE_NOMEM;
   824    843     sqlite3_value *pVal;
   825    844   
          845  +  assert( zFilename );
   826    846     assert( ppDb );
   827    847     *ppDb = 0;
   828    848     pVal = sqlite3ValueNew();
   829    849     sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   830    850     zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   831    851     if( zFilename8 ){
   832    852       rc = openDatabase(zFilename8, ppDb);
   833    853       if( rc==SQLITE_OK && *ppDb ){
   834         -      sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
          854  +      rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
   835    855       }
   836         -  }
   837         -  if( pVal ){
   838         -    sqlite3ValueFree(pVal);
          856  +  }else{
          857  +    assert( sqlite3ThreadData()->mallocFailed );
          858  +    sqlite3MallocClearFailed();
   839    859     }
          860  +  sqlite3ValueFree(pVal);
   840    861   
   841    862     return rc;
   842    863   }
   843    864   #endif /* SQLITE_OMIT_UTF16 */
   844    865   
   845    866   /*
   846    867   ** The following routine destroys a virtual machine that is created by
................................................................................
   946    967   int sqlite3_create_collation16(
   947    968     sqlite3* db, 
   948    969     const char *zName, 
   949    970     int enc, 
   950    971     void* pCtx,
   951    972     int(*xCompare)(void*,int,const void*,int,const void*)
   952    973   ){
   953         -  char const *zName8;
   954         -  sqlite3_value *pTmp;
          974  +  char *zName8;
          975  +  int rc;
   955    976     if( sqlite3SafetyCheck(db) ){
   956    977       return SQLITE_MISUSE;
   957    978     }
   958         -  pTmp = sqlite3GetTransientValue(db);
   959         -  sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   960         -  zName8 = sqlite3ValueText(pTmp, SQLITE_UTF8);
   961         -  return sqlite3_create_collation(db, zName8, enc, pCtx, xCompare);
          979  +  zName8 = sqlite3utf16to8(zName, -1);
          980  +  rc = sqlite3_create_collation(db, zName8, enc, pCtx, xCompare);
          981  +  sqliteFree(zName8);
          982  +  return rc;
   962    983   }
   963    984   #endif /* SQLITE_OMIT_UTF16 */
   964    985   
   965    986   /*
   966    987   ** Register a collation sequence factory callback with the database handle
   967    988   ** db. Replace any previously installed collation sequence factory.
   968    989   */
................................................................................
   998   1019     db->pCollNeededArg = pCollNeededArg;
   999   1020     return SQLITE_OK;
  1000   1021   }
  1001   1022   #endif /* SQLITE_OMIT_UTF16 */
  1002   1023   
  1003   1024   #ifndef SQLITE_OMIT_GLOBALRECOVER
  1004   1025   /*
  1005         -** This function is called to recover from a malloc failure that occured
  1006         -** within SQLite. 
  1007         -**
  1008         -** This function is *not* threadsafe. Calling this from within a threaded
  1009         -** application when threads other than the caller have used SQLite is 
  1010         -** dangerous and will almost certainly result in malfunctions.
         1026  +** This function is now an anachronism. It used to be used to recover from a
         1027  +** malloc() failure, but SQLite now does this automatically.
  1011   1028   */
  1012   1029   int sqlite3_global_recover(){
  1013         -  int rc = SQLITE_OK;
  1014         -
  1015         -  if( sqlite3_malloc_failed ){
  1016         -    sqlite3 *db;
  1017         -    int i;
  1018         -    sqlite3_malloc_failed = 0;
  1019         -    for(db=pDbList; db; db=db->pNext ){
  1020         -      sqlite3ExpirePreparedStatements(db);
  1021         -      for(i=0; i<db->nDb; i++){
  1022         -        Btree *pBt = db->aDb[i].pBt;
  1023         -        if( pBt && (rc=sqlite3BtreeReset(pBt)) ){
  1024         -          goto recover_out;
  1025         -        }
  1026         -      } 
  1027         -      db->autoCommit = 1;
  1028         -    }
  1029         -  }
  1030         -
  1031         -recover_out:
  1032         -  if( rc!=SQLITE_OK ){
  1033         -    sqlite3_malloc_failed = 1;
  1034         -  }
  1035         -  return rc;
         1030  +  return SQLITE_OK;
  1036   1031   }
  1037   1032   #endif
  1038   1033   
  1039   1034   /*
  1040   1035   ** Test to see whether or not the database connection is in autocommit
  1041   1036   ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
  1042   1037   ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
................................................................................
  1054   1049   ** debugging builds.  This provides a way to set a breakpoint for when
  1055   1050   ** corruption is first detected.
  1056   1051   */
  1057   1052   int sqlite3Corrupt(void){
  1058   1053     return SQLITE_CORRUPT;
  1059   1054   }
  1060   1055   #endif
         1056  +
         1057  +
         1058  +#ifndef SQLITE_OMIT_SHARED_CACHE
         1059  +/*
         1060  +** Enable or disable the shared pager and schema features for the
         1061  +** current thread.
         1062  +**
         1063  +** This routine should only be called when there are no open
         1064  +** database connections.
         1065  +*/
         1066  +int sqlite3_enable_shared_cache(int enable){
         1067  +  ThreadData *pTd = sqlite3ThreadData();
         1068  +  
         1069  +  /* It is only legal to call sqlite3_enable_shared_cache() when there
         1070  +  ** are no currently open b-trees that were opened by the calling thread.
         1071  +  ** This condition is only easy to detect if the shared-cache were 
         1072  +  ** previously enabled (and is being disabled). 
         1073  +  */
         1074  +  if( pTd->pBtree && !enable ){
         1075  +    assert( pTd->useSharedData );
         1076  +    return SQLITE_MISUSE;
         1077  +  }
         1078  +
         1079  +  pTd->useSharedData = enable;
         1080  +  return SQLITE_OK;
         1081  +}
         1082  +#endif

Added SQLite.Interop/src/md5.c.

            1  +/*
            2  +** SQLite uses this code for testing only.  It is not a part of
            3  +** the SQLite library.  This file implements two new TCL commands
            4  +** "md5" and "md5file" that compute md5 checksums on arbitrary text
            5  +** and on complete files.  These commands are used by the "testfixture"
            6  +** program to help verify the correct operation of the SQLite library.
            7  +**
            8  +** The original use of these TCL commands was to test the ROLLBACK
            9  +** feature of SQLite.  First compute the MD5-checksum of the database.
           10  +** Then make some changes but rollback the changes rather than commit
           11  +** them.  Compute a second MD5-checksum of the file and verify that the
           12  +** two checksums are the same.  Such is the original use of this code.
           13  +** New uses may have been added since this comment was written.
           14  +*/
           15  +/*
           16  + * This code implements the MD5 message-digest algorithm.
           17  + * The algorithm is due to Ron Rivest.  This code was
           18  + * written by Colin Plumb in 1993, no copyright is claimed.
           19  + * This code is in the public domain; do with it what you wish.
           20  + *
           21  + * Equivalent code is available from RSA Data Security, Inc.
           22  + * This code has been tested against that, and is equivalent,
           23  + * except that you don't need to include two pages of legalese
           24  + * with every copy.
           25  + *
           26  + * To compute the message digest of a chunk of bytes, declare an
           27  + * MD5Context structure, pass it to MD5Init, call MD5Update as
           28  + * needed on buffers full of bytes, and then call MD5Final, which
           29  + * will fill a supplied 16-byte array with the digest.
           30  + */
           31  +#include <tcl.h>
           32  +#include <string.h>
           33  +#include "sqlite3.h"
           34  +
           35  +/*
           36  + * If compiled on a machine that doesn't have a 32-bit integer,
           37  + * you just set "uint32" to the appropriate datatype for an
           38  + * unsigned 32-bit integer.  For example:
           39  + *
           40  + *       cc -Duint32='unsigned long' md5.c
           41  + *
           42  + */
           43  +#ifndef uint32
           44  +#  define uint32 unsigned int
           45  +#endif
           46  +
           47  +struct Context {
           48  +  uint32 buf[4];
           49  +  uint32 bits[2];
           50  +  unsigned char in[64];
           51  +};
           52  +typedef char MD5Context[88];
           53  +
           54  +/*
           55  + * Note: this code is harmless on little-endian machines.
           56  + */
           57  +static void byteReverse (unsigned char *buf, unsigned longs){
           58  +        uint32 t;
           59  +        do {
           60  +                t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
           61  +                            ((unsigned)buf[1]<<8 | buf[0]);
           62  +                *(uint32 *)buf = t;
           63  +                buf += 4;
           64  +        } while (--longs);
           65  +}
           66  +/* The four core functions - F1 is optimized somewhat */
           67  +
           68  +/* #define F1(x, y, z) (x & y | ~x & z) */
           69  +#define F1(x, y, z) (z ^ (x & (y ^ z)))
           70  +#define F2(x, y, z) F1(z, x, y)
           71  +#define F3(x, y, z) (x ^ y ^ z)
           72  +#define F4(x, y, z) (y ^ (x | ~z))
           73  +
           74  +/* This is the central step in the MD5 algorithm. */
           75  +#define MD5STEP(f, w, x, y, z, data, s) \
           76  +        ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
           77  +
           78  +/*
           79  + * The core of the MD5 algorithm, this alters an existing MD5 hash to
           80  + * reflect the addition of 16 longwords of new data.  MD5Update blocks
           81  + * the data and converts bytes into longwords for this routine.
           82  + */
           83  +static void MD5Transform(uint32 buf[4], const uint32 in[16]){
           84  +        register uint32 a, b, c, d;
           85  +
           86  +        a = buf[0];
           87  +        b = buf[1];
           88  +        c = buf[2];
           89  +        d = buf[3];
           90  +
           91  +        MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
           92  +        MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
           93  +        MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
           94  +        MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
           95  +        MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
           96  +        MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
           97  +        MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
           98  +        MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
           99  +        MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
          100  +        MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
          101  +        MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
          102  +        MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
          103  +        MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
          104  +        MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
          105  +        MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
          106  +        MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
          107  +
          108  +        MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
          109  +        MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
          110  +        MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
          111  +        MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
          112  +        MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
          113  +        MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
          114  +        MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
          115  +        MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
          116  +        MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
          117  +        MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
          118  +        MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
          119  +        MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
          120  +        MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
          121  +        MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
          122  +        MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
          123  +        MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
          124  +
          125  +        MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
          126  +        MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
          127  +        MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
          128  +        MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
          129  +        MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
          130  +        MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
          131  +        MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
          132  +        MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
          133  +        MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
          134  +        MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
          135  +        MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
          136  +        MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
          137  +        MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
          138  +        MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
          139  +        MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
          140  +        MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
          141  +
          142  +        MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
          143  +        MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
          144  +        MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
          145  +        MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
          146  +        MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
          147  +        MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
          148  +        MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
          149  +        MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
          150  +        MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
          151  +        MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
          152  +        MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
          153  +        MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
          154  +        MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
          155  +        MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
          156  +        MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
          157  +        MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
          158  +
          159  +        buf[0] += a;
          160  +        buf[1] += b;
          161  +        buf[2] += c;
          162  +        buf[3] += d;
          163  +}
          164  +
          165  +/*
          166  + * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
          167  + * initialization constants.
          168  + */
          169  +static void MD5Init(MD5Context *pCtx){
          170  +        struct Context *ctx = (struct Context *)pCtx;
          171  +        ctx->buf[0] = 0x67452301;
          172  +        ctx->buf[1] = 0xefcdab89;
          173  +        ctx->buf[2] = 0x98badcfe;
          174  +        ctx->buf[3] = 0x10325476;
          175  +        ctx->bits[0] = 0;
          176  +        ctx->bits[1] = 0;
          177  +}
          178  +
          179  +/*
          180  + * Update context to reflect the concatenation of another buffer full
          181  + * of bytes.
          182  + */
          183  +static 
          184  +void MD5Update(MD5Context *pCtx, const unsigned char *buf, unsigned int len){
          185  +        struct Context *ctx = (struct Context *)pCtx;
          186  +        uint32 t;
          187  +
          188  +        /* Update bitcount */
          189  +
          190  +        t = ctx->bits[0];
          191  +        if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
          192  +                ctx->bits[1]++; /* Carry from low to high */
          193  +        ctx->bits[1] += len >> 29;
          194  +
          195  +        t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
          196  +
          197  +        /* Handle any leading odd-sized chunks */
          198  +
          199  +        if ( t ) {
          200  +                unsigned char *p = (unsigned char *)ctx->in + t;
          201  +
          202  +                t = 64-t;
          203  +                if (len < t) {
          204  +                        memcpy(p, buf, len);
          205  +                        return;
          206  +                }
          207  +                memcpy(p, buf, t);
          208  +                byteReverse(ctx->in, 16);
          209  +                MD5Transform(ctx->buf, (uint32 *)ctx->in);
          210  +                buf += t;
          211  +                len -= t;
          212  +        }
          213  +
          214  +        /* Process data in 64-byte chunks */
          215  +
          216  +        while (len >= 64) {
          217  +                memcpy(ctx->in, buf, 64);
          218  +                byteReverse(ctx->in, 16);
          219  +                MD5Transform(ctx->buf, (uint32 *)ctx->in);
          220  +                buf += 64;
          221  +                len -= 64;
          222  +        }
          223  +
          224  +        /* Handle any remaining bytes of data. */
          225  +
          226  +        memcpy(ctx->in, buf, len);
          227  +}
          228  +
          229  +/*
          230  + * Final wrapup - pad to 64-byte boundary with the bit pattern 
          231  + * 1 0* (64-bit count of bits processed, MSB-first)
          232  + */
          233  +static void MD5Final(unsigned char digest[16], MD5Context *pCtx){
          234  +        struct Context *ctx = (struct Context *)pCtx;
          235  +        unsigned count;
          236  +        unsigned char *p;
          237  +
          238  +        /* Compute number of bytes mod 64 */
          239  +        count = (ctx->bits[0] >> 3) & 0x3F;
          240  +
          241  +        /* Set the first char of padding to 0x80.  This is safe since there is
          242  +           always at least one byte free */
          243  +        p = ctx->in + count;
          244  +        *p++ = 0x80;
          245  +
          246  +        /* Bytes of padding needed to make 64 bytes */
          247  +        count = 64 - 1 - count;
          248  +
          249  +        /* Pad out to 56 mod 64 */
          250  +        if (count < 8) {
          251  +                /* Two lots of padding:  Pad the first block to 64 bytes */
          252  +                memset(p, 0, count);
          253  +                byteReverse(ctx->in, 16);
          254  +                MD5Transform(ctx->buf, (uint32 *)ctx->in);
          255  +
          256  +                /* Now fill the next block with 56 bytes */
          257  +                memset(ctx->in, 0, 56);
          258  +        } else {
          259  +                /* Pad block to 56 bytes */
          260  +                memset(p, 0, count-8);
          261  +        }
          262  +        byteReverse(ctx->in, 14);
          263  +
          264  +        /* Append length in bits and transform */
          265  +        ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
          266  +        ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
          267  +
          268  +        MD5Transform(ctx->buf, (uint32 *)ctx->in);
          269  +        byteReverse((unsigned char *)ctx->buf, 4);
          270  +        memcpy(digest, ctx->buf, 16);
          271  +        memset(ctx, 0, sizeof(ctx));    /* In case it's sensitive */
          272  +}
          273  +
          274  +/*
          275  +** Convert a digest into base-16.  digest should be declared as
          276  +** "unsigned char digest[16]" in the calling function.  The MD5
          277  +** digest is stored in the first 16 bytes.  zBuf should
          278  +** be "char zBuf[33]".
          279  +*/
          280  +static void DigestToBase16(unsigned char *digest, char *zBuf){
          281  +  static char const zEncode[] = "0123456789abcdef";
          282  +  int i, j;
          283  +
          284  +  for(j=i=0; i<16; i++){
          285  +    int a = digest[i];
          286  +    zBuf[j++] = zEncode[(a>>4)&0xf];
          287  +    zBuf[j++] = zEncode[a & 0xf];
          288  +  }
          289  +  zBuf[j] = 0;
          290  +}
          291  +
          292  +/*
          293  +** A TCL command for md5.  The argument is the text to be hashed.  The
          294  +** Result is the hash in base64.  
          295  +*/
          296  +static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
          297  +  MD5Context ctx;
          298  +  unsigned char digest[16];
          299  +
          300  +  if( argc!=2 ){
          301  +    Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0], 
          302  +        " TEXT\"", 0);
          303  +    return TCL_ERROR;
          304  +  }
          305  +  MD5Init(&ctx);
          306  +  MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
          307  +  MD5Final(digest, &ctx);
          308  +  DigestToBase16(digest, interp->result);
          309  +  return TCL_OK;
          310  +}
          311  +
          312  +/*
          313  +** A TCL command to take the md5 hash of a file.  The argument is the
          314  +** name of the file.
          315  +*/
          316  +static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
          317  +  FILE *in;
          318  +  MD5Context ctx;
          319  +  unsigned char digest[16];
          320  +  char zBuf[10240];
          321  +